From 451a3400b76511393c62a444f588a4ed15f4a549 Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 19 Feb 2017 10:28:42 +0200 Subject: Initial OpenECOMP SDC commit Change-Id: I0924d5a6ae9cdc161ae17c68d3689a30d10f407b Signed-off-by: Michael Lando --- .../org/openecomp/sdc/AuditingMockManager.java | 44 + .../org/openecomp/sdc/ElementOperationMock.java | 266 ++++ .../org/openecomp/sdc/ErrorConfigurationTest.java | 77 + .../openecomp/sdc/TestExternalConfiguration.java | 63 + .../src/test/java/org/openecomp/sdc/ZipUtil.java | 132 ++ .../sdc/be/components/AuditingManagerTest.java | 79 + .../sdc/be/components/BaseConfDependentTest.java | 48 + .../be/components/ComponentBusinessLogicTest.java | 61 + .../components/HealthCheckBusinessLogicTest.java | 91 ++ .../be/components/PropertyBusinessLogicTest.java | 189 +++ .../be/components/ResourceImportManagerTest.java | 369 +++++ .../sdc/be/components/ResourceTestUtils.java | 90 ++ .../be/components/ServiceBusinessLogicTest.java | 931 ++++++++++++ .../engine/DistributionEngineConfigTest.java | 168 +++ .../engine/DistributionEngineHealthCheckTest.java | 138 ++ .../engine/DistributionEngineInitTaskTest.java | 269 ++++ .../components/impl/ArtifactBusinessLogicTest.java | 234 +++ .../impl/CapabilityTypeImportManagerTest.java | 105 ++ .../impl/CategoriesImportManagerTest.java | 111 ++ .../impl/CompositionBusinessLogicTest.java | 155 ++ .../components/impl/CsarValidationUtilsTest.java | 37 + .../sdc/be/components/impl/ImportUtilsTest.java | 509 +++++++ .../InterfaceLifecycleTypeImportManagerTest.java | 94 ++ .../components/impl/ResourceBusinessLogicTest.java | 1423 ++++++++++++++++++ .../impl/ResourceInstanceBusinessLogicTest.java | 284 ++++ .../CertificationChangeTransitionTest.java | 169 +++ .../lifecycle/CertificationRequestTest.java | 230 +++ .../sdc/be/components/lifecycle/CheckinTest.java | 170 +++ .../sdc/be/components/lifecycle/CheckoutTest.java | 188 +++ .../be/components/lifecycle/LifecycleTestBase.java | 215 +++ .../be/components/lifecycle/UndoCheckoutTest.java | 125 ++ .../DistributionBusinessLogicTest.java | 192 +++ .../servlet/DistributionServletTest.java | 159 ++ .../sdc/be/ecomp/GenerateEcompErrorFileTest.java | 77 + .../servlets/AbstractValidationsServletTest.java | 72 + .../sdc/be/servlets/ApplicationConfig.java | 62 + .../sdc/be/servlets/ResourceServletTest.java | 268 ++++ .../sdc/be/servlets/ResourceUploadServletTest.java | 189 +++ .../sdc/be/servlets/TypesUploadServletTest.java | 154 ++ .../sdc/be/servlets/UserAdminServletTest.java | 148 ++ .../sdc/be/user/UserAdminManagerTest.java | 91 ++ .../transaction/mngr/SdncTransactionTest.java | 437 ++++++ .../resources/config/catalog-be/configuration.yaml | 427 ++++++ .../distribution-engine-configuration.yaml | 43 + .../catalog-be/ecomp-error-configuration.yaml | 383 +++++ .../config/catalog-be/error-configuration.yaml | 1583 ++++++++++++++++++++ .../catalog-be/neo4j-errors-configuration.yaml | 60 + .../config/catalog-be/users-configuration.yaml | 2 + .../src/test/resources/config/configuration1.yaml | 17 + .../src/test/resources/config/elasticsearch.yml | 387 +++++ .../test/resources/config/elasticsearch.yml.bak | 387 +++++ .../resources/config/mysql-type-empty-nodes.zip | Bin 0 -> 1894 bytes .../test/resources/config/mysql-type-no-nodes.zip | Bin 0 -> 448 bytes .../resources/config/mysql-type-no-version.zip | Bin 0 -> 1142 bytes .../test/resources/config/mysql-type-only-yaml.zip | Bin 0 -> 1129 bytes .../resources/config/mysql-type-with-scripts.zip | Bin 0 -> 66267 bytes .../src/test/resources/config/mysql-type.yml | 82 + .../src/test/resources/config/mysql-type.zip | Bin 0 -> 1129 bytes .../test/resources/config/normative-types-root.zip | Bin 0 -> 1638 bytes catalog-be/src/test/resources/config/sample.yaml | 17 + .../test/resources/config/sampleNoProtocol.yaml | 17 + catalog-be/src/test/resources/elasticsearch.yml | 391 +++++ catalog-be/src/test/resources/logback-test.xml | 13 + catalog-be/src/test/resources/mock_vf.csar | Bin 0 -> 1316 bytes .../normativeTypes/importToscaProperties.yml | 452 ++++++ .../normativeTypes/importToscaWithAttribute.yml | 41 + .../normative-types-all-map-test.yml | 30 + .../normativeTypes/normative-types-new-DBMS.yml | 17 + .../normativeTypes/normative-types-new-Root.yml | 23 + .../normative-types-new-blockStorage.yml | 18 + .../normativeTypes/normative-types-new-compute.yml | 35 + .../normative-types-new-database.yml | 27 + .../normativeTypes/normative-types-new-port.yml | 31 + .../normative-types-new-softwareComponent.yml | 17 + .../normative-types-new-webServer.yml | 11 + .../normative-types-string-list-test.yml | 29 + .../topology_template_duplicateNode.yml | 23 + .../normativeTypes/topology_template_empty.yml | 17 + .../normativeTypes/topology_template_inputs.yml | 103 ++ .../normativeTypes/topology_template_nodeEmpty.yml | 18 + .../normativeTypes/topology_template_nodeVF.yml | 38 + .../topology_template_notValidNode.yml | 36 + .../topology_template_notValidRelationNode.yml | 36 + .../normativeTypes/topology_template_sample.yml | 36 + .../src/test/resources/types/capabilityTypes.yml | 148 ++ .../src/test/resources/types/capabilityTypes.zip | Bin 0 -> 979 bytes .../src/test/resources/types/categoryTypes.yml | 74 + .../src/test/resources/types/categoryTypes.zip | Bin 0 -> 403 bytes .../dataTypeDeriveFromIntegerWithProperty.yml | 8 + .../dataTypeDerivedFromRootNoProperties.yml | 4 + .../types/datatypes/dataTypeDuplicateProperty.yml | 11 + .../resources/types/datatypes/dataTypeForGroup.yml | 40 + .../dataTypeUpdatePropertyRemoved_part1.yml | 15 + .../dataTypeUpdatePropertyRemoved_part2.yml | 12 + ...ypeUpdateWithDifferentDerivedDataType_part1.yml | 19 + ...ypeUpdateWithDifferentDerivedDataType_part2.yml | 19 + .../dataTypeUpdateWithDifferentEntryType_part1.yml | 20 + .../dataTypeUpdateWithDifferentEntryType_part2.yml | 20 + ...taTypeUpdateWithDifferentPropertyType_part1.yml | 22 + ...taTypeUpdateWithDifferentPropertyType_part2.yml | 19 + ...ateWithExistingPropertyNameInAncestor_part1.yml | 19 + ...ateWithExistingPropertyNameInAncestor_part2.yml | 25 + .../dataTypeWithPropertyTypeThisDataType.yml | 9 + .../test/resources/types/datatypes/dataTypes.yml | 129 ++ .../types/datatypes/derived3levelDataType.yml | 37 + .../resources/types/datatypes/derivedDataType.yml | 19 + .../datatypes/derivedDataTypeNoProperties.yml | 15 + .../types/datatypes/derivedInvalidDataType.yml | 15 + .../resources/types/datatypes/emptyDataType.yml | 4 + .../datatypes/emptyDataTypeNoPropertiesTag.yml | 3 + .../types/datatypes/exitingPropertyAtAncestor.yml | 19 + .../resources/types/datatypes/invalidDataType.yml | 1 + .../test/resources/types/datatypes/oneDataType.yml | 9 + .../resources/types/interfaceLifecycleTypes.yml | 11 + .../resources/types/interfaceLifecycleTypes.zip | Bin 0 -> 273 bytes catalog-be/src/test/resources/valid_vf.csar | Bin 0 -> 1316 bytes 116 files changed, 14506 insertions(+) create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java create mode 100644 catalog-be/src/test/resources/config/catalog-be/configuration.yaml create mode 100644 catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml create mode 100644 catalog-be/src/test/resources/config/catalog-be/ecomp-error-configuration.yaml create mode 100644 catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml create mode 100644 catalog-be/src/test/resources/config/catalog-be/neo4j-errors-configuration.yaml create mode 100644 catalog-be/src/test/resources/config/catalog-be/users-configuration.yaml create mode 100644 catalog-be/src/test/resources/config/configuration1.yaml create mode 100644 catalog-be/src/test/resources/config/elasticsearch.yml create mode 100644 catalog-be/src/test/resources/config/elasticsearch.yml.bak create mode 100644 catalog-be/src/test/resources/config/mysql-type-empty-nodes.zip create mode 100644 catalog-be/src/test/resources/config/mysql-type-no-nodes.zip create mode 100644 catalog-be/src/test/resources/config/mysql-type-no-version.zip create mode 100644 catalog-be/src/test/resources/config/mysql-type-only-yaml.zip create mode 100644 catalog-be/src/test/resources/config/mysql-type-with-scripts.zip create mode 100644 catalog-be/src/test/resources/config/mysql-type.yml create mode 100644 catalog-be/src/test/resources/config/mysql-type.zip create mode 100644 catalog-be/src/test/resources/config/normative-types-root.zip create mode 100644 catalog-be/src/test/resources/config/sample.yaml create mode 100644 catalog-be/src/test/resources/config/sampleNoProtocol.yaml create mode 100644 catalog-be/src/test/resources/elasticsearch.yml create mode 100644 catalog-be/src/test/resources/logback-test.xml create mode 100644 catalog-be/src/test/resources/mock_vf.csar create mode 100644 catalog-be/src/test/resources/normativeTypes/importToscaProperties.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/importToscaWithAttribute.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-all-map-test.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-DBMS.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-Root.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-blockStorage.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-compute.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-database.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-port.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-softwareComponent.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-new-webServer.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/normative-types-string-list-test.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_duplicateNode.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_empty.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_inputs.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_nodeEmpty.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_nodeVF.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_notValidNode.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_notValidRelationNode.yml create mode 100644 catalog-be/src/test/resources/normativeTypes/topology_template_sample.yml create mode 100644 catalog-be/src/test/resources/types/capabilityTypes.yml create mode 100644 catalog-be/src/test/resources/types/capabilityTypes.zip create mode 100644 catalog-be/src/test/resources/types/categoryTypes.yml create mode 100644 catalog-be/src/test/resources/types/categoryTypes.zip create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeDeriveFromIntegerWithProperty.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeDerivedFromRootNoProperties.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeDuplicateProperty.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeForGroup.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part1.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part2.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part1.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part2.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part1.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part2.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part1.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part2.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part1.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part2.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypeWithPropertyTypeThisDataType.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/dataTypes.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/derived3levelDataType.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/derivedDataType.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/derivedDataTypeNoProperties.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/derivedInvalidDataType.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/emptyDataType.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/emptyDataTypeNoPropertiesTag.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/exitingPropertyAtAncestor.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/invalidDataType.yml create mode 100644 catalog-be/src/test/resources/types/datatypes/oneDataType.yml create mode 100644 catalog-be/src/test/resources/types/interfaceLifecycleTypes.yml create mode 100644 catalog-be/src/test/resources/types/interfaceLifecycleTypes.zip create mode 100644 catalog-be/src/test/resources/valid_vf.csar (limited to 'catalog-be/src/test') diff --git a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java b/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java new file mode 100644 index 0000000000..272f0d6a1d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.util.EnumMap; + +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AuditingMockManager implements IAuditingManager { + + private static Logger log = LoggerFactory.getLogger(AuditingMockManager.class.getName()); + + public AuditingMockManager(String string) { + // TODO Auto-generated constructor stub + } + + @Override + public void auditEvent(EnumMap auditingFields) { + AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); + log.debug("call was made to auditEvent with event type {}", actionEnum.getName()); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java new file mode 100644 index 0000000000..28b60559aa --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.Category; +import org.openecomp.sdc.be.model.PropertyScope; +import org.openecomp.sdc.be.model.Tag; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.CategoryData; + +import fj.data.Either; + +public class ElementOperationMock implements IElementOperation { + + CategoryDefinition resourceCategory; + CategoryDefinition serviceCategory; + CategoryDefinition productCategory; + + Category oldService; + + public ElementOperationMock() { + resourceCategory = new CategoryDefinition(); + resourceCategory.setName("Network Layer 2-3"); + SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(); + subCategoryDefinition.setName("Router"); + SubCategoryDefinition subCategoryDefinition1 = new SubCategoryDefinition(); + subCategoryDefinition1.setName("Gateway"); + + resourceCategory.addSubCategory(subCategoryDefinition); + resourceCategory.addSubCategory(subCategoryDefinition1); + + serviceCategory = new CategoryDefinition(); + serviceCategory.setName("Mobility"); + oldService = new Category(); + oldService.setName("Mobility"); + + productCategory = new CategoryDefinition(); + productCategory.setName("Network Layer 2-31"); + SubCategoryDefinition subCategoryDefinition11 = new SubCategoryDefinition(); + subCategoryDefinition11.setName("Router1"); + GroupingDefinition group = new GroupingDefinition(); + group.setName("group1"); + subCategoryDefinition11.addGrouping(group); + productCategory.addSubCategory(subCategoryDefinition11); + + } + + @Override + public Either, ActionStatus> getAllResourceCategories() { + + List categories = new ArrayList(); + categories.add(resourceCategory); + return Either.left(categories); + + } + + @Override + public Either, ActionStatus> getAllServiceCategories() { + + List categories = new ArrayList(); + categories.add(serviceCategory); + return Either.left(categories); + + } + + /* + * @Override public Either getCategory(String name) { if (name.equals(resourceCategory.getName())){ return Either.left(resourceCategory); } else { return Either.right(ActionStatus.CATEGORY_NOT_FOUND); } } + */ + + @Override + public Either, ActionStatus> getAllTags() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllPropertyScopes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllArtifactTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllDeploymentArtifactTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getCategoryData(String name, NodeTypeEnum type, Class clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getDefaultHeatTimeout() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createCategory(CategoryDefinition category, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either deleteCategory(NodeTypeEnum nodeType, String categoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { + + List categories = new ArrayList(); + switch (nodeType) { + case ResourceNewCategory: + categories.add(resourceCategory); + break; + case ProductCategory: + categories.add(productCategory); + break; + case ServiceNewCategory: + categories.add(serviceCategory); + break; + default: + break; + } + return Either.left(categories); + } + + @Override + public Either getCategory(NodeTypeEnum nodeType, String categoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either deleteGrouping(NodeTypeEnum nodeType, String groupingId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getResourceTypesMap() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getNewCategoryData(String name, NodeTypeEnum type, Class clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllProductCategories() { + List categories = new ArrayList(); + categories.add(productCategory); + return Either.left(categories); + } + + @Override + public Either createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java new file mode 100644 index 0000000000..5b86b9cc69 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.config.ErrorConfiguration; +import org.openecomp.sdc.be.config.ErrorInfo; +import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.FileChangeCallback; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ErrorConfigurationTest { + ConfigurationSource configurationSource = null; + private static Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class.getName()); + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + } + + @Test + public void testReadConfigurationFile() { + + ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() { + + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + } + + }); + + ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener); + + assertTrue(testConfiguration != null); + ErrorInfo errorInfo = testConfiguration.getErrorInfo("USER_NOT_FOUND"); + assertTrue(errorInfo != null); + log.debug("{}", testConfiguration); + log.debug("{}", errorInfo); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java new file mode 100644 index 0000000000..d19ae9c872 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.io.IOException; + +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.common.api.BasicConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.FileChangeCallback; +import org.openecomp.sdc.common.impl.ConfigFileChangeListener; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class TestExternalConfiguration { + + public static void main(String[] args) throws IOException { + + ExternalConfiguration.setAppName("catalog-server"); + ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() { + + @Override + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + + } + }); + + ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir()); + configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener); + + try { + Thread.currentThread().sleep(100 * 1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java new file mode 100644 index 0000000000..a651b77f9a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.ByteArrayOutputStream; + +public class ZipUtil { + + public static void main(String[] args) { + + String zipFileName = "/src/test/resources/config/config.zip"; + + zipFileName = "C:\\Git_work\\D2-SDnC\\catalog-be\\src\\test\\resources\\config\\config.zip"; + zipFileName = "src/test/resources/config/config.zip"; + + Path path = Paths.get(zipFileName); + + try { + byte[] zipAsBytes = Files.readAllBytes(path); + // encode to base + + byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes); + String decodedStr = new String(decodedMd5); + + zipAsBytes = Base64.decodeBase64(decodedStr.getBytes()); + + // String str = new String(zipAsBytes); + + // readZip(str.getBytes()); + readZip(zipAsBytes); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + private static Map readZip(byte[] zipAsBytes) { + + Map fileNameToByteArray = new HashMap(); + + byte[] buffer = new byte[1024]; + ZipInputStream zis = null; + try { + + zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes)); + // get the zipped file list entry + ZipEntry ze = zis.getNextEntry(); + + while (ze != null) { + + String fileName = ze.getName(); + + if (false == ze.isDirectory()) { + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + int len; + while ((len = zis.read(buffer)) > 0) { + os.write(buffer, 0, len); + } + + // aClass.outputStreamMethod(os); + String aString = new String(os.toByteArray(), "UTF-8"); + + fileNameToByteArray.put(fileName, os.toByteArray()); + + } finally { + if (os != null) { + os.close(); + } + } + } + ze = zis.getNextEntry(); + + } + + zis.closeEntry(); + zis.close(); + + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } finally { + if (zis != null) { + try { + zis.closeEntry(); + zis.close(); + } catch (IOException e) { + // TODO: add log + } + + } + } + + return fileNameToByteArray; + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java new file mode 100644 index 0000000000..dff0e3c729 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.mockito.Mockito.when; + +import java.util.EnumMap; +import java.util.UUID; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; + +public class AuditingManagerTest extends BaseConfDependentTest{ + + @InjectMocks + private AuditingManager auditingManager = Mockito.spy(AuditingManager.class); + public static final AuditingDao auditingDao = Mockito.mock(AuditingDao.class); + + public AuditingManagerTest() { + } + + @SuppressWarnings("unchecked") + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); + + } + + @Test + public void testNormalizeEmptyStringValuesAndUuid() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create"); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null "); + + String randomUUID = UUID.randomUUID().toString(); + ThreadLocalsHolder.setUuid(randomUUID); + + auditingManager.auditEvent(auditingFields); + // Checking normalization + Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC), Constants.EMPTY_STRING); + Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT), Constants.EMPTY_STRING); + Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID), randomUUID); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java new file mode 100644 index 0000000000..ad5471e852 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.io.File; + +import org.junit.BeforeClass; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class BaseConfDependentTest { + protected static ConfigurationManager configurationManager; + + @BeforeClass + public static void setupBeforeClass() { + + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + configurationManager = new ConfigurationManager(configurationSource); + + configurationManager.getConfiguration().setTitanInMemoryGraph(true); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java new file mode 100644 index 0000000000..8f3234bc39 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.util.List; + +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class ComponentBusinessLogicTest { + ComponentBusinessLogic businessLogic = new ComponentBusinessLogic() { + + @Override + public Either, ResponseFormat> deleteMarkedComponents() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + // TODO Auto-generated method stub + return null; + } + }; + + @Test + public void testGetRequirementsAndCapabilities() { + // businessLogic.getRequirementsAndCapabilities(componentId, + // componentTypeEnum); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java new file mode 100644 index 0000000000..6af338ebcf --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent; +import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +public class HealthCheckBusinessLogicTest { + + HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); + + @Test + public void checkStausUpdated() { + + boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); + assertFalse("check false", statusChanged); + + List checkInfosLeft = new ArrayList(); + List checkInfosRight = new ArrayList(); + + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); + + HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, null); + + HealthCheckInfo checkInfoEsUp = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoEsDown = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.DOWN, null, null); + + /* + * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null); + */ + + checkInfosLeft.add(checkInfoTitanUp); + checkInfosLeft.add(checkInfoEsUp); + + checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoEsUp); + + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); + + checkInfosRight.remove(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); + + checkInfosRight.add(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); + + checkInfosRight.remove(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); + + checkInfosRight.add(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); + + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); + assertTrue("check true", statusChanged); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java new file mode 100644 index 0000000000..aea29a6419 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.PropertyConstraint; +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.operations.api.IPropertyOperation; +import org.openecomp.sdc.be.model.operations.api.IResourceOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.EntryData; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; +import junit.framework.Assert; + +public class PropertyBusinessLogicTest { + + private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class.getName()); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final IResourceOperation resourceOperation = Mockito.mock(IResourceOperation.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + PropertyBusinessLogic bl = new PropertyBusinessLogic(); + User user = null; + Resource resourceResponse = null; + ResourceBusinessLogic blResource = new ResourceBusinessLogic(); + PropertyBusinessLogic spy = null; + String resourceId = "resourceforproperty.0.1"; + + public PropertyBusinessLogicTest() { + + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + + // Init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + + // Resource Operation mock methods + // getCount + Either eitherCount = Either.left(0); + when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); + Either eitherCountExist = Either.left(1); + when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); + Either eitherCountRoot = Either.left(1); + when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); + + Either eitherGetResource = Either.left(createResourceObject(true)); + when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); + + // // createResource + // resourceResponse = createResourceObject(true); + // Either eitherCreate = + // Either.left(resourceResponse); + // when(resourceOperation.createResource(Mockito.any(Resource.class))).thenReturn(eitherCreate); + + // BL object + // bl = PropertyBusinessLogic.getInstance(servletContext); + // PropertyBusinessLogic spy = PowerMockito.spy(bl); + // when(spy, method(PropertyBusinessLogic.class, "getResource", + // String.class)).withArguments(resource).thenReturn(true); + + } + + private Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName("MyResourceName"); + resource.addCategory("Generic", "VoIP"); + resource.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("yavivi"); + resource.setIcon("MyIcon.jpg"); + + if (afterCreate) { + resource.setName(resource.getName().toLowerCase()); + resource.setVersion("0.1"); + ; + resource.setUniqueId(resourceId); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + return resource; + } + + // @Test + public void testHappyScenario() { + + String propertyName = "disk_size"; + PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId); + Either, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId()); + + if (either.isRight()) { + Assert.assertFalse(true); + } + Assert.assertEquals(newPropertyDefinition, either.left().value()); + } + + private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { + PropertyDefinition pd = new PropertyDefinition(); + List constraints = new ArrayList(); + pd.setConstraints(null); + pd.setDefaultValue("100"); + pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node"); + pd.setPassword(false); + pd.setRequired(true); + pd.setType("Integer"); + pd.setUniqueId(resourceId + "." + propertyName); + return pd; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java new file mode 100644 index 0000000000..eee5c4dd32 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java @@ -0,0 +1,369 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ImportUtilsTest; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.PolicyException; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; + +import fj.data.Either; + +public class ResourceImportManagerTest { + + private static ConfigurationManager configurationManager; + static ResourceImportManager importManager; + static IAuditingManager auditingManager = Mockito.mock(IAuditingManager.class); + static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); + static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + static ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class); + static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + static Logger log = Mockito.spy(Logger.class); + + @BeforeClass + public static void beforeClass() throws IOException { + importManager = new ResourceImportManager(); + importManager.setAuditingManager(auditingManager); + when(resourceOperation.getLatestByToscaResourceName(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(Either.left(null)); + importManager.setResponseFormatManager(responseFormatManager); + importManager.setResourceBusinessLogic(resourceBusinessLogic); + importManager.setResourceOperation(resourceOperation); + ResourceImportManager.setLog(log); + + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + Configuration configuration = new Configuration(); + configuration.setTitanInMemoryGraph(true); + configurationManager.setConfiguration(configuration); + } + + @Before + public void beforeTest() { + Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin, log); + } + + @Test + public void testBasicResourceCreation() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + + User user = new User(); + user.setUserId(resourceMD.getContactId()); + user.setRole("ADMIN"); + user.setFirstName("Jhon"); + user.setLastName("Doh"); + Either eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + + testSetConstantMetaData(resource); + testSetMetaDataFromJson(resource, resourceMD); + + testSetDerivedFrom(resource); + testSetProperties(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)); + } + + @Test + public void testResourceCreationFailed() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either eitherUser = Either.left(user); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + ResponseFormat dummyResponseFormat = createGeneralErrorInfo(); + + when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat); + setResourceBusinessLogicMock(); + + String jsonContent = "this is an invalid yml!"; + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isRight()); + ResponseFormat errorInfoFromTest = createResource.right().value(); + assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus())); + assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId())); + assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage())); + Mockito.verify(log).debug(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Exception.class)); + // Mockito.verify(log).error(Mockito.anyString(), Mockito.anyString(), + // Mockito.anyString()); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true)); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)); + + } + + @Test + public void testResourceCreationWithCapabilities() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"); + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + testSetCapabilities(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)); + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true); + + } + + @Test + public void testResourceCreationWithRequirments() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml"); + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + testSetRequirments(createResource.left().value().left); + + } + + private void setResourceBusinessLogicMock() { + when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin); + when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean())) + .thenAnswer(new Answer, ResponseFormat>>() { + public Either, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left(new ImmutablePair((Resource) args[0], ActionStatus.CREATED)); + + } + }); + when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true))) + .thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[1]); + + } + }); + when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean())).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + + Either either = Either.left(true); + when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either); + } + + public ResponseFormat createGeneralErrorInfo() { + ResponseFormat responseFormat = new ResponseFormat(500); + responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null)); + return responseFormat; + } + + private UploadResourceInfo createDummyResourceMD() { + UploadResourceInfo resourceMD = new UploadResourceInfo(); + resourceMD.setName("tosca.nodes.BlockStorage"); + resourceMD.addSubCategory("Generic", "Infrastructure"); + resourceMD.setContactId("ya107f"); + resourceMD.setResourceIconPath("defaulticon"); + resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" })); + resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created."); + return resourceMD; + } + + private void testSetProperties(Resource resource) { + List propertiesList = resource.getProperties(); + + Map properties = new HashMap(); + for (PropertyDefinition propertyDefinition : propertiesList) { + properties.put(propertyDefinition.getName(), propertyDefinition); + } + + assertTrue(properties.size() == 3); + assertTrue(properties.containsKey("size")); + PropertyDefinition propertyDefinition = properties.get("size"); + assertTrue(propertyDefinition.getType().equals("scalar-unit.size")); + assertTrue(propertyDefinition.getConstraints().size() == 1); + PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0); + assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint); + + assertTrue(properties.containsKey("volume_id")); + propertyDefinition = properties.get("volume_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + assertTrue(properties.containsKey("snapshot_id")); + propertyDefinition = properties.get("snapshot_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + } + + private void testSetCapabilities(Resource resource) { + Map> capabilities = resource.getCapabilities(); + assertTrue(capabilities.size() == 3); + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint")); + List capabilityList = capabilities.get("tosca.capabilities.Endpoint"); + CapabilityDefinition capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint")); + assertTrue(capability.getName().equals("data_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); + capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin")); + assertTrue(capability.getName().equals("admin_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Container")); + capabilityList = capabilities.get("tosca.capabilities.Container"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Container")); + assertTrue(capability.getName().equals("host")); + + List validSourceTypes = capability.getValidSourceTypes(); + assertTrue(validSourceTypes.size() == 1); + assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication")); + + } + + private void testSetRequirments(Resource resource) { + Map> requirements = resource.getRequirements(); + assertTrue(requirements.size() == 2); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable")); + List requirementList = requirements.get("tosca.capabilities.network.Linkable"); + RequirementDefinition requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo")); + assertTrue(requirement.getName().equals("link")); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable")); + requirementList = requirements.get("tosca.capabilities.network.Bindable"); + requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo")); + assertTrue(requirement.getName().equals("binding")); + + } + + private void testSetDerivedFrom(Resource resource) { + assertTrue(resource.getDerivedFrom().size() == 1); + assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root")); + + } + + private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) { + + // assertTrue( resource.getCategory().equals(resourceMD.getCategory()) + // ); + assertTrue(resource.getDescription().equals(resourceMD.getDescription())); + assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath())); + assertTrue(resource.getName().equals(resourceMD.getName())); + assertTrue(resource.getContactId().equals(resourceMD.getContactId())); + assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId())); + + // assertTrue( resource.isAbstract() == + // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory())); + + assertTrue(resourceMD.getTags().size() == resource.getTags().size()); + for (String tag : resource.getTags()) { + assertTrue(resourceMD.getTags().contains(tag)); + } + + } + + private void testSetConstantMetaData(Resource resource) { + assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION)); + assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); + assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME)); + assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java new file mode 100644 index 0000000000..9a8f1c5ad8 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class ResourceTestUtils { + + public static Resource prepareResource(int resourceIndex) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.addCategory("Generic", "Infrastructure"); + List arr = new ArrayList(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List arr1 = new ArrayList(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } + + public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setToscaResourceName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.setResourceType(resourceType); + r.addCategory("Generic", "Infrastructure"); + List arr = new ArrayList(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List arr1 = new ArrayList(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } + + public static Service prepareService(int serviceIndex) { + Service service = new Service(); + service.setName("service_" + serviceIndex); + service.setDescription("desc"); + service.setIcon("icon-service-red1"); + List tags = new ArrayList(); + tags.add(service.getName()); + service.setTags(tags); + CategoryDefinition category = new CategoryDefinition(); + category.setName("Mobility"); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setContactId("as123y"); + service.setProjectCode("123456"); + + return service; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java new file mode 100644 index 0000000000..fd83af016a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java @@ -0,0 +1,931 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class ServiceBusinessLogicTest { + + private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IAuditingManager iAuditingManager = null; + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + AuditingManager auditingManager = Mockito.mock(AuditingManager.class); + ComponentsUtils componentsUtils = new ComponentsUtils(); + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanGenericDao mockTitanDao = Mockito.mock(TitanGenericDao.class); + + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + User user = null; + Service serviceResponse = null; + private static final String CERTIFIED_VERSION = "1.0"; + private static final String UNCERTIFIED_VERSION = "0.2"; + private static final String COMPONNET_ID = "myUniqueId"; + private static Map FILTER_MAP_CERTIFIED_VERSION = new HashMap(); + private static Map FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap(); + private static Map FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap(); + + public ServiceBusinessLogicTest() { + + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + + // Init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(serviceOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either eitherCreate = Either.left(serviceResponse); + when(serviceOperation.createService(Mockito.any(Service.class))).thenReturn(eitherCreate); + Either eitherCount = Either.left(true); + when(serviceOperation.validateServiceNameExists("Service")).thenReturn(eitherCount); + Either eitherCountExist = Either.left(false); + when(serviceOperation.validateServiceNameExists("alreadyExist")).thenReturn(eitherCountExist); + + when(serviceOperation.validateComponentNameExists("alreadyExist")).thenReturn(eitherCountExist); + when(serviceOperation.validateComponentNameExists("Service")).thenReturn(eitherCount); + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setServiceOperation(serviceOperation); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + + componentsUtils.Init(); + componentsUtils.setAuditingManager(auditingManager); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + @Test + public void testGetComponentAuditRecordsCertifiedVersion() { + Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 3); + } + + @Test + public void testGetComponentAuditRecordsUnCertifiedVersion() { + Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 1); + } + + @Test + public void testHappyScenario() { + Service service = createServiceObject(false); + Either createResponse = bl.createService(service, user); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEqualsServiceObject(createServiceObject(true), createResponse.left().value()); + } + + private void assertEqualsServiceObject(Service origService, Service newService) { + assertEquals(origService.getContactId(), newService.getContactId()); + assertEquals(origService.getCategories(), newService.getCategories()); + assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId()); + assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName()); + assertEquals(origService.getDescription(), newService.getDescription()); + assertEquals(origService.getIcon(), newService.getIcon()); + assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId()); + assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getUniqueId(), newService.getUniqueId()); + assertEquals(origService.getVersion(), newService.getVersion()); + assertEquals(origService.getArtifacts(), newService.getArtifacts()); + assertEquals(origService.getCreationDate(), newService.getCreationDate()); + assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate()); + assertEquals(origService.getLifecycleState(), newService.getLifecycleState()); + assertEquals(origService.getTags(), newService.getTags()); + } + + private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + /* CREATE validations - start ***********************/ + // Service name - start + + @Test + public void testFailedServiceValidations() { + testServiceNameAlreadyExists(); + testServiceNameEmpty(); + // testServiceNameExceedsLimit(); + testServiceNameWrongFormat(); + testServiceDescriptionEmpty(); + testServiceDescriptionMissing(); + testServiceDescExceedsLimitCreate(); + testServiceDescNotEnglish(); + testServiceIconEmpty(); + testServiceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + // testTagsExceedsLimitCreate(); + // testTagsSingleExcessLimit(); + testTagsNoServiceName(); + testInvalidTag(); + testServiceTagNotExist(); + testServiceTagEmpty(); + // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them + //testContactIdTooLong(); + //testContactIdWrongFormatCreate(); + testResourceContactIdMissing(); + testServiceCategoryExist(); + testServiceBadCategoryCreate(); + // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them + //testInvalidProjectCode(); + //testProjectCodeTooLong(); + //testProjectCodeTooShort(); + testMissingProjectCode(); + } + + private void testServiceNameAlreadyExists() { + String serviceName = "alreadyExist"; + Service serviceExccedsNameLimit = createServiceObject(false); + // 51 chars, the limit is 50 + serviceExccedsNameLimit.setName(serviceName); + List tgs = new ArrayList(); + tgs.add(serviceName); + serviceExccedsNameLimit.setTags(tgs); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName); + } + + private void testServiceNameEmpty() { + Service serviceExccedsNameLimit = createServiceObject(false); + serviceExccedsNameLimit.setName(null); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceNameExceedsLimit() { + Service serviceExccedsNameLimit = createServiceObject(false); + // 51 chars, the limit is 50 + String tooLongServiceName = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxdsafefegesse"; + serviceExccedsNameLimit.setName(tooLongServiceName); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testServiceNameWrongFormat() { + Service service = createServiceObject(false); + // contains : + String nameWrongFormat = "ljg\fd"; + service.setName(nameWrongFormat); + + Either createResponse = bl.createService(service, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service name - end + // Service description - start + private void testServiceDescriptionEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(""); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescriptionMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescExceedsLimitCreate() { + Service serviceExccedsDescLimit = createServiceObject(false); + // 1025 chars, the limit is 1024 + String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + serviceExccedsDescLimit.setDescription(tooLongServiceDesc); + + Either createResponse = bl.createService(serviceExccedsDescLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testServiceDescNotEnglish() { + Service notEnglish = createServiceObject(false); + // Not english + String tooLongServiceDesc = "\uC2B5"; + notEnglish.setDescription(tooLongServiceDesc); + + Either createResponse = bl.createService(notEnglish, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service description - stop + // Service icon - start + private void testServiceIconEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(""); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceIconMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconInvalid() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Service icon - stop + // Service tags - start + private void testTagsExceedsLimitCreate() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(serviceExccedsNameLimit.getName()); + + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExcessLimit() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9a"; + String tag2 = serviceExccedsNameLimit.getName(); + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb%#%"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" }); + + } + + private void testServiceTagNotExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testServiceTagEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(new ArrayList()); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + // Service tags - stop + // Service contactId - start + private void testContactIdTooLong() { + Service serviceContactId = createServiceObject(false); + // 7 chars instead of 6 + String contactIdTooLong = "yrt1234"; + serviceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Service serviceContactId = createServiceObject(false); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + serviceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceContactIdMissing() { + Service resourceExist = createServiceObject(false); + resourceExist.setContactId(null); + + Either createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service contactId - stop + // Service category - start + private void testServiceCategoryExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setCategories(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } + + public void markDistributionAsDeployedTestAlreadyDeployed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String resultAction = "DResult"; + String did = "123456"; + + setupBeforeDeploy(notifyAction, requestAction, did); + List resultList = new ArrayList(); + Map params = new HashMap(); + DistributionDeployEvent event = new DistributionDeployEvent(); + + event.setAction(resultAction); + event.setDid(did); + event.setStatus("200"); + // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent(); + // deployEvent.setFields(params); + resultList.add(event); + Either, ActionStatus> eventList = Either.left(resultList); + + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); + + Either markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); + + Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); + + } + + @Test + public void markDistributionAsDeployedTestSuccess() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; + + setupBeforeDeploy(notifyAction, requestAction, did); + + Either markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); + + } + + @Test + public void markDistributionAsDeployedTestNotDistributed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; + + setupBeforeDeploy(notifyAction, requestAction, did); + List emptyList = new ArrayList(); + Either, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList); + + Either notFound = Either.right(StorageOperationStatus.NOT_FOUND); + Mockito.when(serviceOperation.getService(did)).thenReturn(notFound); + + Either markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isRight()); + assertEquals(404, markDeployed.right().value().getStatus().intValue()); + + } + + private void testServiceBadCategoryCreate() { + + Service serviceExist = createServiceObject(false); + CategoryDefinition category = new CategoryDefinition(); + category.setName("koko"); + List categories = new ArrayList<>(); + categories.add(category); + serviceExist.setCategories(categories); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service category - stop + private void testInvalidProjectCode() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("koko"); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } + + private void testProjectCodeTooLong() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("5555555555555"); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } + + private void testProjectCodeTooShort() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("555"); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } + + private void testMissingProjectCode() { + + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); + } + + @Test + public void testDeleteMarkedServicesNoServices() { + List ids = new ArrayList(); + Either, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(serviceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + assertTrue(deleteMarkedResources.left().value().isEmpty()); + + Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); + + } + + @Test + public void testDeleteMarkedServices() { + List ids = new ArrayList(); + String resourceInUse = "123"; + ids.add(resourceInUse); + String resourceFree = "456"; + ids.add(resourceFree); + Either, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(serviceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + Either resourceInUseResponse = Either.left(true); + Either resourceFreeResponse = Either.left(false); + + List artifacts = new ArrayList(); + Either, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); + when(serviceOperation.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); + + when(serviceOperation.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(serviceOperation.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either eitherDelete = Either.left(new Resource()); + when(serviceOperation.deleteComponent(resourceFree, true)).thenReturn(eitherDelete); + + when(artifactBl.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); + + Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + List resourceIdList = deleteMarkedResources.left().value(); + assertFalse(resourceIdList.isEmpty()); + assertTrue(resourceIdList.contains(resourceFree)); + assertFalse(resourceIdList.contains(resourceInUse)); + + Mockito.verify(artifactBl, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); + } + + private Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + + service.setDescription("description"); + List tgs = new ArrayList(); + tgs.add(service.getName()); + service.setTags(tgs); + // service.setVendorName("Motorola"); + // service.setVendorRelease("1.0.0"); + // service.setContactId("ya5467"); + service.setIcon("MyIcon"); + // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + + if (afterCreate) { + service.setVersion("0.1"); + service.setUniqueId(service.getName() + ":" + service.getVersion()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug("{}", gson.toJson(service)); + return service; + } + + private void mockAuditingDaoLogic() { + FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); + + final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); + createResourceAudit.setModifier("Carlos Santana(cs0008)"); + createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + createResourceAudit.setCurrVersion("0.1"); + createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); + createResourceAudit.setDesc("OK"); + createResourceAudit.setResourceType("Resource"); + createResourceAudit.setStatus("201"); + createResourceAudit.setPrevVersion(""); + createResourceAudit.setAction("Create"); + // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); + createResourceAudit.setPrevState(""); + createResourceAudit.setResourceName("MyTestResource"); + // createResourceAudit.setFields(fields); + + final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); + checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); + checkInResourceAudit.setCurrVersion("0.1"); + checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); + checkInResourceAudit.setDesc("OK"); + checkInResourceAudit.setComment("Stam"); + checkInResourceAudit.setResourceType("Resource"); + checkInResourceAudit.setStatus("200"); + checkInResourceAudit.setPrevVersion("0.1"); + checkInResourceAudit.setAction("Checkin"); + // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); + checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); + checkInResourceAudit.setResourceName("MyTestResource"); + + final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); + checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + checkOutResourceAudit.setCurrVersion("0.2"); + checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); + checkOutResourceAudit.setDesc("OK"); + checkOutResourceAudit.setComment(""); + checkOutResourceAudit.setResourceType("Resource"); + checkOutResourceAudit.setStatus("200"); + checkOutResourceAudit.setPrevVersion("0.1"); + checkOutResourceAudit.setAction("Checkout"); + // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); + checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); + checkOutResourceAudit.setResourceName("MyTestResource"); + // checkOutResourceAudit.setFields(fields); + + // Mockito.doAnswer(new Answer, + // ActionStatus> >() { + // public Either, ActionStatus> + // answer(InvocationOnMock invocation) { + // final Either, ActionStatus> either; + // final List list; + // Object[] args = invocation.getArguments(); + // Map filterMap = + // (Map) args[0]; + // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ + // list = new + // ArrayList(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; + // either = Either.left(list); + // + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ + // list = new ArrayList(); + // either = Either.left(list); + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ + // list = new + // ArrayList(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; + // either = Either.left(list); + // } + // else{ + // either = null; + // } + // return either; + // } + // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); + // + // + List list = new ArrayList() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List listPrev = new ArrayList(); + Either, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List listCurr = new ArrayList() { + { + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + } + + private void setupBeforeDeploy(String notifyAction, String requestAction, String did) { + + DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent(); + notifyEvent.setAction(notifyAction); + notifyEvent.setDid(did); + notifyEvent.setStatus("200"); + + ResourceAdminEvent requestEvent = new ResourceAdminEvent(); + requestEvent.setAction(requestAction); + requestEvent.setDid(did); + requestEvent.setStatus("200"); + + ArrayList arrayList = new ArrayList(); + List notifyResults = arrayList; + notifyResults.add(notifyEvent); + Either, ActionStatus> eitherNotify = Either.left(notifyResults); + + Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); + + List requestResults = new ArrayList(); + requestResults.add(requestEvent); + Either, ActionStatus> eitherRequest = Either.left(requestResults); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); + + Either eitherService = Either.left(createServiceObject(true)); + Mockito.when(serviceOperation.getService(Mockito.anyString())).thenReturn(eitherService); + + List emptyList = new ArrayList(); + Either, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java new file mode 100644 index 0000000000..7ad93226c7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.ComponentArtifactTypesConfig; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class DistributionEngineConfigTest { + + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } + + @Test + public void validateMissingEnvironments() { + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + + String uebPublicKey = "uebPublicKey"; + String uebSecretKey = "uebSecretKey"; + + DistributionEngine distributionEngine = new DistributionEngine(); + + List environments = new ArrayList(); + environments.add("PROD"); + deConfiguration.setEnvironments(environments); + + List servers = new ArrayList(); + servers.add("server1:80"); + servers.add("server2:8080"); + + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); + + ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); + + deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); + deConfiguration.setDistributionStatusTopicName("statusTopic"); + + DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig(); + distributionStatusTopic.setConsumerGroup("asdc-group"); + distributionStatusTopic.setConsumerId("asdc-id"); + distributionStatusTopic.setFetchTimeSec(20); + distributionStatusTopic.setPollingIntervalSec(20); + deConfiguration.setDistributionStatusTopic(distributionStatusTopic); + + deConfiguration.setUebServers(servers); + deConfiguration.setUebPublicKey(uebPublicKey); + deConfiguration.setUebSecretKey(uebSecretKey); + deConfiguration.setInitMaxIntervalSec(8); + deConfiguration.setInitRetryIntervalSec(3); + + boolean isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setUebServers(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setUebServers(servers); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setEnvironments(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setEnvironments(environments); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setUebPublicKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setUebPublicKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setUebSecretKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setUebSecretKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setDistributionNotifTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setDistributionNotifTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setDistributionStatusTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setDistributionStatusTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setInitMaxIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setInitMaxIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + deConfiguration.setInitRetryIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); + + deConfiguration.setInitRetryIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java new file mode 100644 index 0000000000..b3a254f531 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; +import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class DistributionEngineHealthCheckTest extends BaseConfDependentTest { + + @Mock + private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + + DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth(); + + Gson gson = new Gson(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + // + // @Test + // public void validateDownWhenEnvAreDown() { + // + // Map envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(false)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); + // + // HealthCheckInfo healthCheckInfo = + // distributionEngineClusterHealth.getHealthCheckInfo(); + // assertEquals("verify down", HealthCheckStatus.DOWN, + // healthCheckInfo.getHealthCheckStatus()); + // assertEquals("verify DE component", HealthCheckComponent.DE, + // healthCheckInfo.getHealthCheckComponent()); + // + // } + + @Test + public void validateUpWhenQuerySucceed() { + + // Map envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(true)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus, + // false); + + CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403); + + List uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers(); + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + + UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + Boolean call1 = healthCheckCall1.call(); + assertTrue("check response okay", call1); + + UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + Boolean call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java new file mode 100644 index 0000000000..de7b84fa82 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.distribution.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; +import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import fj.data.Either; + +public class DistributionEngineInitTaskTest { + + @Mock + private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + + @Mock + private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + + // public static final IAuditingDao iAuditingDao = + // Mockito.mock(AuditingDao.class); + + @Before + public void setup() { + // ExternalConfiguration.setAppName("distribEngine1"); + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); + + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } + + @Test + public void checkIncrement() { + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + + for (int i = 1; i < 5; i++) { + initTask.incrementRetryInterval(); + assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i)); + } + + initTask.incrementRetryInterval(); + assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry); + + } + + @Test + public void testInitFlowScenarioSuccess() { + + String notifTopic = "notif"; + String statusTopic = "status"; + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + + } + + @Test + public void testInitFlowScenarioSuccessTopicsAlreadyExists() { + + String envName = "PrOD"; + String notifTopic = "notif"; + String statusTopic = "status"; + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + + Set topics = new HashSet(); + topics.add(realNotifTopic); + topics.add(realStatusTopic); + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either, CambriaErrorResponse> left = Either.left(topics); + + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left); + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + try { + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + } catch (Exception e) { + assertTrue("Should not throw exception", false); + } + + } + + @Test + public void testInitFlowScenarioFailToRegister() { + + String notifTopic = "notif"; + String statusTopic = "status"; + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(Collection.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.eq(realNotifTopic), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + + when(cambriaHandler.registerToTopic(Mockito.any(Collection.class), Mockito.eq(realStatusTopic), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(SubscriberTypeEnum.class))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + @Test + public void testInitFlowScenario1GetTopicsFailed() { + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR); + Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java new file mode 100644 index 0000000000..0905b8cd19 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; +import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; +import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + +import fj.data.Either; + +public class ArtifactBusinessLogicTest { + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @InjectMocks + static ArtifactsBusinessLogic artifactBL = new ArtifactsBusinessLogic(); + + public static final ArtifactOperation artifactOperation = Mockito.mock(ArtifactOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final IInterfaceLifecycleOperation lifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final IUserAdminOperation userOperation = Mockito.mock(IUserAdminOperation.class); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + // public static final InformationDeployedArtifactsBusinessLogic + // informationDeployedArtifactsBusinessLogic = + // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); + + public static final Resource resource = Mockito.mock(Resource.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @BeforeClass + public static void setup() { + + Either NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifactById(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(NotFoundResult); + + Either, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifacts(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + when(artifactOperation.getArtifacts(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + + Either, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); + when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); + + User userJH = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); + Either getUserResult = Either.left(userJH); + + when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); + + Either, ActionStatus> getType = Either.left(getAllTypes()); + when(elementOperation.getAllArtifactTypes()).thenReturn(getType); + + when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + // when(informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts(Mockito.any(Resource.class))).thenReturn(new + // ArrayList()); + } + + private static List getAllTypes() { + List artifactTypes = new ArrayList(); + List artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); + for (String artifactType : artifactTypesList) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return artifactTypes; + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testValidJson() { + ArtifactDefinition ad = createArtifactDef(); + + String jsonArtifact = gson.toJson(ad); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); + assertEquals(ad, afterConvert); + } + + private ArtifactDefinition createArtifactDef() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1.yaml"); + ad.setArtifactLabel("label1"); + ad.setDescription("description"); + ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + return ad; + } + + @Test + public void testInvalidStringGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidNumberGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidGroupTypeWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidTimeoutWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("timeout", " 15"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + // @Test + // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ + // ArtifactDefinition createArtifactDef = createArtifactDef(); + // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); + // + // Either validateResult = artifactBL + // .convertAndValidate(resource, "resourceId", + // gson.toJson(createArtifactDef), "jh0003", null, null, true, + // null, NodeTypeEnum.Resource); + // + // assertTrue(validateResult.isLeft()); + // ArtifactDefinition validatedArtifact = validateResult.left().value(); + // + // assertEquals(createArtifactDef.getArtifactGroupType(), + // validatedArtifact.getArtifactGroupType()); + // assertEquals(new Integer(0), validatedArtifact.getTimeout()); + // assertFalse(validatedArtifact.getMandatory()); + // assertFalse(validatedArtifact.getServiceApi()); + // + // } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java new file mode 100644 index 0000000000..776fe8864e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; +import org.openecomp.sdc.be.components.impl.CommonImportManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.common.util.CapabilityTypeNameEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CapabilityTypeImportManagerTest { + @InjectMocks + private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + + @BeforeClass + public static void beforeClass() { + when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either ans = Either.left((CapabilityTypeDefinition) args[0]); + return ans; + } + + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testCreateCapabilityTypes() throws IOException { + String ymlContent = getCapabilityTypesYml(); + Either, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + List capabilityTypesList = createCapabilityTypes.left().value(); + assertTrue(capabilityTypesList.size() == 14); + Map capibilityTypeMap = new HashMap<>(); + for (CapabilityTypeDefinition capType : capabilityTypesList) { + capibilityTypeMap.put(capType.getType(), capType); + } + assertTrue(capabilityTypesList.size() == 14); + + for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { + assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); + } + + } + + private String getCapabilityTypesYml() throws IOException { + Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java new file mode 100644 index 0000000000..05fc6a2948 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.CategoriesImportManager; +import org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; + +import fj.data.Either; + +public class CategoriesImportManagerTest { + @InjectMocks + static CategoriesImportManager importManager = new CategoriesImportManager(); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + + static Logger log = Mockito.spy(Logger.class); + + private static SubCategoryDefinition subcategory; + + @BeforeClass + public static void beforeClass() throws IOException { + InterfaceLifecycleTypeImportManager.setLog(log); + + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId("123"); + + when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either ans = Either.left((CategoryDefinition) args[0]); + return ans; + } + + }); + when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); + Either ans = Either.left(subcategory); + return ans; + } + + }); + + // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void importCategoriesTest() throws IOException { + String ymlContent = getYmlContent(); + Either>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + } + + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java new file mode 100644 index 0000000000..135caf2c82 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.CompositionBusinessLogic; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; + +public class CompositionBusinessLogicTest { + CompositionBusinessLogic compBl = new CompositionBusinessLogic(); + + @Test + public void testBuildSpiralPatternPositioningForComponentInstances() { + int instancesNum = 10; + Resource createVF = FactoryUtils.createVF(); + for (int i = 0; i < instancesNum; i++) { + FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); + } + Map, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); + assertTrue(componentInstances.size() == instancesNum); + // Verify Spiral Pattern + ImmutablePair key; + key = new ImmutablePair<>(0D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-2D, -1D); + assertTrue(componentInstances.containsKey(key)); + } + + @Test + public void testGetCpsConnectedToVFC() { + List allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); + + Map> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + assertTrue(cpsConnectedToVFC.size() == 1); + assertTrue(cpsConnectedToVFC.containsKey(vfc)); + Set cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); + assertTrue(cps.size() == 3); + cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); + + } + + @Test + public void testBuildCirclePatternForCps() { + List allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); + Map> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + + Map, ComponentInstance> componentInstLocations = new HashMap<>(); + componentInstLocations.put(new ImmutablePair(0D, 0D), vfcInstance); + compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); + assertTrue(componentInstLocations.size() == 4); + + Set> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); + // Verify that all cps are located at different positions + assertTrue(cpsLocations.size() == 3); + Set distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); + // Verify that all cps are at the same distance from center + assertTrue(distances.size() == 1); + + } + + /** + * Adds 4 instances to the vf.
+ * vfc instance and 3 cps instances.
+ * the cp instances are connected to the vfc instance.
+ * + * @param allComponentInstances + * @param createVF + * @return vfc instance + */ + private ComponentInstance populateVfWithVfcAndCps(List allComponentInstances, Resource createVF) { + ComponentInstance vfc = FactoryUtils.createResourceInstance(); + vfc.setOriginType(OriginTypeEnum.VFC); + FactoryUtils.addComponentInstanceToVF(createVF, vfc); + allComponentInstances.add(vfc); + + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + return vfc; + } + + private void connectCpToVfc(List allComponentInstances, Resource createVF, ComponentInstance vfc) { + List allRelations; + if (createVF.getComponentInstancesRelations() != null) { + allRelations = createVF.getComponentInstancesRelations(); + } else { + allRelations = new ArrayList<>(); + createVF.setComponentInstancesRelations(allRelations); + } + ComponentInstance cp1 = FactoryUtils.createResourceInstance(); + cp1.setOriginType(OriginTypeEnum.CP); + addVfcCpRelation(vfc, cp1, allRelations); + FactoryUtils.addComponentInstanceToVF(createVF, cp1); + allComponentInstances.add(cp1); + } + + private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List allRelations) { + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + rel.setToNode(vfc.getComponentUid()); + rel.setFromNode(cp.getComponentUid()); + allRelations.add(rel); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java new file mode 100644 index 0000000000..84c8286f14 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import java.util.Arrays; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.CsarValidationUtils; + +public class CsarValidationUtilsTest { + private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; + private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; + + @Test + public void testIsCsarPayloadName() { + Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); + Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java new file mode 100644 index 0000000000..6dd19cce57 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -0,0 +1,509 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Function; + +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; +import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.yaml.snakeyaml.Yaml; + +import fj.data.Either; + +public class ImportUtilsTest { + @Test + public void testStringTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 4); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof String); + String value = (String) element; + assertTrue(value.equals("stringVal" + count)); + count++; + } + } + + @Test + public void testBooleanTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Boolean); + Boolean value = (Boolean) element; + if (count == 1 || count == 3) { + assertFalse(value); + } else if (count == 2) { + assertTrue(value); + } + + count++; + } + } + + @Test + public void testListTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof List); + + if (count == 1) { + verifyListElement1(element); + } else if (count == 2) { + verifyListElement2(element); + } + + else if (count == 3) { + verifyListElement3(element); + } + count++; + } + } + + @Test + public void testAllTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 5); + int count = 1; + for (Object element : list) { + if (count == 1) { + assertTrue(element instanceof String); + assertTrue(element.equals("tosca.nodes.Root")); + } else if (count == 2) { + assertTrue(element instanceof Map); + Map mapElement = (Map) element; + assertTrue(mapElement.size() == 2); + Iterator> elementEntries = mapElement.entrySet().iterator(); + Entry elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("mapTestTag")); + assertTrue(elementEntry.getValue().equals("string")); + + elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("required")); + assertTrue(elementEntry.getValue() instanceof Boolean); + assertTrue((Boolean) elementEntry.getValue()); + } + + else if (count == 3) { + assertTrue(element instanceof String); + assertTrue(element.equals("1 MB")); + } + + else if (count == 4) { + assertTrue(element instanceof List); + List listElement = (List) element; + assertTrue(listElement.size() == 2); + + assertTrue(listElement.get(0) instanceof Map); + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("greater_or_equal")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal3")); + } else if (count == 5) { + assertTrue(element instanceof Boolean); + assertFalse((Boolean) element); + } + count++; + } + } + + @Test + public void testMapTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 2); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Map); + + if (count == 1) { + Map mapElement = (Map) element; + assertTrue(mapElement.size() == 2); + Iterator> iterator = mapElement.entrySet().iterator(); + Entry inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("stringTestTag")); + assertTrue(inerElementEntry.getValue().equals("stringVal1")); + + inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("listTestTag")); + assertTrue(inerElementEntry.getValue() instanceof List); + List innerValue = (List) inerElementEntry.getValue(); + + assertTrue(innerValue.size() == 3); + + } else if (count == 2) { + Map mapElement = (Map) element; + assertTrue(mapElement.size() == 2); + Iterator> entryItr = mapElement.entrySet().iterator(); + Entry inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("type")); + assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); + inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("allTestTag")); + assertTrue(inerElementEntry.getValue() instanceof Boolean); + } + + count++; + } + } + + @Test + public void testCreateFullHeatParameterModuleWithString() { + + testCreateFullHeatParameterModule("string", "default value"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithNumber() { + + testCreateFullHeatParameterModule("number", "777"); + testCreateFullHeatParameterModule("number", "777.23"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithBoolean() { + + testCreateFullHeatParameterModule("boolean", "true"); + testCreateFullHeatParameterModule("boolean", "on"); + testCreateFullHeatParameterModule("boolean", "n"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithList() { + + testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); + + } + + // @Test + // public void testCreateFullHeatParameterModuleWithInvalidType(){ + // + // String name = "fullParameter"; + // String description = "description_text"; + // + // Map parametersMap = new HashMap(); + // Map firstParam = createParameterMap("aaa", "aaa", + // name, description); + // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), + // firstParam); + // + // Either,ResultStatusEnum> heatParameters = + // ImportUtils.getHeatParameters(parametersMap); + // assertTrue(heatParameters.isRight()); + // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, + // heatParameters.right().value()); + // + // } + + @Test + public void testCreateFullHeatParameterModuleWithMissingType() { + + String name = "fullParameter"; + String description = "description_text"; + + Map parametersMap = new HashMap(); + Map firstParam = createParameterMap(null, "aaa", name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isRight()); + assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); + + } + + @Test + public void testCreateFullHeatParameterModuleWithMissingFields() { + + String name = "fullParameter"; + + Map parametersMap = new HashMap(); + String type = "number"; + String defValue = "defvalue"; + // default value cannot be empty in heat in case tag exists + Map firstParam = createParameterMap(type, defValue, name, null); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + + assertParameter(parameterDefinition, name, type, null, defValue); + + } + + @Test + public void testGetAttributesFromYml() throws IOException { + + Map toscaJson = (Map) loadJsonFromFile("importToscaWithAttribute.yml"); + Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + assertTrue(actualAttributes.isLeft()); + Map> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); + compareAttributes(expectedAttributes, actualAttributes.left().value()); + + } + + @Test + public void testGetPropertiesFromYml() throws IOException { + + Map toscaJson = (Map) loadJsonFromFile("importToscaProperties.yml"); + Either, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); + assertTrue(actualProperties.isLeft()); + Map> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); + compareProperties(expectedProperties, actualProperties.left().value()); + + } + + private void compareAttributes(Map> expected, Map actual) { + + Map singleExpectedAttribute; + AttributeDefinition actualAttribute, expectedAttributeModel; + // attributes of resource + for (Map.Entry> expectedAttribute : expected.entrySet()) { + + singleExpectedAttribute = expectedAttribute.getValue(); + assertNotNull(singleExpectedAttribute); + actualAttribute = actual.get(expectedAttribute.getKey()); + assertNotNull(actualAttribute); + actualAttribute.setName(expectedAttribute.getKey().toString()); + expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); + expectedAttributeModel.setName(expectedAttribute.getKey().toString()); + + assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); + assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); + assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); + assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); + assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); + + compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); + + } + + } + + private void compareProperties(Map> expected, Map actual) { + + Map singleExpectedProperty; + PropertyDefinition actualProperty, expectedPropertyModel; + // attributes of resource + for (Map.Entry> expectedProperty : expected.entrySet()) { + + singleExpectedProperty = expectedProperty.getValue(); + assertNotNull(singleExpectedProperty); + actualProperty = actual.get(expectedProperty.getKey()); + assertNotNull(actualProperty); + actualProperty.setName(expectedProperty.getKey().toString()); + expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); + expectedPropertyModel.setName(expectedProperty.getKey().toString()); + + assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); + assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); + assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); + assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); + assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); + + compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); + + } + + } + + private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { + + if (expected == null && actual == null) { + return; + } + PropertyDataDefinition actualPropertySchema = actual.getProperty(); + PropertyDataDefinition expectedPropertySchema = expected.getProperty(); + assertNotNull(actualPropertySchema); + assertNotNull(expectedPropertySchema); + assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); + assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); + + } + + private Map getElements(Map toscaJson, ToscaTagNamesEnum elementType) { + + Either, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); + assertTrue(toscaExpectedElements.isLeft()); + + return toscaExpectedElements.left().value(); + + } + + private void testCreateFullHeatParameterModule(String type, Object defaultVal) { + + String name = "fullParameter"; + String description = "description_text"; + + Map parametersMap = new HashMap(); + Map firstParam = createParameterMap(type, defaultVal, name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + + assertParameter(parameterDefinition, name, type, description, defaultVal); + + } + + private Map createParameterMap(String type, Object defaultVal, String name, String description) { + Map firstParam = new HashMap(); + Map valuesMap = new HashMap(); + + valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); + valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); + valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); + + firstParam.put(name, valuesMap); + return firstParam; + } + + private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { + assertEquals(name, parameterDefinition.getName()); + assertEquals(description, parameterDefinition.getDescription()); + assertEquals(type, parameterDefinition.getType()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); + } + + private void verifyListElement3(Object element) { + List listElement = (List) element; + assertTrue(listElement.size() == 2); + + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("type")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + private void verifyListElement2(Object element) { + List listElement = (List) element; + assertTrue(listElement.size() == 2); + + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue() instanceof List); + } + + private void verifyListElement1(Object element) { + List listElement = (List) element; + assertTrue(listElement.size() == 3); + + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("2 MB")); + + innerElement = (Map) listElement.get(2); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + public static String loadFileNameToJsonString(String fileName) throws IOException { + String sourceDir = "src/test/resources/normativeTypes"; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static Object loadJsonFromFile(String fileName) throws IOException { + String content = loadFileNameToJsonString(fileName); + Object load = new Yaml().load(content); + return load; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java new file mode 100644 index 0000000000..6ba74ec133 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.CommonImportManager; +import org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; + +import fj.data.Either; + +public class InterfaceLifecycleTypeImportManagerTest { + + @InjectMocks + private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + + static Logger log = Mockito.spy(Logger.class); + + @BeforeClass + public static void beforeClass() throws IOException { + InterfaceLifecycleTypeImportManager.setLog(log); + when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either ans = Either.left((InterfaceDefinition) args[0]); + return ans; + } + + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void importLiecycleTest() throws IOException { + String ymlContent = getYmlContent(); + Either, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + } + + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } +} 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 new file mode 100644 index 0000000000..5a503dc97c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -0,0 +1,1423 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingLogFormatUtil; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +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.operations.api.ICapabilityTypeOperation; +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.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.CsarOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +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.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class ResourceBusinessLogicTest { + + private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class.getName()); + public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; + public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; + public static final String RESOURCE_SUBCATEGORY = "Router"; + + public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; + public static final String UPDATED_SUBCATEGORY = "Gateway"; + + public static final String RESOURCE_NAME = "My-Resource_Name with space"; + + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IAuditingManager iAuditingManager = null; + IElementOperation mockElementDao; + TitanGenericDao mockTitanDao = Mockito.mock(TitanGenericDao.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + final ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class); + final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); + final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + ResponseFormatManager responseManager = null; + AuditingManager auditingManager = Mockito.mock(AuditingManager.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + User user = null; + Resource resourceResponse = null; + ComponentsUtils componentsUtils = new ComponentsUtils(); + ArtifactsBusinessLogic artifactManager = Mockito.mock(ArtifactsBusinessLogic.class); + CsarOperation csarOperation = Mockito.mock(CsarOperation.class); + Map emptyDataTypes = new HashMap(); + + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + public ResourceBusinessLogicTest() { + + } + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.reset(propertyOperation); + + ExternalConfiguration.setAppName("catalog-be"); + + // Init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); + when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + + // Resource Operation mock methods + // getCount + /* + * Either eitherCount = Either.left(0); when(resourceOperation.getNumberOfResourcesByName("MyResourceName")). thenReturn(eitherCount); Either eitherCountExist = Either.left(1); + * when(resourceOperation.getNumberOfResourcesByName("alreadyExist")). thenReturn(eitherCountExist); + */ + Either eitherCountRoot = Either.left(1); + when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); + Either eitherFalse = Either.left(false); + when(resourceOperation.validateResourceNameExists(ValidationUtils.normaliseComponentName("Root"), ResourceTypeEnum.VFC)).thenReturn(eitherFalse); + + Either eitherCountExist = Either.left(false); + when(resourceOperation.validateResourceNameExists("alreadyExists", ResourceTypeEnum.VFC)).thenReturn(eitherCountExist); + Either eitherCount = Either.left(true); + when(resourceOperation.validateResourceNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC)).thenReturn(eitherCount); + + Either validateDerivedExists = Either.left(false); + when(resourceOperation.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + Either validateDerivedNotExists = Either.left(true); + when(resourceOperation.validateToscaResourceNameExists(ValidationUtils.normaliseComponentName("kuku"))).thenReturn(validateDerivedNotExists); + + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + + ArtifactDefinition artifactDef = new ArtifactDefinition(); + artifactDef.setUniqueId("123.123"); + Either returnEither = Either.left(artifactDef); + when(artifactManager.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + when(artifactManager.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyBoolean())).thenReturn(returnEither); + + // createResource + resourceResponse = createResourceObject(true); + Either eitherCreate = Either.left(resourceResponse); + Either, StorageOperationStatus> eitherValidate = Either.left(null); + when(resourceOperation.createResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(eitherCreate); + when(resourceOperation.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); + Map emptyDataTypes = new HashMap(); + when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); + + // BL object + bl = new ResourceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setResourceOperation(resourceOperation); + bl.setCapabilityTypeOperation(capabilityTypeOperation); + componentsUtils.Init(); + componentsUtils.setAuditingManager(auditingManager); + bl.setComponentsUtils(componentsUtils); + bl.setLifecycleManager(lifecycleBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setArtifactsManager(artifactManager); + bl.setPropertyOperation(propertyOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setApplicationDataTypeCache(applicationDataTypeCache); + bl.setCsarOperation(csarOperation); + bl.setCacheManagerOperation(cacheManager); + + Resource resourceCsar = createResourceObjectCsar(true); + setCanWorkOnResource(resourceCsar); + Either oldResourceRes = Either.left(resourceCsar); + when(resourceOperation.getResource(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + when(resourceOperation.getLatestResourceByCsarOrName(resourceCsar.getCsarUUID(), resourceCsar.getSystemName())).thenReturn(oldResourceRes); + when(resourceOperation.updateResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(oldResourceRes); + responseManager = ResponseFormatManager.getInstance(); + + } + + 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 tgs = new ArrayList(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List 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); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + return resource; + } + + 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 tgs = new ArrayList(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + 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); + } + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + return resource; + } + + private Resource setCanWorkOnResource(Resource resource) { + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setLastUpdaterUserId(user.getUserId()); + return resource; + } + + @Test + public void testHappyScenario() { + Resource resource = createResourceObject(false); + Either createResponse = bl.createResource(resource, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEquals(createResourceObject(true), createResponse.left().value()); + } + + @Test + public void testUpdateHappyScenario() { + Resource resource = createResourceObjectCsar(true); + setCanWorkOnResource(resource); + Either updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); + if (updateResponse.isRight()) { + assertEquals(new Integer(200), updateResponse.right().value().getStatus()); + } + assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); + } + + /* CREATE validations - start ***********************/ + // Resource name - start + + @Test + public void testFailedResourceValidations() { + testResourceNameExist(); + testResourceNameEmpty(); + // testResourceNameExceedsLimit(); + testResourceNameWrongFormat(); + testResourceDescExceedsLimitCreate(); + testResourceDescNotEnglish(); + testResourceDescriptionEmpty(); + testResourceDescriptionMissing(); + testResourceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + testResourceTagNotExist(); + testResourceTagEmpty(); + testTagsExceedsLimitCreate(); + // testTagsSingleExceedsLimit(); + testTagsNoServiceName(); + testInvalidTag(); + // 1610OS Support - Because of changes in the validation in the ui these tests will fail. need to fix them + //testContactIdTooLong(); + //testContactIdWrongFormatCreate(); + testResourceContactIdEmpty(); + testResourceContactIdMissing(); + testVendorNameExceedsLimit(); + testVendorNameWrongFormatCreate(); + testVendorReleaseWrongFormat(); + testVendorReleaseExceedsLimitCreate(); + testResourceVendorNameMissing(); + testResourceVendorReleaseMissing(); + testResourceCategoryExist(); + testResourceBadCategoryCreate(); + testHappyScenarioCostLicenseType(); + testCostWrongFormatCreate(); + testLicenseTypeWrongFormatCreate(); + testResourceTemplateNotExist(); + testResourceTemplateEmpty(); + testResourceTemplateInvalid(); + } + + private void testResourceNameExist() { + String resourceName = "alreadyExists"; + Resource resourceExist = createResourceObject(false); + resourceExist.setName(resourceName); + resourceExist.getTags().add(resourceName); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + private void testResourceNameEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setName(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceNameExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + resourceExccedsNameLimit.setName(tooLongResourceName); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testResourceNameWrongFormat() { + Resource resource = createResourceObject(false); + // contains : + String nameWrongFormat = "ljg?fd"; + resource.setName(nameWrongFormat); + + Either createResponse = bl.createResource(resource, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Resource name - end + // Resource description - start + private void testResourceDescExceedsLimitCreate() { + Resource resourceExccedsDescLimit = createResourceObject(false); + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + resourceExccedsDescLimit.setDescription(tooLongResourceDesc); + + Either createResponse = bl.createResource(resourceExccedsDescLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testResourceDescNotEnglish() { + Resource notEnglish = createResourceObject(false); + // Not english + String notEnglishDesc = "\uC2B5"; + notEnglish.setDescription(notEnglishDesc); + + Either createResponse = bl.createResource(notEnglish, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(""); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + // Resource description - end + // Resource icon start + + private void testResourceIconMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconInvalid() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Resource icon end + // Resource tags - start + private void testResourceTagNotExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testResourceTagEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(new ArrayList()); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testTagsExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resourceExccedsNameLimit.getName()); + + resourceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; + String tag2 = resourceExccedsNameLimit.getName(); + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + + resourceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(serviceExccedsNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb%#%"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(serviceExccedsNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" }); + + } + + // Resource tags - stop + // Resource contact info start + private void testContactIdTooLong() { + Resource resourceContactId = createResourceObject(false); + // 7 chars instead of 6 + String contactIdTooLong = "yrt1234"; + resourceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createResource(resourceContactId, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Resource resourceContactId = createResourceObject(false); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + resourceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createResource(resourceContactId, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(""); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testVendorNameExceedsLimit() { + Resource resourceExccedsVendorNameLimit = createResourceObject(false); + String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); + + Either createResponse = bl.createResource(resourceExccedsVendorNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + } + + private void testVendorNameWrongFormatCreate() { + Resource resource = createResourceObject(false); + // contains * + String nameWrongFormat = "ljg*fd"; + resource.setVendorName(nameWrongFormat); + + Either createResponse = bl.createResource(resource, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + } + + private void testVendorReleaseWrongFormat() { + Resource resource = createResourceObject(false); + // contains > + String nameWrongFormat = "1>2"; + resource.setVendorRelease(nameWrongFormat); + + Either createResponse = bl.createResource(resource, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); + + } + + private void testVendorReleaseExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + private void testResourceVendorNameMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorName(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); + } + + private void testResourceVendorReleaseMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorRelease(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); + } + + // Resource vendor name/release stop + // Category start + private void testResourceCategoryExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceBadCategoryCreate() { + + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + resourceExist.addCategory("koko", "koko"); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Category stop + // Cost start + private void testHappyScenarioCostLicenseType() { + Resource createResourceObject = createResourceObject(false); + Resource createResourceObjectAfterCreate = createResourceObject(true); + // Adding cost and licenseType to basic mock + Either eitherCreate = Either.left(createResourceObjectAfterCreate); + when(resourceOperation.createResource(Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(eitherCreate); + + String cost = "123.456"; + String licenseType = "User"; + createResourceObject.setCost(cost); + createResourceObject.setLicenseType(licenseType); + Either createResponse = bl.createResource(createResourceObject, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + createResourceObjectAfterCreate.setCost(cost); + createResourceObjectAfterCreate.setLicenseType(licenseType); + assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); + } + + private void testCostWrongFormatCreate() { + Resource resourceCost = createResourceObject(false); + // Comma instead of fullstop + String cost = "12356,464"; + resourceCost.setCost(cost); + + Either createResponse = bl.createResource(resourceCost, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // Cost stop + // License type start + private void testLicenseTypeWrongFormatCreate() { + Resource resourceLicenseType = createResourceObject(false); + // lowcase + String licenseType = "cpu"; + resourceLicenseType.setLicenseType(licenseType); + + Either createResponse = bl.createResource(resourceLicenseType, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // License type stop + // Derived from start + private void testResourceTemplateNotExist() { + Resource resourceExist = createResourceObject(false); + List list = null; + resourceExist.setDerivedFrom(list); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDerivedFrom(new ArrayList()); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateInvalid() { + Resource resourceExist = createResourceObject(false); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("kuku"); + resourceExist.setDerivedFrom(derivedFrom); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + // Derived from stop + + private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + // UPDATE tests - start + // Resource name + @Test + public void testResourceNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setName(nameWrongFormat); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testResourceNameAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String name = "ljg"; + updatedResource.setName(name); + resource.setVersion("1.0"); + ; + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + + } + + @Test + @Ignore + public void testResourceNameExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + updatedResource.setName(tooLongResourceName); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + @Test + public void testResourceNameAlreadyExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String resourceName = "alreadyExists"; + updatedResource.setName(resourceName); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + // + + @Test + public void testResourceDescExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + updatedResource.setDescription(tooLongResourceDesc); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + + } + + @Test + public void testIconWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains . + String icon = "icon.jpg"; + updatedResource.setIcon(icon); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testIconAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains + String icon = "icon"; + updatedResource.setIcon(icon); + + resource.setVersion("1.0"); + ; + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + + } + + @Test + public void testTagsExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resource.getName()); + + updatedResource.setTags(tagsList); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + } + + @Test + public void testVendorNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorNameAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + resource.setVersion("1.0"); + ; + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); + + } + + @Test + public void testVendorReleaseExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + // 129 chars, the limit is 128 + String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; + updatedResource.setVendorRelease(tooLongVendorRelease); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + // 1610OS Support - Because of changes in the validation in the ui this test needs to be fixed +// @Test +// public void testContactIdWrongFormat_UPDATE() { +// Resource resource = createResourceObject(true); +// Resource updatedResource = createResourceObject(true); +// +// // this is in order to prevent failing with 403 earlier +// Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); +// // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); +// when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); +// +// String resourceId = resource.getUniqueId(); +// // 3 letters and 3 digits +// String contactIdTooLong = "yrt134"; +// updatedResource.setContactId(contactIdTooLong); +// Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); +// assertTrue(createResponse.isRight()); +// +// assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); +// } + + @Test + public void testResourceBadCategory_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + String badCategory = "ddfds"; + updatedResource.setCategories(null); + updatedResource.addCategory(badCategory, "fikt"); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceCategoryAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + updatedResource.setCategories(null); + updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); + resource.setVersion("1.0"); + ; + + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + } + + // Derived from start + @Test + public void testResourceTemplateNotExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + String resourceId = resource.getUniqueId(); + + List list = null; + updatedResource.setDerivedFrom(list); + + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateEmpty_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + updatedResource.setDerivedFrom(new ArrayList()); + + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateInvalid_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("kuku"); + updatedResource.setDerivedFrom(derivedFrom); + + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + + @Test + public void testResourceTemplateCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(resourceOperation.getResource(resource.getUniqueId(), false)).thenReturn(eitherUpdate); + resource.setVersion("1.0"); + ; + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED); + } + // Derived from stop + + @Test + public void createOrUpdateResourceAlreadyCheckout() { + Resource resourceExist = createResourceObject(false); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + + createResponse.left().value().setLastUpdaterUserId(user.getUserId()); + assertTrue(createResponse.isLeft()); + + Either getLatestResult = Either.left(createResponse.left().value()); + when(resourceOperation.getLatestByName(resourceExist.getName(), true)).thenReturn(getLatestResult); + when(resourceOperation.overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(getLatestResult); + + Resource resourceToUpdtae = createResourceObject(false); + + Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(resourceOperation, Mockito.times(1)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean()); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceCertified() { + Resource resourceExist = createResourceObject(false); + + Either createResponse = bl.createResource(resourceExist, user, null, null); + + assertTrue(createResponse.isLeft()); + Resource certifiedResource = createResponse.left().value(); + certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + certifiedResource.setVersion("1.0"); + ; + + Either getLatestResult = Either.left(certifiedResource); + when(resourceOperation.getLatestByName(resourceExist.getName(), true)).thenReturn(getLatestResult); + when(resourceOperation.overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean())).thenReturn(getLatestResult); + + when(lifecycleBl.changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); + + Resource resourceToUpdtae = createResourceObject(false); + + Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(resourceOperation, Mockito.times(1)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean()); + Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceNotExist() { + Resource resourceToUpdtae = createResourceObject(false); + + Either getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(resourceOperation.getLatestByName(resourceToUpdtae.getName(), true)).thenReturn(getLatestResult); + + Either getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(resourceOperation.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName(), true)).thenReturn(getLatestResult); + + Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(resourceOperation, Mockito.times(0)).overrideResource(Mockito.any(Resource.class), Mockito.any(Resource.class), Mockito.anyBoolean()); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { + Resource basic = createResourceObject(true); + + Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1"); + List properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); + when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); + Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_FailedWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1.5"); + List properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); + + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); + Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isRight()); + } + + @Test + public void testDeleteMarkedResourcesNoResources() { + List ids = new ArrayList(); + Either, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(resourceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + assertTrue(deleteMarkedResources.left().value().isEmpty()); + + Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); + + } + + @Test + public void testDeleteMarkedResources() { + List ids = new ArrayList(); + String resourceInUse = "123"; + ids.add(resourceInUse); + String resourceFree = "456"; + ids.add(resourceFree); + Either, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(resourceOperation.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); + + Either resourceInUseResponse = Either.left(true); + Either resourceFreeResponse = Either.left(false); + + List artifacts = new ArrayList(); + Either, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); + when(resourceOperation.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); + + when(resourceOperation.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(resourceOperation.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either eitherDelete = Either.left(new Resource()); + when(resourceOperation.deleteComponent(resourceFree, true)).thenReturn(eitherDelete); + + when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); + + Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + List resourceIdList = deleteMarkedResources.left().value(); + assertFalse(resourceIdList.isEmpty()); + assertTrue(resourceIdList.contains(resourceFree)); + assertFalse(resourceIdList.contains(resourceInUse)); + + Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java new file mode 100644 index 0000000000..d1597886d8 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -0,0 +1,284 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class ResourceInstanceBusinessLogicTest { + + private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; + private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; + private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; + private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; + private static final String SERVICE_ID = "MyServiceId"; + private static final String HEAT_LABEL = "myHeat"; + private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; + private static final String USER_ID = "jh0003"; + private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); + + static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); + + @InjectMocks + static ServiceComponentInstanceBusinessLogic bl = new ServiceComponentInstanceBusinessLogic(); + + public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); + public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); + public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // @BeforeClass + public static void setup() { + + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + Map placeHolderData = (Map) deploymentResourceArtifacts.get(ComponentInstanceBusinessLogic.HEAT_ENV_NAME); + + ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); + Map artifacts = new HashMap(); + artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); + Either, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT)).thenReturn(eitherGetResourceArtifact); + + ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); + Map artifactsNoPayload = new HashMap(); + artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); + Either, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT)).thenReturn(eitherGetResourceArtifactNoPayload); + + ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); + Map artifactsNoParams = new HashMap(); + artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); + Either, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT)).thenReturn(eitherGetResourceArtifactNoParams); + + Either eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); + Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); + + Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap(AuditingFieldsKeysEnum.class)); + + Either eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyBoolean())).thenReturn(eitherArtifact); + + Either eitherUser = Either.left(adminUser); + Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); + + Object lightService = new Service(); + Either eitherLightService = Either.left(lightService); + Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); + + Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class)); + + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); + setup(); + } + + @Test + public void testAddResourceInstanceArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null); + assertTrue(addArtifactsRes.isLeft()); + + Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); + assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); + + ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); + assertNotNull(heatEnvDefinition); + + List heatParameters = heatDefinition.getHeatParameters(); + assertNotNull(heatParameters); + + List heatEnvParameters = heatEnvDefinition.getHeatParameters(); + assertNotNull(heatEnvParameters); + + assertEquals(heatParameters.size(), heatEnvParameters.size()); + + int index = 0; + for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { + HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); + assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); + assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); + assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); + assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); + assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); + // current of heat parameter should be the default for heat env + // parameter + assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); + + index++; + } + } + + @Test + public void testAddResourceInstanceArtifactsNoParams() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null); + assertTrue(addArtifactsRes.isLeft()); + + Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); + assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); + + ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); + assertNotNull(heatEnvDefinition); + + List heatParameters = heatDefinition.getHeatParameters(); + assertNull(heatParameters); + + List heatEnvParameters = heatEnvDefinition.getHeatParameters(); + assertNull(heatEnvParameters); + + } + + @Test + public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, USER_ID, false, null); + assertTrue(addArtifactsRes.isLeft()); + + Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 0); + + Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyBoolean()); + } + + private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".yml"); + artifactInfo.setArtifactType("HEAT"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + artifactInfo.setUserIdCreator(userId); + String fullName = "Jim H"; + artifactInfo.setUpdaterFullName(fullName); + // long time = System.currentTimeMillis(); + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(userId); + artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); + + if (!placeholderOnly) { + artifactInfo.setEsId(artifactInfo.getUniqueId()); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + if (withHeatParams) { + List heatParams = new ArrayList(); + HeatParameterDefinition heatParam = new HeatParameterDefinition(); + heatParam.setCurrentValue("11"); + heatParam.setDefaultValue("22"); + heatParam.setDescription("desc"); + heatParam.setName("myParam"); + heatParam.setType("number"); + heatParams.add(heatParam); + artifactInfo.setHeatParameters(heatParams); + } + } + + return artifactInfo; + } + + private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java new file mode 100644 index 0000000000..48cd83a7c8 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.CertificationChangeTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CertificationChangeTransitionTest extends LifecycleTestBase { + + private CertificationChangeTransition certifyTransitionObj = null; + private CertificationChangeTransition certificationCancelObj = null; + private CertificationChangeTransition certificationFailObj = null; + + private ComponentsUtils componentsUtils = new ComponentsUtils(); + private String resourceName = "myResource"; + private User owner = null; + + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class); + + Resource resource; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + + super.setup(); + componentsUtils.Init(); + // checkout transition object + certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation); + certifyTransitionObj.setConfigurationManager(configurationManager); + + certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation); + certificationCancelObj.setConfigurationManager(configurationManager); + + certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, lcOperation); + certificationFailObj.setConfigurationManager(configurationManager); + + owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + when(artifactsManager.deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + resource = createResourceObject(false); + } + + @Test + public void testStateValidationSuccess() { + + Either changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testStateValidationFail() { + + // checkout + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + assertValidationStateErrorResponse(validateBeforeTransition); + + // checkin + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertValidationStateErrorResponse(validateBeforeTransition); + + // rfc + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertValidationStateErrorResponse(validateBeforeTransition); + + // certified + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertValidationStateErrorResponse(validateBeforeTransition); + + } + + @Test + public void testRolesFail() { + Either changeStateResult; + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRolesSuccess() { + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.ADMIN.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + } + + private void assertValidationStateErrorResponse(Either validateBeforeTransition) { + assertEquals(validateBeforeTransition.isRight(), true); + ResponseFormat error = validateBeforeTransition.right().value(); + Either changeStateResult = Either.right(error); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java new file mode 100644 index 0000000000..b45aa61de1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java @@ -0,0 +1,230 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.CertificationRequestTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.tosca.ToscaError; +import org.openecomp.sdc.be.tosca.ToscaExportHandler; +import org.openecomp.sdc.be.tosca.ToscaRepresentation; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CertificationRequestTest extends LifecycleTestBase { + + private ComponentsUtils componentsUtils = new ComponentsUtils(); + + protected ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = Mockito.mock(ServiceDistributionArtifactsBuilder.class); + protected ServiceBusinessLogic serviceBusinessLogic = Mockito.mock(ServiceBusinessLogic.class); + protected ResourceOperation resourceOperation = Mockito.mock(ResourceOperation.class); + protected CapabilityOperation capabilityOperation = Mockito.mock(CapabilityOperation.class); + protected ToscaExportHandler toscaExportUtils = Mockito.mock(ToscaExportHandler.class); + @InjectMocks + private CertificationRequestTransition rfcObj = new CertificationRequestTransition(componentsUtils, lcOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils); + + protected ToscaRepresentation toscaRepresentation = Mockito.mock(ToscaRepresentation.class); + + @Before + public void setup() { + Mockito.reset(resourceOperation); + MockitoAnnotations.initMocks(this); + super.setup(); + + // checkout transition object + rfcObj.setLifeCycleOperation(lcOperation); + // checkoutObj.setAuditingManager(iAuditingManager); + rfcObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + + Either either = Either.left(toscaRepresentation); + when(toscaExportUtils.exportComponent(Mockito.anyObject())).thenReturn(either); + + } + + @Test + public void testCheckoutStateValidation() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testAlreadyRfc() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testAlreadyCertified() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() { + Resource resource = new Resource(); + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() { + Resource resource = new Resource(); + List riList = new ArrayList(); + ComponentInstance ri = new ComponentInstance(); + ri.setComponentVersion("2.0"); + riList.add(ri); + resource.setComponentInstances(riList); + + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() { + Resource resource = createVFWithRI("0.3"); + + simulateCertifiedVersionExistForRI(); + + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() { + Resource resource = createVFWithRI("1.3"); + + simulateCertifiedVersionExistForRI(); + + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + private void simulateCertifiedVersionExistForRI() { + Resource dummyResource = new Resource(); + Either, StorageOperationStatus> result = Either.left(new ArrayList() { + { + add(dummyResource); + } + }); + Mockito.when(resourceOperation.getResource(Mockito.anyString())).thenReturn(Either.left(dummyResource)); + Mockito.when(resourceOperation.findLastCertifiedResourceByUUID(Mockito.any(Resource.class))).thenReturn(result); + } + + private Resource createVFWithRI(String riVersion) { + Resource resource = new Resource(); + List riList = new ArrayList(); + ComponentInstance ri = new ComponentInstance(); + + ri.setComponentVersion(riVersion); + ri.setComponentUid("someUniqueId"); + riList.add(ri); + resource.setComponentInstances(riList); + return resource; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java new file mode 100644 index 0000000000..e0d942e2bc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.lifecycle.CheckinTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CheckinTest extends LifecycleTestBase { + + private CheckinTransition checkinObj = null; + private ComponentsUtils componentsUtils = new ComponentsUtils(); + + @Before + public void setup() { + + super.setup(); + + // checkout transition object + checkinObj = new CheckinTransition(componentsUtils, lcOperation); + checkinObj.setLifeCycleOperation(lcOperation); + checkinObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + } + + @Test + public void testSimpleCheckin() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testSimpleServiceCheckin() { + Either changeStateResult; + Service service = createServiceObject(false); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testCheckinTwiceValidation() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(owner.isLeft()); + // changeStateResult = checkinObj.changeStateOperation(resource, user, + // owner.left().value()); + Either validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckinTwiceValidation() { + Either changeStateResult; + Service service = createServiceObject(false); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(owner.isLeft()); + + Either validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCheckoutByAnotherUserValidation() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkinObj.changeStateOperation(resource, + // modifier, owner); + Either validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckoutByAnotherUserValidation() { + Either changeStateResult; + Service service = createServiceObject(false); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java new file mode 100644 index 0000000000..4a81653e14 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.lifecycle.CheckoutTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class CheckoutTest extends LifecycleTestBase { + + private CheckoutTransition checkoutObj = null; + private ComponentsUtils componentsUtils = new ComponentsUtils(); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + + @Before + public void setup() { + + super.setup(); + + // checkout transition object + checkoutObj = new CheckoutTransition(componentsUtils, lcOperation); + checkoutObj.setLifeCycleOperation(lcOperation); + checkoutObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + + } + + @Test + public void testCheckoutStateValidation() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testAlreadyCheckout() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testReadyForCertification() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + + // if modifier = owner + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // else + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + + // admin + modifier.setRole(Role.ADMIN.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // designer + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRoles() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isLeft(), true); + + modifier.setRole(Role.TESTER.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java new file mode 100644 index 0000000000..734a3d9bde --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; + +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.AuditingMockManager; +import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; +import junit.framework.Assert; + +public class LifecycleTestBase { + private static Logger log = LoggerFactory.getLogger(LifecycleTestBase.class.getName()); + @InjectMocks + protected final ServletContext servletContext = Mockito.mock(ServletContext.class); + protected IAuditingManager iAuditingManager = null; + protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + protected LifecycleOperation lcOperation = Mockito.mock(LifecycleOperation.class); + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; + protected User user = null; + protected Resource resourceResponse; + protected Service serviceResponse; + protected ConfigurationManager configurationManager = null; + protected ResponseFormatManager responseManager = null; + + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + + // Init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + // Auditing + iAuditingManager = new AuditingMockManager("lll"); + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); + // when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(LifecycleOperation.class)).thenReturn(lcOperation); + when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); + + // Resource Operation mock methods + // getCount + + // createResource + resourceResponse = createResourceObject(true); + serviceResponse = createServiceObject(true); + Either eitherCreate = Either.left(resourceResponse); + Either eitherCreateComponent = Either.left(resourceResponse); + when((Either) lcOperation.checkoutComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))) + .thenAnswer(createAnswer(eitherCreate)); + when(lcOperation.checkoutComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))).thenAnswer(createAnswer(eitherCreateComponent)); + + when((Either) lcOperation.checkinComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))) + .thenAnswer(createAnswer(eitherCreate)); + + when((Either) lcOperation.requestCertificationComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))) + .thenAnswer(createAnswer(eitherCreate)); + when(lcOperation.requestCertificationComponent(Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Component.class), Mockito.any(User.class), Mockito.any(User.class), Mockito.any(Boolean.class))).thenAnswer(createAnswer(eitherCreateComponent)); + + Either getOwnerResult = Either.left(user); + when(lcOperation.getComponentOwner(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource), Mockito.any(Boolean.class))).thenReturn(getOwnerResult); + when(lcOperation.getComponentOwner(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.any(Boolean.class))).thenReturn(getOwnerResult); + + responseManager = ResponseFormatManager.getInstance(); + + } + + public static Answer createAnswer(final T value) { + Answer dummy = new Answer() { + @Override + public T answer(InvocationOnMock invocation) throws Throwable { + return value; + } + + }; + return dummy; + } + + protected Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName("MyResourceName"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("yavivi"); + resource.setIcon("MyIcon.jpg"); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(resource)); + return resource; + } + + protected Service createServiceObject(boolean b) { + Service service = new Service(); + service.setName("MyServiceName"); + service.addCategory("VoIP", null); + service.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + service.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + service.setContactId("aa0001"); + service.setIcon("MyIcon.jpg"); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + log.debug(gson.toJson(service)); + return service; + } + + protected void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + Assert.assertTrue(createResponse.isRight()); + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + Assert.assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + Assert.assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + protected void assertServiceResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + Assert.assertTrue(createResponse.isRight()); + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + Assert.assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + Assert.assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java new file mode 100644 index 0000000000..6cc0385667 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.lifecycle; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.lifecycle.UndoCheckoutTransition; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +public class UndoCheckoutTest extends LifecycleTestBase { + + private UndoCheckoutTransition undoCheckoutObj = null; + private ComponentsUtils componentsUtils = new ComponentsUtils(); + + @Before + public void setup() { + + super.setup(); + + // checkout transition object + undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, lcOperation); + undoCheckoutObj.setLifeCycleOperation(lcOperation); + undoCheckoutObj.setConfigurationManager(configurationManager); + componentsUtils.Init(); + + } + + @Test + public void testResourceNotCheckedOutValidation() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testDifferentResourceOwnerValidation() { + Either changeStateResult; + Resource resource = createResourceObject(false); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + Either ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java new file mode 100644 index 0000000000..104cd14e7a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.distribution; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.core.Response; + +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; +import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.distribution.AuditHandler; +import org.openecomp.sdc.be.distribution.DistributionBusinessLogic; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; +import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; +import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse; +import org.openecomp.sdc.common.datastructure.Wrapper; + +public class DistributionBusinessLogicTest extends BaseConfDependentTest { + + @InjectMocks + DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class); + + CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + AuditHandler auditHandler = Mockito.mock(AuditHandler.class); + + @Test + public void testHandleRegistrationHappyScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse); + + Wrapper responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity(); + + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + } + + @Test + public void testHandleRegistrationFailedScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR, HttpStatus.SC_SERVICE_UNAVAILABLE); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + + Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse); + Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER)) + .thenReturn(errorResponse); + + Wrapper responseWrapper = new Wrapper<>(); + + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + + } + + @Test + public void testHandleUnRegistrationHappyScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + + Mockito.when(cambriaHandler.unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse); + + Wrapper responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER); + + Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + + } + + @Test + public void testHandleUnRegistrationFailedScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); + + Wrapper responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER)) + .thenReturn(errorResponse); + + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.AUTHENTICATION_ERROR); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + + } + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + Mockito.reset(cambriaHandler); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java new file mode 100644 index 0000000000..d6274ad90e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.distribution.servlet; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.http.HttpStatus; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.distribution.AuditHandler; +import org.openecomp.sdc.be.distribution.DistributionBusinessLogic; +import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; +import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; +import org.openecomp.sdc.be.distribution.servlet.DistributionServlet; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class DistributionServletTest extends JerseyTest { + + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + public static final DistributionBusinessLogic distributionBusinessLogic = Mockito.mock(DistributionBusinessLogic.class); + public static final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class); + + public static final String ENV_NAME = "myEnv"; + public static final String NOTIFICATION_TOPIC = ENV_NAME + "_Notification"; + public static final String STATUS_TOPIC = ENV_NAME + "_Status"; + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("myApplicationInstanceID"); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(DistributionBusinessLogic.class)).thenReturn(distributionBusinessLogic); + when(distributionBusinessLogic.getDistributionEngine()).thenReturn(distributionEngine); + when(distributionEngine.isEnvironmentAvailable(ENV_NAME)).thenReturn(StorageOperationStatus.OK); + when(distributionEngine.isEnvironmentAvailable()).thenReturn(StorageOperationStatus.OK); + + mockBusinessLogicResponse(); + + } + + private static void mockBusinessLogicResponse() { + // Mock Register + Mockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Wrapper responseWrapper = (Wrapper) args[0]; + TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); + okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); + okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + + return true; + } + }).when(distributionBusinessLogic).handleRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); + + // Mock Unregister + Mockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Wrapper responseWrapper = (Wrapper) args[0]; + TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); + okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); + okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + + return true; + } + }).when(distributionBusinessLogic).handleUnRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); + } + + @Test + public void registerSuccessTest() { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME); + Response response = target().path("/v1/registerForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + } + + @Test + public void unRegisterSuccessTest() { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME); + Response response = target().path("/v1/unRegisterForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + } + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(DistributionServlet.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java new file mode 100644 index 0000000000..e4f46dd4dd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.ecomp; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.common.config.EcompClassification; +import org.openecomp.sdc.common.config.EcompErrorCode; +import org.openecomp.sdc.common.config.EcompErrorEnum; +import org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv; + +import static org.junit.Assert.assertTrue; + +public class GenerateEcompErrorFileTest { + + @Test + public void verifyNoDuplicatesInEcompErrorCodes() { + + EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values(); + + Map> map = new HashMap>(); + for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) { + + List list = map.get(ecompErrorEnum.getEcompErrorCode()); + if (list == null) { + list = new ArrayList<>(); + + list.add(ecompErrorEnum.getClassification()); + + map.put(ecompErrorEnum.getEcompErrorCode(), list); + } else { + if (list.contains(ecompErrorEnum.getClassification())) { + assertTrue(ecompErrorEnum.getEcompErrorCode() + " already defined with ecomp classification " + ecompErrorEnum.getClassification(), false); + } else { + list.add(ecompErrorEnum.getClassification()); + } + + } + + } + + } + + @Test + public void generateEcompErrorFileInTarget() { + + GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); + boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false); + assertTrue("check result from file generation", result); + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java new file mode 100644 index 0000000000..d41e95da9d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; +import org.apache.commons.codec.binary.Base64; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.exception.ResponseFormat; + +import fj.data.Either; + +import static org.mockito.Mockito.mock; + +public class AbstractValidationsServletTest { + private static AbstractValidationsServlet servlet = mock(AbstractValidationsServlet.class); + + @SuppressWarnings("unchecked") + @Test + public void testGetScarFromPayload() { + + String payloadName = "valid_vf.csar"; + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + Either, ResponseFormat> returnValue = null; + try { + path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + UploadResourceInfo resourceInfo = new UploadResourceInfo(); + resourceInfo.setPayloadName(payloadName); + resourceInfo.setPayloadData(payloadData); + Method privateMethod = null; + privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getScarFromPayload", UploadResourceInfo.class); + privateMethod.setAccessible(true); + returnValue = (Either, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo); + } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + Assert.assertTrue(returnValue.isLeft()); + Map csar = returnValue.left().value(); + Assert.assertTrue(csar != null); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java new file mode 100644 index 0000000000..2dda0f5d14 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import java.util.HashSet; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Application; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.server.ResourceConfig; +import org.mockito.Mockito; +import org.openecomp.sdc.be.servlets.ResourceUploadServlet; + +public class ApplicationConfig extends Application { + + public Set> getClasses() { + final Set> resources = new HashSet>(); + + // Add your resources. + resources.add(ResourceUploadServlet.class); + resources.add(MultiPart.class); + resources.add(FormDataContentDisposition.class); + + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + ResourceConfig resourceConfig = ResourceConfig.forApplication(this); + + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // TODO Auto-generated method stub + bind(request).to(HttpServletRequest.class); + } + }); + + return resources; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java new file mode 100644 index 0000000000..5e1e4577e2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.Arrays; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.ResourcesServlet; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.http.HttpStatus; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class ResourceServletTest extends JerseyTest { + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); + final static HttpSession session = Mockito.mock(HttpSession.class); + final static ServletContext servletContext = Mockito.mock(ServletContext.class); + final static WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + final static WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + String userId = "jh0003"; + User user = new User(); + user.setUserId(userId); + user.setRole(Role.ADMIN.name()); + Either eitherUser = Either.left(user); + when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); + + ImmutablePair pair = new ImmutablePair(new Resource(), ActionStatus.OK); + Either, ResponseFormat> ret = Either.left(pair); + when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(ret); + + } + + @Before + public void beforeTest() { + Mockito.reset(componentUtils); + + Mockito.doAnswer(new Answer() { + public ResponseFormat answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + ActionStatus action = (ActionStatus) args[0]; + ResponseFormat resp = (action == ActionStatus.OK) ? new ResponseFormat(HttpStatus.CREATED.value()) : new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR.value()); + return resp; + } + }).when(componentUtils).getResponseFormat(Mockito.any(ActionStatus.class)); + + } + + @Test + public void testHappyScenarioTest() { + UploadResourceInfo validJson = buildValidJson(); + setMD5OnRequest(true, validJson); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK); + assertTrue(response.getStatus() == HttpStatus.CREATED.value()); + + } + + @Test + public void testNonValidMd5Fail() { + UploadResourceInfo validJson = buildValidJson(); + + setMD5OnRequest(false, validJson); + + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); + assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); + + } + + @Test + public void testNonValidPayloadNameFail() { + UploadResourceInfo mdJson = buildValidJson(); + mdJson.setPayloadName("myCompute.xml"); + + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION); + + } + + @Test + public void testNullPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + mdJson.setPayloadData(null); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD); + + } + + @Test + public void testNonYmlPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + String payload = "{ json : { isNot : yaml } "; + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE); + + } + + @Test + public void testNonToscaPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE); + + } + + @Test + public void testServiceToscaPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n" + + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); + + } + + @Test + public void testMultipleResourcesInPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE); + + } + + @Test + public void testNonValidNameSpaceInPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE); + + } + + private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) { + Base64.encodeBase64(payload.getBytes()); + mdJson.setPayloadData(payload); + } + + private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) { + setMD5OnRequest(true, mdJson); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload); + assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); + } + + private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) { + String md5 = (isValid) ? GeneralUtility.calculateMD5ByString(gson.toJson(json)) : "stam="; + when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5); + + } + + private UploadResourceInfo buildValidJson() { + UploadResourceInfo ret = new UploadResourceInfo(); + ret.setName("MyCompute"); + ret.setPayloadName("MyCompute.yml"); + ret.addSubCategory("Application Layer 4+", "Application Servers"); + ret.setDescription("ResourceDescription"); + ret.setVendorName("VendorName"); + ret.setVendorRelease("VendorRelease"); + ret.setContactId("AT1234"); + ret.setIcon("router"); + ret.setTags(Arrays.asList(new String[] { "MyCompute" })); + ret.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl"); + return ret; + } + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(ResourcesServlet.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java new file mode 100644 index 0000000000..252e9d8fbc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.resources.api.IResourceUploader; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.servlets.ResourceUploadServlet; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; + +public class ResourceUploadServletTest extends JerseyTest { + private static Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class.getName()); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpSession session = Mockito.mock(HttpSession.class); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class); + final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class); + + Gson gson = new Gson(); + + public void zipDirectory() { + + } + + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader); + when(iResourceUploader.saveArtifact((ESArtifactData) anyObject(), eq(true))).thenReturn(ResourceUploadStatus.OK); + when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager); + } + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(ResourceUploadServlet.class); + + resourceConfig.register(MultiPartFeature.class); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // The below code was cut-pasted to here from setup() because + // due to it now has + // to be executed during servlet initialization + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { + + when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); + + } + + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + } + }); + + return resourceConfig; + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + public class DelegatingServletInputStream extends ServletInputStream { + + private final InputStream sourceStream; + + /** + * Create a DelegatingServletInputStream for the given source stream. + * + * @param sourceStream + * the source stream (never null) + */ + public DelegatingServletInputStream(InputStream sourceStream) { + // Assert.notNull(sourceStream, + // "Source InputStream must not be null"); + this.sourceStream = sourceStream; + } + + /** + * Return the underlying source stream (never null). + */ + public final InputStream getSourceStream() { + return this.sourceStream; + } + + public int read() throws IOException { + return this.sourceStream.read(); + } + + public void close() throws IOException { + super.close(); + this.sourceStream.close(); + } + + } + + @Test + public void testMultipart() { + FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip")); + + List tags = new ArrayList(); + tags.add("tag1"); + tags.add("tag2"); + UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null); + + FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE); + MultiPart multipartEntity = new FormDataMultiPart(); + multipartEntity.bodyPart(filePart); + multipartEntity.bodyPart(metadataPart); + + Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); + log.debug("{}", response); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java new file mode 100644 index 0000000000..420cbcca6b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.grizzly.http.util.HttpStatus; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.TypesUploadServlet; +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.springframework.web.context.WebApplicationContext; + +import fj.data.Either; + +public class TypesUploadServletTest extends JerseyTest { + + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class); + public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + String userId = "jh0003"; + User user = new User(); + user.setUserId(userId); + user.setRole(Role.ADMIN.name()); + Either eitherUser = Either.left(user); + when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); + when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode()); + when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); + + } + + @Test + public void creatingCapabilityTypeSuccessTest() { + List emptyList = new ArrayList(); + Either, ResponseFormat> either = Either.left(emptyList); + when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either); + FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip", new File("src/test/resources/types/capabilityTypes.zip")); + MultiPart multipartEntity = new FormDataMultiPart(); + multipartEntity.bodyPart(filePart); + + Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); + + assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode()); + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + @Override + protected Application configure() { + ResourceConfig resourceConfig = new ResourceConfig(TypesUploadServlet.class); + + resourceConfig.register(MultiPartFeature.class); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // The below code was cut-pasted to here from setup() because + // due to it now has + // to be executed during servlet initialization + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { + + when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); + + } + + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + } + }); + + return resourceConfig; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java new file mode 100644 index 0000000000..ed69f104d2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.Application; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Before; +import org.junit.BeforeClass; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.UserAdminServlet; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.http.HttpStatus; +import org.springframework.web.context.WebApplicationContext; + +import com.google.gson.Gson; + +import fj.data.Either; + +public class UserAdminServletTest extends JerseyTest { + + final static HttpServletRequest request = mock(HttpServletRequest.class); + final static HttpSession session = mock(HttpSession.class); + final static ServletContext servletContext = mock(ServletContext.class); + final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class); + final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class); + final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class); + final static AuditingManager auditingManager = mock(AuditingManager.class); + final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + final static ResponseFormat okResponseFormat = mock(ResponseFormat.class); + + final static String ADMIN_ATT_UID = "jh0003"; + Gson gson = new Gson(); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + + when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager); + when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils); + when(componentsUtils.getAuditingManager()).thenReturn(auditingManager); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat); + when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value()); + + } + + @Before + public void beforeTest() { + reset(userAdminManager); + doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false); + + reset(request); + when(request.getSession()).thenReturn(session); + when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID); + } + + /* + * @Test public void deactivateUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); Either eitherActiveUser = buildEitherUser(userToDeleteUserId, true); + * User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId); + * + * Either eitherInactiveUser = buildEitherUser(userToDeleteUserId, false); doReturn(eitherInactiveUser).when(userAdminManager).deActivateUser( adminUser, userToDelete.getUserId()); + * + * + * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(1)).deActivateUser(adminUser, userToDelete.getUserId()); } + * + * + * @Test public void forceDeleteUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; when(request.getHeader(User.FORCE_DELETE_HEADER_FLAG)).thenReturn(User. FORCE_DELETE_HEADER_FLAG); + * + * User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); + * + * Either eitherActiveUser = buildEitherUser(userToDeleteUserId, true); User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId); + * + * Either eitherUser = buildEitherUser(userToDeleteUserId, true); doReturn(eitherUser).when(userAdminManager).deleteUser(userToDelete. getUserId()); + * + * + * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(0)).deActivateUser(adminUser, userToDelete.getUserId()); + * verify(userAdminManager, times(1)).deleteUser(userToDelete.getUserId()); } + */ + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class); + + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } + + private static Either buildEitherUser(String userId, boolean isActive) { + User user = new User(); + user.setUserId(userId); + user.setRole(UserRoleEnum.ADMIN.getName()); + if (!isActive) { + user.setStatus(UserStatusEnum.INACTIVE); + } + return Either.left(user); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java new file mode 100644 index 0000000000..4b01b4fd61 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/user/UserAdminManagerTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.user; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.api.IUsersDAO; +import org.openecomp.sdc.be.dao.impl.Neo4jUsersDAO; +import org.openecomp.sdc.be.resources.data.UserData; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +public class UserAdminManagerTest { + + final IUsersDAO usersDao = Mockito.mock(Neo4jUsersDAO.class); + Gson gson; + + @Before + public void setup() { + Either eitherOk = Either.right(ActionStatus.OK); + gson = new GsonBuilder().setPrettyPrinting().create(); + when(usersDao.getUserData(anyString())).thenReturn(eitherOk); + when(usersDao.saveUserData((UserData) anyObject())).thenReturn(ActionStatus.OK); + when(usersDao.updateUserData((UserData) anyObject())).thenReturn(ActionStatus.OK); + when(usersDao.deleteUserData(anyString())).thenReturn(ActionStatus.OK); + } + + // @Test + // public void testCreateUser() { + // String json = "{\"firstName\": \"James\",\"lastName\": + // \"Brown\",\"userId\": \"jb1234u\",\"email\": + // \"jb1234u@sdc.com\",\"role\": \"ADMIN\"}"; + // UserData user = gson.fromJson(json, UserData.class); + // Either either = + // UserAdminManager.getInstance().createUser(user); + // assertTrue(either.isRight()); + // assertEquals(ActionStatus.OK, either.right().value()); + // } + // + // + // @Test + // public void testCreateUserInvalidEmail() { + // String json = "{\"firstName\": \"James\",\"lastName\": + // \"Brown\",\"userId\": \"jb1234u\",\"email\": \"@sdc.com\",\"role\": + // \"ADMIN\"}"; + // UserData user = gson.fromJson(json, UserData.class); + // Either either = + // UserAdminManager.getInstance().createUser(user); + // assertTrue(either.isRight()); + // assertEquals(ActionStatus.INVALID_EMAIL_ADDRESS, either.right().value()); + // } + // + // @Test + // public void testCreateUserInvalidRole() { + // String json = "{\"firstName\": \"James\",\"lastName\": + // \"Brown\",\"userId\": \"jb1234u\",\"email\": + // \"jb1234u@sdc.com\",\"role\": \"MIN\"}"; + // UserData user = gson.fromJson(json, UserData.class); + // Either either = + // UserAdminManager.getInstance().createUser(user); + // assertTrue(either.isRight()); + // assertEquals(ActionStatus.INVALID_EMAIL_ADDRESS, either.right().value()); + // } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java new file mode 100644 index 0000000000..bf87033bfe --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java @@ -0,0 +1,437 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.transaction.mngr; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; +import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.transaction.api.IDBAction; +import org.openecomp.sdc.common.transaction.api.RollbackHandler; +import org.openecomp.sdc.common.transaction.api.TransactionUtils; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.ActionTypeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum; +import org.openecomp.sdc.common.transaction.mngr.CommitManager; +import org.openecomp.sdc.common.transaction.mngr.TransactionSdncImpl; +import org.slf4j.Logger; + +import fj.data.Either; + +public class SdncTransactionTest { + private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class); + private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static Logger log = Mockito.spy(Logger.class); + private static int transactionId = 0; + private static ConfigurationManager configurationManager; + + public enum TestAction { + TitanAction, Rollback, GeneralAction + } + + public enum TestResponse { + TitanResponseSuccess, GeneralSuccess + } + + @BeforeClass + public static void beforeClass() { + TransactionSdncImpl.setLog(log); + CommitManager.setLog(log); + RollbackHandler.setLog(log); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + } + + @Before + public void beforeTest() { + reset(log); + reset(esCatalogDao); + reset(titanGenericDao); + } + + @Test + public void testInvokeTitanAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doBasicTitanAction(transactionId, tx, false, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + } + + @Test + public void testInvokeESAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doESAddArtifactAction(transactionId, tx, true, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + } + + @Test + public void testfinishTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + } + + @Test + public void testFinishOnClosedTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + + TransactionCodeEnum finishTransaction = tx.finishTransaction(); + assertTrue(finishTransaction == TransactionCodeEnum.TRANSACTION_CLOSED); + // verify(log).error(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, + // transactionId, TransactionStatusEnum.CLOSED.name(), + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, TransactionStatusEnum.CLOSED.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + } + + @Test + public void testCallingLastActionTwice() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doBasicTitanAction(transactionId, tx, true, true); + Either doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false); + assertTrue(doBasicTitanAction.isRight()); + assertTrue(tx.getStatus() != TransactionStatusEnum.OPEN); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log).error( LogMessages.DOUBLE_FINISH_FLAG_ACTION, + // transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testActionOnClosedTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + + Either eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); + assertTrue(eitherESResult.isRight()); + assertTrue(eitherESResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + Either eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + assertTrue(eitherTitanResult.isRight()); + assertTrue(eitherTitanResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + Either eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess), + createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess)); + assertTrue(eitherGeneralDBAction.isRight()); + assertTrue(eitherGeneralDBAction.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + // verify(log, times(3)).error(LogMessages.ACTION_ON_CLOSED_TRANSACTION, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(3)).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + } + + @Test + public void testBasicHappyScenario() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doBasicTitanAction(transactionId, tx, false, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + + doESAddArtifactAction(transactionId, tx, true, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + + doFinishTransaction(transactionId, tx, true); + + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + } + + @Test + public void testRollbackSucceededOnAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + String crushMessage = "DB Crush Simulation"; + Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + + assertTrue(eitherTransactionResult.isRight()); + assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.TITAN.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackFailedOnAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doESAddArtifactAction(transactionId, tx, false, true); + + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED); + String crushMessage = "DB Crush Simulation"; + Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + + assertTrue(eitherTransactionResult.isRight()); + assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); + assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_FAILED); + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.TITAN.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackSucceededOnCommit() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + doBasicTitanAction(transactionId, tx, true, true); + + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackFailedOnCommit() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + doBasicTitanAction(transactionId, tx, true, true); + + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + String esError = "No Connection to Es"; + Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString()); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_FAILED); + assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log).error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, + // transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), esError, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, + // DBTypeEnum.ELASTIC_SEARCH.name(), esError, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testInvokeGeneralAction() { + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess); + IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess); + String crushMessage = "No DB Connection"; + IDBAction crushingAction = createCrushingAction(TestAction.GeneralAction, crushMessage); + + Either eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, generalAction, rollbackAction); + assertTrue(eitherResult.isLeft()); + assertTrue(eitherResult.left().value() == TestResponse.GeneralSuccess); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, crushingAction, rollbackAction); + + assertTrue(eitherResult.isRight()); + assertTrue(eitherResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(2)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(2)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + } + + private Either doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Add Titan Action + Either eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + if (isVerifyAction) { + // Check Titan Action + assertTrue(eitherTitanResult.isLeft()); + assertTrue(eitherTitanResult.left().value() == TestResponse.TitanResponseSuccess); + verify(log).debug(TestAction.TitanAction.name()); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verifyNoErrorsInLog(); + verifyNoInfoInLog(); + } + return eitherTitanResult; + } + + private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) { + // Prerequisite finishTransaction + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + if (isVerifyAction) { + // Check finishTransaction + verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + assertTrue(transactionCode == TransactionCodeEnum.SUCCESS); + } + return transactionCode; + } + + private void doESAddArtifactAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Prerequisite ES Action + Either eitherBeforeAddArtifact = Either.right(ResourceUploadStatus.NOT_EXIST); + when(esCatalogDao.getArtifact(Mockito.anyString())).thenReturn(eitherBeforeAddArtifact); + + // Add ES Action + Either eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); + + if (isVerifyAction) { + // Check Titan Action + assertTrue(eitherEsAction.isLeft()); + assertTrue(eitherEsAction.left().value() == DBActionCodeEnum.SUCCESS); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verifyNoErrorsInLog(); + verifyNoInfoInLog(); + } + } + + private ESArtifactData createDummyArtifactData() { + String strData = "qweqwqweqw34e4wrwer"; + String myNodeType = "MyNewNodeType"; + ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes()); + return arData; + } + + private void verifyNoErrorsInLog() { + verify(log, Mockito.times(0)).error(Mockito.anyString(), Mockito.any(Object[].class)); + verify(log, Mockito.times(0)).error(Mockito.anyString()); + } + + private void verifyNoInfoInLog() { + verify(log, Mockito.times(0)).info(Mockito.anyString(), Mockito.any(Object[].class)); + verify(log, Mockito.times(0)).info(Mockito.anyString()); + } + + private IDBAction createBasicAction(TestAction action, TestResponse resp) { + final TestAction finalAction = action; + final TestResponse finalResp = resp; + return new IDBAction() { + @Override + public TestResponse doAction() { + log.debug(finalAction.name()); + return finalResp; + } + }; + } + + private IDBAction createCrushingAction(TestAction action, final String crushMessage) { + final TestAction finalAction = action; + return new IDBAction() { + @Override + public TestResponse doAction() { + log.debug(finalAction.name()); + throw new RuntimeException(crushMessage); + } + }; + } + + public int getNextTransactionId() { + transactionId++; + return transactionId; + } +} diff --git a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml new file mode 100644 index 0000000000..18d23707b1 --- /dev/null +++ b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml @@ -0,0 +1,427 @@ +identificationHeaderFields: + - HTTP_IV_USER + - HTTP_CSP_FIRSTNAME + - HTTP_CSP_LASTNAME + - HTTP_IV_REMOTE_ADDRESS + - HTTP_CSP_WSTYPE + + + +# catalog backend hostname +beFqdn: localhost + +# catalog backend http port +beHttpPort: 8080 + +# catalog backend http context +beContext: /sdc/rest/config/get + +# catalog backend protocol +beProtocol: http + +# catalog backend ssl port +beSslPort: 8443 + +version: 1.0 +released: 2012-11-30 + +titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties +titanInMemoryGraph: true +titanLockTimeout: 600 +titanReconnectIntervalInSeconds: 3 +titanHealthCheckReadTimeout: 1 +esReconnectIntervalInSeconds: 3 +uebHealthCheckReconnectIntervalInSeconds: 15 +uebHealthCheckReadTimeout: 4 + +# Protocols +protocols: + - http + - https + +# Users +users: + tom: passwd + bob: passwd + +neo4j: + host: neo4jhost + port: 7474 + user: neo4j + password: "12345" + + +#Application-specific settings of ES +elasticSearch: + # Mapping of index prefix to time-based frame. For example, if below is configured: + # + # - indexPrefix: auditingevents + # creationPeriod: minute + # + # then ES object of type which is mapped to "auditingevents-*" template, and created on 2015-12-23 13:24:54, will enter "auditingevents-2015-12-23-13-24" index. + # Another object created on 2015-12-23 13:25:54, will enter "auditingevents-2015-12-23-13-25" index. + # If creationPeriod: month, both of the above will enter "auditingevents-2015-12" index. + # + # PLEASE NOTE: the timestamps are created in UTC/GMT timezone! This is needed so that timestamps will be correctly presented in Kibana. + # + # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour). + # + # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month. + + indicesTimeFrequency: + - indexPrefix: auditingevents + creationPeriod: month + - indexPrefix: monitoring_events + creationPeriod: month + +artifactTypes: + - CHEF + - PUPPET + - SHELL + - YANG + - YANG_XML + - HEAT + - BPEL + - DG_XML + - MURANO_PKG + - WORKFLOW + - NETWORK_CALL_FLOW + - TOSCA_TEMPLATE + - TOSCA_CSAR + - AAI_SERVICE_MODEL + - AAI_VF_MODEL + - AAI_VF_MODULE_MODEL + - AAI_VF_INSTANCE_MODEL + - OTHER + +licenseTypes: + - User + - Installation + - CPU + +#Deployment artifacts placeHolder +resourceTypes: &allResourceTypes + - VFC + - CP + - VL + - VF + +# validForResourceTypes usage +# validForResourceTypes: +# - VF +# - VL +deploymentResourceArtifacts: +# heat: +# displayName: "Base HEAT Template" +# type: HEAT +# validForResourceTypes: *allResourceTypes +# heatVol: +# displayName: "Volume HEAT Template" +# type: HEAT_VOL +# validForResourceTypes: *allResourceTypes +# heatNet: +# displayName: "Network HEAT Template" +# type: HEAT_NET +# validForResourceTypes: *allResourceTypes + +deploymentResourceInstanceArtifacts: + heatEnv: + displayName: "HEAT ENV" + type: HEAT_ENV + description: "Auto-generated HEAT Environment deployment artifact" + fileExtension: "env" + +#tosca artifacts placeholders +toscaArtifacts: + assetToscaTemplate: + artifactName: -template.yml + displayName: Tosca Template + type: TOSCA_TEMPLATE + description: TOSCA representation of the asset + assetToscaCsar: + artifactName: -csar.csar + displayName: Tosca Model + type: TOSCA_CSAR + description: TOSCA definition package of the asset + +#Informational artifacts placeHolder +excludeResourceCategory: + - Generic +informationalResourceArtifacts: + features: + displayName: Features + type: OTHER + capacity: + displayName: Capacity + type: OTHER + vendorTestResult: + displayName: Vendor Test Result + type: OTHER + testScripts: + displayName: Test Scripts + type: OTHER + cloudQuestionnaire: + displayName: Cloud Questionnaire (completed) + type: OTHER + HEATTemplateFromVendor: + displayName: HEAT Template from Vendor + type: HEAT + resourceSecurityTemplate: + displayName: Resource Security Template + type: OTHER + +excludeServiceCategory: + +informationalServiceArtifacts: + serviceArtifactPlan: + displayName: Service Artifact Plan + type: OTHER + summaryOfImpactsToECOMPElements: + displayName: Summary of impacts to ECOMP elements,OSSs, BSSs + type: OTHER + controlLoopFunctions: + displayName: Control Loop Functions + type: OTHER + dimensioningInfo: + displayName: Dimensioning Info + type: OTHER + affinityRules: + displayName: Affinity Rules + type: OTHER + operationalPolicies: + displayName: Operational Policies + type: OTHER + serviceSpecificPolicies: + displayName: Service-specific Policies + type: OTHER + engineeringRules: + displayName: Engineering Rules (ERD) + type: OTHER + distributionInstructions: + displayName: Distribution Instructions + type: OTHER + certificationTestResults: + displayName: TD Certification Test Results + type: OTHER + deploymentVotingRecord: + displayName: Deployment Voting Record + type: OTHER + serviceQuestionnaire: + displayName: Service Questionnaire + type: OTHER + serviceSecurityTemplate: + displayName: Service Security Template + type: OTHER + +serviceApiArtifacts: + configuration: + displayName: Configuration + type: OTHER + instantiation: + displayName: Instantiation + type: OTHER + monitoring: + displayName: Monitoring + type: OTHER + reporting: + displayName: Reporting + type: OTHER + logging: + displayName: Logging + type: OTHER + testing: + displayName: Testing + type: OTHER + + +additionalInformationMaxNumberOfKeys: 50 + +systemMonitoring: + enabled: false + isProxy: false + probeIntervalInSeconds: 15 + +defaultHeatArtifactTimeoutMinutes: 60 + +serviceDeploymentArtifacts: + YANG_XML: + acceptedTypes: + - xml + VNF_CATALOG: + acceptedTypes: + - xml + MODEL_INVENTORY_PROFILE: + acceptedTypes: + - xml + MODEL_QUERY_SPEC: + acceptedTypes: + - xml + AAI_SERVICE_MODEL: + acceptedTypes: + - xml + AAI_VF_MODULE_MODEL: + acceptedTypes: + - xml + AAI_VF_INSTANCE_MODEL: + acceptedTypes: + - xml + OTHER: + acceptedTypes: + +resourceDeploymentArtifacts: + HEAT: + acceptedTypes: + - yaml + - yml + validForResourceTypes: *allResourceTypes + HEAT_VOL: + acceptedTypes: + - yaml + - yml + validForResourceTypes: *allResourceTypes + HEAT_NESTED: + acceptedTypes: + - yaml + - yml + validForResourceTypes: *allResourceTypes + HEAT_ARTIFACT: + acceptedTypes: + validForResourceTypes: *allResourceTypes + HEAT_NET: + acceptedTypes: + - yaml + - yml + validForResourceTypes: *allResourceTypes + YANG_XML: + acceptedTypes: + - xml + validForResourceTypes: *allResourceTypes + VNF_CATALOG: + acceptedTypes: + - xml + validForResourceTypes: *allResourceTypes + VF_LICENSE: + acceptedTypes: + - xml + validForResourceTypes: *allResourceTypes + VENDOR_LICENSE: + acceptedTypes: + - xml + validForResourceTypes: *allResourceTypes + MODEL_INVENTORY_PROFILE: + acceptedTypes: + - xml + validForResourceTypes: *allResourceTypes + MODEL_QUERY_SPEC: + acceptedTypes: + - xml + validForResourceTypes: *allResourceTypes + APPC_CONFIG: + acceptedTypes: + validForResourceTypes: + - VF + AAI_VF_MODEL: + acceptedTypes: + - xml + validForResourceTypes: + - VF + AAI_VF_MODULE_MODEL: + acceptedTypes: + - xml + validForResourceTypes: + - VF + OTHER: + acceptedTypes: + validForResourceTypes: *allResourceTypes + +resourceInstanceDeploymentArtifacts: + HEAT_ENV: + acceptedTypes: + - env + VF_MODULES_METADATA: + acceptedTypes: + - json + +resourceInformationalDeployedArtifacts: + + +requirementsToFulfillBeforeCert: + CP: + - tosca.capabilities.network.Bindable + +capabilitiesToConsumeBeforeCert: + +unLoggedUrls: + - /sdc2/rest/healthCheck + +cleanComponentsConfiguration: + cleanIntervalInMinutes: 1440 + componentsToClean: + - Resource + - Service + +artifactsIndex: resources + +cassandraConfig: + cassandraHosts: ['localhost'] + localDataCenter: + reconnectTimeout : 30000 + authenticate: false + username: koko + password: bobo + ssl: false + truststorePath : /path/path + truststorePassword : 123123 + keySpaces: + - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + +switchoverDetector: + gBeFqdn: + gFeFqdn: + beVip: 1.2.3.4 + feVip: 1.2.3.4 + beResolveAttempts: 3 + feResolveAttempts: 3 + enabled: false + interval: 60 + changePriorityUser: ecompasdc + changePriorityPassword: ecompasdc123 + publishNetworkUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root" + publishNetworkBody: '{"note":"publish network"}' + groups: + beSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip?user=root", + changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'} + feSet: { changePriorityUrl: "http://cora.web/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip?user=root", + changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip"}'} + + +heatEnvArtifactHeader: + "" +heatEnvArtifactFooter: + "" + +onboarding: + protocol: http + host: localhost + port: 8080 + downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages" + +applicationL1Cache: + datatypes: + enabled: true + firstRunDelay: 10 + pollIntervalInSec: 60 + +applicationL2Cache: + enabled: false + catalogL1Cache: + enabled: true + resourcesSizeInCache: 300 + servicesSizeInCache: 200 + productsSizeInCache: 100 + queue: + syncIntervalInSecondes: 60 + waitOnShutDownInMinutes: 30 + numberOfCacheWorkers: 4 + diff --git a/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml new file mode 100644 index 0000000000..a64ea7f364 --- /dev/null +++ b/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml @@ -0,0 +1,43 @@ +uebServers: + - uebsb91kcdc.it.att.com:3904 + - uebsb92kcdc.it.att.com:3904 +# - uebsb93kcdc.it.att.com:3904 + +uebPublicKey: 8F3MDAtMSBwwpSMy + +uebSecretKey: gzFmsTxSCtO5RQfAccM6PqqX + +distributionNotifTopicName: ASDC-DISTR-NOTIF-TOPIC +distributionStatusTopicName: ASDC-DISTR-STATUS-TOPIC + +initRetryIntervalSec: 5 +initMaxIntervalSec: 60 + +distribNotifServiceArtifactTypes: + info: + - MURANO-PKG + +distribNotifResourceArtifactTypes: + lifecycle: + - HEAT + - DG-XML + +environments: + - PROD + +distributionStatusTopic: + pollingIntervalSec: 60 + fetchTimeSec: 15 + consumerGroup: asdc + consumerId: asdc-id + +distributionNotificationTopic: + minThreadPoolSize: 0 + maxThreadPoolSize: 10 + maxWaitingAfterSendingSeconds: 5 + +createTopic: + partitionCount: 1 + replicationCount: 1 + +startDistributionEngine: true \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/catalog-be/ecomp-error-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/ecomp-error-configuration.yaml new file mode 100644 index 0000000000..9d7cd74a2b --- /dev/null +++ b/catalog-be/src/test/resources/config/catalog-be/ecomp-error-configuration.yaml @@ -0,0 +1,383 @@ +########################################### +# Note the conventions of the field values: +# type can be one of: CONFIG_ERROR, SYSTEM_ERROR, DATA_ERROR, CONNECTION_PROBLEM, AUTHENTICATION_PROBLEM +# severity can be one of: WARN, ERROR, FATAL +# alarmSeverity can be one of: CRITICAL,MAJOR,MINOR,INFORMATIONAL,NONE +# code is a unique integer in range of 3003-9999 (3000-3002 are occupied for internal usage) +# The above enumeration values are out-of-the-box and can be changed in code. +# In case of config and code mismatch, the appropriate error will be printed to log +# +## Range of BE codes - 3010-7999 + +errors: + + BeRestApiGeneralError: { + type: SYSTEM_ERROR, + code: ASDC_4000, + severity: ERROR, + description: "Unexpected error during BE REST API execution", + alarmSeverity: CRITICAL + } + + BeHealthCheckError: { + type: SYSTEM_ERROR, + code: ASDC_3010, + severity: ERROR, + description: "Error during BE Health Check", + alarmSeverity: CRITICAL + } + + BeInitializationError: { + type: SYSTEM_ERROR, + code: ASDC_4019, + severity: ERROR, + description: "Catalog-BE was not initialized properly", + alarmSeverity: CRITICAL + } + + BeResourceMissingError: { + type: SYSTEM_ERROR, + code: ASDC_3011, + severity: ERROR, + description: "Mandatory resource %s cannot be found in repository", + alarmSeverity: MAJOR + } + + BeServiceMissingError: { + type: SYSTEM_ERROR, + code: ASDC_3012, + severity: ERROR, + description: "Mandatory service %s cannot be found in repository", + alarmSeverity: MAJOR + } + + BeFailedAddingResourceInstanceError: { + type: SYSTEM_ERROR, + code: ASDC_3013, + severity: ERROR, + description: "Failed to add resource instance of resource %s to service %s", + alarmSeverity: MAJOR + } + + BeIncorrectServiceError: { + type: SYSTEM_ERROR, + code: ASDC_3014, + severity: ERROR, + description: "Service %s is not valid", + alarmSeverity: MAJOR + } + + BeRepositoryDeleteError: { + type: SYSTEM_ERROR, + code: ASDC_3015, + severity: ERROR, + description: "Failed to delete object %s from repository", + alarmSeverity: CRITICAL + } + + BeRepositoryQueryError: { + type: SYSTEM_ERROR, + code: ASDC_3016, + severity: ERROR, + description: "Failed to fetch from repository %s", + alarmSeverity: MAJOR + } + + BeInvalidConfigurationError: { + type: CONFIG_ERROR, + code: ASDC_3017, + severity: FATAL, + description: "Configuration parameter %s is invalid. Value configured is %s", + alarmSeverity: MAJOR + } + + BeUebConnectionError: { + type: CONNECTION_PROBLEM, + code: ASDC_4001, + severity: ERROR, + description: "Connection problem towards U-EB server. Reason: %s", + alarmSeverity: MAJOR + } + + BeUebSystemError: { + type: SYSTEM_ERROR, + code: ASDC_3019, + severity: ERROR, + description: "Error occured during access to U-EB Server. Operation: %s", + alarmSeverity: MAJOR + } + + BeUebObjectNotFoundError: { + type: DATA_ERROR, + code: ASDC_4005, + severity: ERROR, + description: "Error occured during access to U-EB Server. Data not found: %s", + alarmSeverity: MAJOR + } + + BeDistributionEngineSystemError: { + type: SYSTEM_ERROR, + code: ASDC_3021, + severity: ERROR, + description: "Error occured in Distribution Engine. Failed operation: %s", + alarmSeverity: MAJOR + } + + BeUebAuthenticationError: { + type: AUTHENTICATION_PROBLEM, + code: ASDC_4003, + severity: ERROR, + description: "Authentication problem towards U-EB server. Reason: %s", + alarmSeverity: MAJOR + } + + BeUebUnkownHostError: { + type: CONNECTION_PROBLEM, + code: ASDC_4002, + severity: ERROR, + description: "Connection problem towards U-EB server. Cannot reach host %s", + alarmSeverity: MAJOR + } + + BeDistributionEngineInvalidArtifactType: { + type: DATA_ERROR, + code: ASDC_4006, + severity: WARN, + description: "The artifact type %s does not appear in the list of valid artifacts %s", + alarmSeverity: MAJOR + } + BeInvalidTypeError: { + type: DATA_ERROR, + code: ASDC_4008, + severity: WARN, + description: "The type %s of %s is invalid", + alarmSeverity: MAJOR + } + BeInvalidValueError: { + type: DATA_ERROR, + code: ASDC_3028, + severity: WARN, + description: "The value %s of %s from type %s is invalid", + alarmSeverity: MAJOR + } + + BeFailedDeletingResourceInstanceError: { + type: SYSTEM_ERROR, + code: ASDC_3029, + severity: ERROR, + description: "Failed to delete resource instance %s from service %s", + alarmSeverity: MAJOR + } + + BeMissingConfigurationError: { + type: CONFIG_ERROR, + code: ASDC_3030, + severity: FATAL, + description: "Configuration parameter %s is missing", + alarmSeverity: MAJOR + } + + BeConfigurationInvalidListSizeError: { + type: CONFIG_ERROR, + code: ASDC_3031, + severity: FATAL, + description: "Configuration parameter %s is invalid. At least %s values shall be configured", + alarmSeverity: MAJOR + } + + ErrorConfigFileFormat: { + type: CONFIG_ERROR, + code: ASDC_3032, + severity: ERROR, + description: "Error element not found in YAML name: %s", + alarmSeverity: MAJOR + } + + BeMissingArtifactInformationError: { + type: DATA_ERROR, + code: ASDC_4010, + severity: ERROR, + description: "Artifact uploaded has missing information. Missing %s", + alarmSeverity: MAJOR + } + + BeArtifactMissingError: { + type: DATA_ERROR, + code: ASDC_4011, + severity: ERROR, + description: "Artifact %s requested is not found", + alarmSeverity: MAJOR + } + + BeArtifactPayloadInvalid: { + type: DATA_ERROR, + code: ASDC_4012, + severity: ERROR, + description: "Payload of artifact uploaded is invalid (invalid MD5 or encryption)", + alarmSeverity: MAJOR + } + + BeUserMissingError: { + type: DATA_ERROR, + code: ASDC_4009, + severity: ERROR, + description: "User %s requested is not found", + alarmSeverity: MAJOR + } + + BeArtifactInformationInvalidError: { + type: DATA_ERROR, + code: ASDC_4013, + severity: ERROR, + description: "Input for artifact metadata is invalid", + alarmSeverity: MAJOR + } + BeFailedAddingCapabilityTypeError: { + type: DATA_ERROR, + code: ASDC_4015, + severity: ERROR, + description: "Failed adding capability type", + alarmSeverity: CRITICAL + } + + BeCapabilityTypeMissingError: { + type: DATA_ERROR, + code: ASDC_4016, + severity: ERROR, + description: "Capability Type %s not found", + alarmSeverity: CRITICAL + } + + BeInterfaceMissingError: { + type: DATA_ERROR, + code: ASDC_4020, + severity: ERROR, + description: "Interface %s required is missing", + alarmSeverity: MAJOR + } + + BeDaoSystemError: { + type: SYSTEM_ERROR, + code: ASDC_4014, + severity: ERROR, + description: "Operation towards database failed", + alarmSeverity: CRITICAL + } + + BeSystemError: { + type: SYSTEM_ERROR, + code: ASDC_4017, + severity: ERROR, + description: "Unexpected error during operation", + alarmSeverity: CRITICAL + } + + BeFailedLockObjectError: { + type: SYSTEM_ERROR, + code: ASDC_4007, + severity: WARN, + description: "Failed to lock object for update", + alarmSeverity: CRITICAL + } + + BeInvalidJsonInput: { + type: SYSTEM_ERROR, + code: ASDC_4018, + severity: ERROR, + description: "Failed to convert json input to object", + alarmSeverity: MAJOR + } + + BeDistributionMissingError: { + type: DATA_ERROR, + code: ASDC_4021, + severity: ERROR, + description: "Distribution %s required is missing", + alarmSeverity: MAJOR + } + + BeHealthCheckRecovery: { + type: RECOVERY, + code: ASDC_4022, + severity: INFO, + description: "BE Health Check Recovery", + alarmSeverity: INFORMATIONAL + } + BeFailedCreateNodeError: { + type: DATA_ERROR, + code: ASDC_6000, + severity: ERROR, + description: "Failed to create node %s on graph. status is %s", + alarmSeverity: MAJOR + } + BeFailedUpdateNodeError: { + type: DATA_ERROR, + code: ASDC_6001, + severity: ERROR, + description: "Failed to update node %s on graph. Status is %s", + alarmSeverity: MAJOR + } + + BeFailedDeleteNodeError: { + type: DATA_ERROR, + code: ASDC_6002, + severity: ERROR, + description: "Failed to delete node %s on graph. Status is %s", + alarmSeverity: MAJOR + } + + BeFailedRetrieveNodeError: { + type: DATA_ERROR, + code: ASDC_6003, + severity: ERROR, + description: "Failed to retrieve node %s from graph. Status is %s", + alarmSeverity: MAJOR + } + + BeExecuteRollbackError: { + type: DATA_ERROR, + code: ASDC_6004, + severity: ERROR, + description: "Going to execute rollback on graph.", + alarmSeverity: MAJOR + } + + BeFailedFindParentError: { + type: DATA_ERROR, + code: ASDC_6005, + severity: ERROR, + description: "Failed to find parent node %s on graph. Status is %s", + alarmSeverity: MAJOR + } + + BeFailedFindAllNodesError: { + type: DATA_ERROR, + code: ASDC_6006, + severity: ERROR, + description: "Failed to fetch all nodes with type %s of parent node %s . Status is %s", + alarmSeverity: MAJOR + } + + BeFailedFindAssociationError: { + type: DATA_ERROR, + code: ASDC_6007, + severity: ERROR, + description: "Cannot find node with type %s associated with node %s . Status is %s", + alarmSeverity: MAJOR + } + + BeFailedFindAssociationError: { + type: DATA_ERROR, + code: ASDC_6008, + severity: ERROR, + description: "Cannot find node with type %s associated with node %s . Status is %s", + alarmSeverity: MAJOR + } + BeComponentCleanerSystemError: { + type: SYSTEM_ERROR, + code: ASDC_6009, + severity: ERROR, + description: "Error occured in Component Cleaner Task. Failed operation: %s", + alarmSeverity: MAJOR + } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml new file mode 100644 index 0000000000..89b44d94d6 --- /dev/null +++ b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml @@ -0,0 +1,1583 @@ +# Errors +errors: + OK: { + code: 200, + message: "OK" + } + CREATED: { + code: 201, + message: "OK" + } + NO_CONTENT: { + code: 204, + message: "No Content" + } +#--------POL4050----------------------------- + NOT_ALLOWED: { + code: 405, + message: "Error: Method not allowed.", + messageId: "POL4050" + } +#--------POL5000----------------------------- + GENERAL_ERROR: { + code: 500, + message: "Error: Internal Server Error. Please try again later.", + messageId: "POL5000" + } +#---------POL5001------------------------------ + MISSING_X_ECOMP_INSTANCE_ID: { + code: 400 , + message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.", + messageId: "POL5001" + } +#---------POL5002------------------------------ + AUTH_REQUIRED: { + code: 401 , + message: "Error: Authentication is required to use the API.", + messageId: "POL5002" + } +#---------POL5003------------------------------ + AUTH_FAILED: { + code: 403 , + message: "Error: Not authorized to use the API.", + messageId: "POL5003" + } +#---------SVC4000----------------------------- + INVALID_CONTENT: { + code: 400, + message: "Error: Invalid content.", + messageId: "SVC4000" + } +#---------SVC4002----------------------------- + MISSING_INFORMATION: { + code: 403, + message: "Error: Missing information.", + messageId: "SVC4002" + } +#---------SVC4003------------------------------ +# %1 - Users's USER_ID + USER_NOT_FOUND: { + code: 404, + message: "Error: User '%1' was not found.", + messageId: "SVC4003" + } +#---------SVC4004----------------------------- +# %1 - Users's email address + INVALID_EMAIL_ADDRESS: { + code: 400, + message: "Error: Invalid email address '%1'.", + messageId: "SVC4004" + } +#---------SVC4005------------------------------ +# %1 - role + INVALID_ROLE: { + code: 400, + message: "Error: Invalid role '%1'.", + messageId: "SVC4005" + } +#---------SVC4006------------------------------ +# %1 - Users's USER_ID + USER_ALREADY_EXIST: { + code: 409, + message: "Error: User with '%1' ID already exists.", + messageId: "SVC4006" + } +#---------SVC4007------------------------------ + DELETE_USER_ADMIN_CONFLICT: { + code: 409, + message: "Error: An administrator can only be deleted by another administrator.", + messageId: "SVC4007" + } +#---------SVC4008----------------------------- +# %1 - Users's userId + INVALID_USER_ID: { + code: 400, + message: "Error: Invalid userId '%1'.", + messageId: "SVC4008" + } +#---------SVC4049------------------------------ +# %1 - service/resource + COMPONENT_MISSING_CONTACT: { + code: 400, + message: "Error: Invalid Content. Missing %1 contact id.", + messageId: "SVC4049" + } +#---------SVC4050----------------------------- +# %1 - Service/Resource/Additional parameter +# %2 - service/resource/label name + COMPONENT_NAME_ALREADY_EXIST: { + code: 409, + message: "Error: %1 with name '%2' already exists.", + messageId: "SVC4050" + } +#---------SVC4051------------------------------ +# %1 - resource/service + COMPONENT_MISSING_CATEGORY: { + code: 400, + message: "Error: Invalid Content. Missing %1 category.", + messageId: "SVC4051" + } + +#---------SVC4052------------------------------ + COMPONENT_MISSING_TAGS: { + code: 400, + message: "Error: Invalid Content. At least one tag has to be specified.", + messageId: "SVC4052" + } + +#---------SVC4053------------------------------ +# %1 - service/resource + COMPONENT_MISSING_DESCRIPTION: { + code: 400, + message: "Error: Invalid Content. Missing %1 description.", + messageId: "SVC4053" + } +#---------SVC4054------------------------------ +# %1 - resource/service + COMPONENT_INVALID_CATEGORY: { + code: 400, + message: "Error: Invalid Content. Invalid %1 category.", + messageId: "SVC4054" + } +#---------SVC4055------------------------------ + MISSING_VENDOR_NAME: { + code: 400, + message: "Error: Invalid Content. Missing vendor name.", + messageId: "SVC4055" + } +#---------SVC4056------------------------------ + MISSING_VENDOR_RELEASE: { + code: 400, + message: "Error: Invalid Content. Missing vendor release.", + messageId: "SVC4056" + } + +#---------SVC4057------------------------------ + MISSING_DERIVED_FROM_TEMPLATE: { + code: 400, + message: "Error: Invalid Content. Missing derived from template specification.", + messageId: "SVC4057" + } + +#---------SVC4058------------------------------ +# %1 - service/resource + COMPONENT_MISSING_ICON: { + code: 400, + message: "Error: Invalid Content. Missing %1 icon.", + messageId: "SVC4058" + } +#---------SVC4059------------------------------ +# %1 - service/resource + COMPONENT_INVALID_ICON: { + code: 400, + message: "Error: Invalid Content. Invalid %1 icon.", + messageId: "SVC4059" + } +#---------SVC4060------------------------------ + PARENT_RESOURCE_NOT_FOUND: { + code: 400, + message: "Error: Invalid Content. Derived from resource template was not found.", + messageId: "SVC4060" + } +#---------SVC4061------------------------------ + MULTIPLE_PARENT_RESOURCE_FOUND: { + code: 400, + message: "Error: Invalid Content. Multiple derived from resource template is not allowed.", + messageId: "SVC4061" + } + +#---------SVC4062------------------------------ +# %1 - service/resource + MISSING_COMPONENT_NAME: { + code: 400, + message: "Error: Invalid Content. Missing %1 name.", + messageId: "SVC4062" + } +#---------SVC4063------------------------------ + #%1  -  resource/service name + RESOURCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' resource was not found.", + messageId: "SVC4063" + } + +#---------SVC4064------------------------------ +# %1 - Service/Resource + COMPONENT_INVALID_DESCRIPTION: { + code: 400, + message: "Error: Invalid Content. %1 description contains non-english characters.", + messageId: "SVC4064" + } +#---------SVC4065------------------------------ +# %1 - Service/Resource +# %2 - max resource/service name length + COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. %1 description exceeds limit of %2 characters.", + messageId: "SVC4065" + } +#---------SVC4066------------------------------ +# %1 - max length + COMPONENT_TAGS_EXCEED_LIMIT: { + code: 400, + message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.", + messageId: "SVC4066" + } +#---------SVC4067------------------------------ +# %1 - max length + VENDOR_NAME_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. Vendor name exceeds limit of %1 characters.", + messageId: "SVC4067" + } +#---------SVC4068------------------------------ +# %1 - max length + VENDOR_RELEASE_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.", + messageId: "SVC4068" + } + +#---------SVC4069------------------------------ +# %1 - Service/Resource/Product + COMPONENT_INVALID_CONTACT_ID: { + code: 400, + message: "Error: Invalid Content. %1 contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9", + messageId: "SVC4069" + } +#---------SVC4070------------------------------ +# %1 - Service/Resource + INVALID_COMPONENT_NAME: { + code: 400, + message: 'Error: Invalid Content. %1 name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.', + messageId: "SVC4070" + } + +#---------SVC4071------------------------------ + INVALID_VENDOR_NAME: { + code: 400, + message: 'Error: Invalid Content. Vendor name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.', + messageId: "SVC4071" + } +#---------SVC4072------------------------------ + INVALID_VENDOR_RELEASE: { + code: 400, + message: 'Error: Invalid Content. Vendor release is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.', + messageId: "SVC4072" + } +#---------SVC4073------------------------------ +# %1 - Service/Resource +# %2 - max resource/service name + COMPONENT_NAME_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. %1 name exceeds limit of %2 characters.", + messageId: "SVC4073" + } +#---------SVC4080------------------------------ +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_IN_CHECKOUT_STATE: { + code: 403, + message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).", + messageId: "SVC4080" + } +#---------SVC4081----------------------------- +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_IN_CERT_IN_PROGRESS_STATE: { + code: 403, + message: "Error: Requested '%1' %2 is locked for certification by %3 %4(%5).", + messageId: "SVC4081" + } + +#-----------SVC4082--------------------------- +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_SENT_FOR_CERTIFICATION: { + code: 403, + message: "Error: Requested '%1' %2 is sent for certification by %3 %4(%5).", + messageId: "SVC4082" + } +#-----------SVC4083--------------------------- + COMPONENT_VERSION_ALREADY_EXIST: { + code: 409, + message: "Error: Version of this %1 was already promoted.", + messageId: "SVC4083" + } +#-----------SVC4084--------------------------- +# %1 - resource/service/product name +# %2 - resource/service/product +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_ALREADY_CHECKED_IN: { + code: 409, + message: "Error: The current version of '%1' %2 was already checked-in by %3 %4(%5).", + messageId: "SVC4084" + } +#-----------SVC4085--------------------------- +# %1 - resource/service/product name +# %2 - resource/service/product +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_CHECKOUT_BY_ANOTHER_USER: { + code: 403, + message: "Error: %1 %2 has already been checked out by %3 %4(%5).", + messageId: "SVC4085" + } +#-----------SVC4086--------------------------- +# %1  - resource/service name +# %2  - resource/service + COMPONENT_IN_USE: { + code: 403, + message: "Error: Requested '%1' %2 is in use by another user.", + messageId: "SVC4086" + } +#-----------SVC4087--------------------------- +# %1 - component name +# %2 - resource/service/product + COMPONENT_HAS_NEWER_VERSION: { + code: 409, + message: "Error: Checking out of the requested version of the '%1' %2 is not allowed as a newer version exists.", + messageId: "SVC4087" + } +#-----------SVC4088--------------------------- +# %1 - resource/service name +# %2 - resource/service +# %3 - First name of last modifier +# %4 - Last name of last modifier +# %5 - USER_ID of last modifier + COMPONENT_ALREADY_CERTIFIED: { + code: 403, + message: "Error: Requested %1 %2 has already been certified by %3 %4(%5).", + messageId: "SVC4088" + } +#-----------SVC4089--------------------------- +# %1 - resource/service name +# %2 - resource/service + COMPONENT_NOT_READY_FOR_CERTIFICATION: { + code: 403, + message: "Error: Requested '%1' %2 is not ready for certification.", + messageId: "SVC4089" + } +#-----------SVC4100--------------------------- +#%1 - property name + PROPERTY_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' property was not found.", + messageId: "SVC4100" + } +#-----------SVC4101--------------------------- +#%1 - property name + PROPERTY_ALREADY_EXIST: { + code: 409, + message: "Error: Property with '%1' name already exists.", + messageId: "SVC4101" + } + +#-----------SVC4102--------------------------- +# %1 - capability type name + CAPABILITY_TYPE_ALREADY_EXIST: { + code: 409, + message: "Error: Capability Type with name '%1' already exists.", + messageId: "SVC4102" + } +#-----------SVC4114--------------------------- + AUTH_FAILED_INVALIDE_HEADER: { + code: 400, + message: "Error: Invalid Authorization header.", + messageId: "SVC4114" + } +#-----------SVC4115--------------------------- +# %1 - capability type name + MISSING_CAPABILITY_TYPE: { + code: 400, + message: "Error: Invalid Content. Missing Capability Type '%1'.", + messageId: "SVC4115" + } + RESOURCE_INSTANCE_BAD_REQUEST: { + code: 400, + message: "Error: Invalid Content.", + messageId: "SVC4116" + } +#-----------SVC4117--------------------------- +# %1 - resource instance name +# %2 - resource instance name +# %3 - requirement name + RESOURCE_INSTANCE_MATCH_NOT_FOUND: { + code: 404, + message: "Error: Match not found between resource instance '%1' and resource instance '%2' for requirement '%3'.", + messageId: "SVC4117" + } +#-----------SVC4118--------------------------- +# %1 - resource instance name +# %2 - resource instance name +# %3 - requirement name + RESOURCE_INSTANCE_ALREADY_EXIST: { + code: 409, + message: "Error: Resource instances '%1' and '%2' are already associated with requirement '%3'.", + messageId: "SVC4118" + } +#-----------SVC4119--------------------------- +# %1 - resource instance name +# %2 - resource instance name +# %3 - requirement name + RESOURCE_INSTANCE_RELATION_NOT_FOUND: { + code: 404, + message: "Error: No relation found between resource instances '%1' and '%2' for requirement '%3'.", + messageId: "SVC4119" + } +#-----------SVC4120--------------------------- +# %1 - User's USER_ID + USER_INACTIVE: { + code: 404, + message: "Error: User %1 was not found.", + messageId: "SVC4120" + } +#-----------SVC4121--------------------------- +# %1 - User's USER_ID + USER_HAS_ACTIVE_ELEMENTS: { + code: 403, + message: "Error: User with %1 ID can not be deleted since it has active elements(resources/services/artifacts).", + messageId: "SVC4121" + } +#-----------SVC4122--------------------------- +# %1 - artifact type + ARTIFACT_TYPE_NOT_SUPPORTED: { + code: 400, + message: "Error: Invalid artifact type '%1'.", + messageId: "SVC4122" + } +#-----------SVC4123--------------------------- + ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Artifact logical name cannot be changed.", + messageId: "SVC4123" + } +#-----------SVC4124--------------------------- + MISSING_ARTIFACT_TYPE: { + code: 400, + message: "Error: Missing artifact type.", + messageId: "SVC4124" + } +#-----------SVC4125--------------------------- +# %1-artifact name + ARTIFACT_EXIST: { + code: 400, + message: "Error: Artifact '%1' already exists.", + messageId: "SVC4125" + } +#---------SVC4126------------------------------ +# %1 - resource/service/product/... +# %2 - field (tag, vendor name...) + INVALID_FIELD_FORMAT: { + code: 400, + message: "Error: Invalid %1 %2 format.", + messageId: "SVC4126" + } +#-----------SVC4127--------------------------- + ARTIFACT_INVALID_MD5: { + code: 400, + message: "Error: Invalid artifact checksum.", + messageId: "SVC4127" + } +#-----------SVC4128--------------------------- + MISSING_ARTIFACT_NAME: { + code: 400, + message: "Error: Invalid content. Missing artifact name.", + messageId: "SVC4128" + } +#-----------SVC4129--------------------------- + MISSING_PROJECT_CODE: { + code: 400, + message: "Error: Invalid Content. Missing PROJECT_CODE number.", + messageId: "SVC4129" + } +#-----------SVC4130--------------------------- + INVALID_PROJECT_CODE: { + code: 400, + message: "Error: Invalid Content. PROJECT_CODE number must be numeric from 5 up to 10 digits.", + messageId: "SVC4130" + } +#-----------SVC4131--------------------------- +# %1-resource/service +# %2-srtifact/artifacts +# %3-semicolomn separated list of artifact + COMPONENT_MISSING_MANDATORY_ARTIFACTS: { + code: 403, + message: "Error: Missing mandatory informational %1 %2: [%3].", + messageId: "SVC4131" + } +#-----------SVC4132--------------------------- +# %1 - lifecycle type name + LIFECYCLE_TYPE_ALREADY_EXIST: { + code: 409, + message: "Error: Lifecycle Type with name '%1' already exists.", + messageId: "SVC4132" + } +#-----------SVC4133--------------------------- +# %1 - service version +# %2 - service name + SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION: { + code: 403, + message: "Error: Version %1 of '%2' service is not available for distribution.", + messageId: "SVC4133" + } +#-----------SVC4134--------------------------- + MISSING_LIFECYCLE_TYPE: { + code: 400, + message: "Error: Invalid Content. Missing interface life-cycle type.", + messageId: "SVC4134" + } +#---------SVC4135------------------------------ + SERVICE_CATEGORY_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Service category cannot be changed once the service is certified.", + messageId: "SVC4135" + } +#---------SVC4136------------------------------ +# %1 - distribution environment name + DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: { + code: 500, + message: "Error: Requested distribution environment '%1' is not available.", + messageId: "SVC4136" + } +#---------SVC4137------------------------------ +# %1 - distribution environment name + DISTRIBUTION_ENVIRONMENT_NOT_FOUND: { + code: 400, + message: "Error: Requested distribution environment '%1' was not found.", + messageId: "SVC4137" + } +#---------SVC4138------------------------------ + DISTRIBUTION_ENVIRONMENT_INVALID: { + code: 400, + message: "Error: Invalid distribution environment.", + messageId: "SVC4138" + } +#---------SVC4139------------------------------ +# %1 - service name + DISTRIBUTION_ARTIFACT_NOT_FOUND: { + code: 409, + message: "Error: Service '%1' cannot be distributed due to missing deployment artifacts.", + messageId: "SVC4139" + } +#---------SVC4200------------------------------ +# %1 - Service/Resource +# %2 - max icon name length + COMPONENT_ICON_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. %1 icon name exceeds limit of %2 characters.", + messageId: "SVC4200" + } +#---------SVC4300------------------------------ + RESTRICTED_ACCESS: { + code: 403, + message: "Error: Restricted access.", + messageId: "SVC4300" + } +#---------SVC4301------------------------------ + RESTRICTED_OPERATION: { + code: 409, + message: "Error: Restricted operation.", + messageId: "SVC4301" + } +#---------SVC4500------------------------------ + MISSING_BODY: { + code: 400 , + message: "Error: Missing request body.", + messageId: "SVC4500" + } +#---------SVC4501------------------------------ + MISSING_PUBLIC_KEY: { + code: 400 , + message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." , + messageId: "SVC4501" + } +#---------SVC4502------------------------------ + DISTRIBUTION_ENV_DOES_NOT_EXIST: { + code: 400 , + message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." , + messageId: "SVC4502" + } +#-----------SVC4503--------------------------- +# %1 - service name + SERVICE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' service was not found.", + messageId: "SVC4503" + } + +#---------SVC4504------------------------------ +# %1 - Service/Resource +# %2 - service/resource version + COMPONENT_VERSION_NOT_FOUND: { + code: 404, + message: "Error: %1 version %2 was not found.", + messageId: "SVC4504" + } +#-----------SVC4505--------------------------- + #%1-artifact name + + ARTIFACT_NOT_FOUND: { + code: 404, + message: "Error: Artifact '%1' was not found.", + messageId: "SVC4505" + } +#---------SVC4506------------------------------ + MISSING_ENV_NAME: { + code: 400 , + message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.", + messageId: "SVC4506" + } +#---------SVC4507------------------------------ + COMPONENT_INVALID_TAGS_NO_COMP_NAME: { + code: 400, + message: "Error: Invalid Content. One of the tags should be the component name.", + messageId: "SVC4507" + } + +#---------SVC4508------------------------------ + SERVICE_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Service name cannot be changed once the service is certified.", + messageId: "SVC4508" + } + +#---------SVC4509------------------------------ + SERVICE_ICON_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Icon cannot be changed once the service is certified.", + messageId: "SVC4509" + } +#---------SVC4510------------------------------ +# %1 - icon name max length + SERVICE_ICON_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. Icon name exceeds limit of %1 characters.", + messageId: "SVC4510" + } +#---------SVC4511------------------------------ + DISTRIBUTION_REQUESTED_NOT_FOUND: { + code: 404, + message: "Error: Requested distribution was not found.", + messageId: "SVC4511" + } +#---------SVC4512------------------------------ +# %1 - Distribution ID + DISTRIBUTION_REQUESTED_FAILED: { + code: 403, + message: "Error: Requested distribution '%1' failed.", + messageId: "SVC4512" + } +#---------SVC4513------------------------------ + RESOURCE_CATEGORY_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Resource category cannot be changed once the resource is certified.", + messageId: "SVC4513" + } +#---------SVC4514------------------------------ + RESOURCE_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Resource name cannot be changed once the resource is certified.", + messageId: "SVC4514" + } +#---------SVC4515------------------------------ + RESOURCE_ICON_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Icon cannot be changed once the resource is certified.", + messageId: "SVC4515" + } +#---------SVC4516------------------------------ + RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Vendor name cannot be changed once the resource is certified.", + messageId: "SVC4516" + } +#---------SVC4517------------------------------ + RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: Derived from resource template cannot be changed once the resource is certified.", + messageId: "SVC4517" + } +#---------SVC4518------------------------------ +# %1 - max length + COMPONENT_SINGLE_TAG_EXCEED_LIMIT: { + code: 400, + message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.", + messageId: "SVC4518" + } +#---------SVC4519------------------------------ + INVALID_DEFAULT_VALUE: { + code: 400, + message: "Error: mismatch in data-type occurred for property %1. data type is %2 and default value found is %3.", + messageId: "SVC4519" + } +#---------SVC4520------------------------------ +# %1 - service or resource + ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: { + code: 409, + message: "Error: Maximal number of additional %1 parameters was reached.", + messageId: "SVC4520" + } +#---------SVC4521------------------------------ + ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: { + code: 400, + message: "Error: Invalid Content. The Additional information label and value cannot be empty.", + messageId: "SVC4521" + } +#---------SVC4522------------------------------ +# %1 - label/value +# %2 - Maximal length of %1 + ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. Additional information %1 exceeds limit of %2 characters.", + messageId: "SVC4522" + } +#---------SVC4523------------------------------ + ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS: { + code: 400, + message: 'Error: Invalid Content. Additional information label is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.', + messageId: "SVC4523" + } +#---------SVC4524------------------------------ + ADDITIONAL_INFORMATION_NOT_FOUND: { + code: 409, + message: "Error: Requested additional information was not found.", + messageId: "SVC4524" + } +#---------SVC4525------------------------------ + ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: { + code: 400, + message: 'Error: Invalid Content. Additional information contains non-english characters.', + messageId: "SVC4525" + } +#---------SVC4526------------------------------ + RESOURCE_INSTANCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' resource instance was not found.", + messageId: "SVC4526" + } +#---------SVC4527------------------------------ + ASDC_VERSION_NOT_FOUND: { + code: 500, + message: 'Error: ASDC version cannot be displayed.', + messageId: "SVC4527" + } +#---------SVC4528------------------------------ +# %1-artifact url/artifact label/artifact description/VNF Service Indicator + MISSING_DATA: { + code: 400, + message: "Error: Invalid content. Missing %1.", + messageId: "SVC4528" + } +#---------SVC4529------------------------------ +# %1-artifact url/artifact label/artifact description/artifact name +# %2 - Maximal length of %1 + EXCEEDS_LIMIT: { + code: 400, + message: "Error: Invalid Content. %1 exceeds limit of %2 characters.", + messageId: "SVC4529" + } +#---------SVC4530------------------------------ + ARTIFACT_INVALID_TIMEOUT: { + code: 400, + message: "Error: Invalid Content. Artifact Timeout should be set to valid positive non-zero number of minutes.", + messageId: "SVC4530" + } +#---------SVC4531------------------------------ + SERVICE_IS_VNF_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: VNF Indicator cannot be updated for certified service.", + messageId: "SVC4531" + } + #---------SVC4532------------------------------ + RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE: { + code: 404, + message: "Error: Requested '%1' resource instance was not found on the service '%2.", + messageId: "SVC4532" + } + #---------SVC4533------------------------------ + # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML" + WRONG_ARTIFACT_FILE_EXTENSION: { + code: 400, + message: "Error: Invalid file extension for %1 artifact type.", + messageId: "SVC4533" + } + +#---------SVC4534------------------------------ +# %1 - "HEAT"/"HEAT_ENV" + INVALID_YAML: { + code: 400, + message: "Error: Uploaded YAML file for %1 artifact is invalid.", + messageId: "SVC4534" + } + +#---------SVC4535------------------------------ +# %1 - "HEAT" + INVALID_DEPLOYMENT_ARTIFACT_HEAT: { + code: 400, + message: "Error: Invalid %1 artifact.", + messageId: "SVC4535" + } +#---------SVC4536------------------------------ +# %1 - "Resource"/"Service" +# %2 - resource/service name +# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG" +# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG + DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: { + code: 400, + message: "Error: %1 '%2' already has a deployment artifact of %3 type .Please delete or update an existing %4 artifact.", + messageId: "SVC4536" + } + +#---------SVC4537------------------------------ + MISSING_HEAT: { + code: 400, + message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.", + messageId: "SVC4537" + } +#---------SVC4538------------------------------ + MISMATCH_HEAT_VS_HEAT_ENV: { + code: 400, + message: "Error: Invalid artifact content. Parameter's set in HEAT_ENV '%1' artifact doesn't match the parameters in HEAT '%2' artifact.", + messageId: "SVC4538" + } +#---------SVC4539------------------------------ + INVALID_RESOURCE_PAYLOAD: { + code: 400, + message: "Error: Invalid resource payload.", + messageId: "SVC4539" + } +#---------SVC4540------------------------------ + INVALID_TOSCA_FILE_EXTENSION: { + code: 400, + message: "Error: Invalid file extension for TOSCA template.", + messageId: "SVC4540" + } +#---------SVC4541------------------------------ + INVALID_YAML_FILE: { + code: 400, + message: "Error: Invalid YAML file.", + messageId: "SVC4541" + } +#---------SVC4542------------------------------ + INVALID_TOSCA_TEMPLATE: { + code: 400, + message: "Error: Invalid TOSCA template.", + messageId: "SVC4542" + } +#---------SVC4543------------------------------ + NOT_RESOURCE_TOSCA_TEMPLATE: { + code: 400, + message: "Error: Imported Service TOSCA template.", + messageId: "SVC4543" + } +#---------SVC4544------------------------------ + NOT_SINGLE_RESOURCE: { + code: 400, + message: "Error: Imported TOSCA template should contain one resource definition.", + messageId: "SVC4544" + } +#---------SVC4545------------------------------ + INVALID_RESOURCE_NAMESPACE: { + code: 400, + message: "Error: Invalid resource namespace.", + messageId: "SVC4545" + } +#---------SVC4546------------------------------ + RESOURCE_ALREADY_EXISTS: { + code: 400, + message: "Error: Imported resource already exists in ASDC Catalog.", + messageId: "SVC4546" + } +#---------SVC4549------------------------------ + INVALID_RESOURCE_CHECKSUM: { + code: 400, + message: "Error: Invalid resource checksum.", + messageId: "SVC4549" + } +#---------SVC4550------------------------------ + #%1  -  Consumer salt + INVALID_LENGTH: { + code: 400, + message: "Error: Invalid %1 length.", + messageId: "SVC4550" + } + #---------SVC4551------------------------------ + #%1  -  ECOMP User name + ECOMP_USER_NOT_FOUND: { + code: 404, + message: "Error: ECOMP User '%1' was not found.", + messageId: "SVC4551" + } +#---------SVC4552------------------------------ + CONSUMER_ALREADY_EXISTS: { + code: 409, + message: "Error: ECOMP User already exists.", + messageId: "SVC4552" + } +#---------SVC4553----------------------------- + #%1  -  Consumer name / Consumer password/ Consumer salt + INVALID_CONTENT_PARAM: { + code: 400, + message: "Error: %1 is invalid.", + messageId: "SVC4553" + } + #---------SVC4554------------------------------ +# %1 - "Resource"/"Service" + COMPONENT_ARTIFACT_NOT_FOUND: { + code: 404, + message: "Error: Requested artifact doesn't belong to specified %1.", + messageId: "SVC4554" + } +#---------SVC4554------------------------------ +# %1 - "Service name" + SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND: { + code: 403, + message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.", + messageId: "SVC4554" + } +#---------SVC4555------------------------------ +#%1 - "Resource"/"Service"/"Product" +#%2 - "category" + COMPONENT_ELEMENT_INVALID_NAME_LENGTH: { + code: 400, + message: "Error: Invalid %1 %2 name length.", + messageId: "SVC4555" + } +#---------SVC4556------------------------------ +#%1 - "Resource"/"Service"/"Product" +#%2 - "category" + COMPONENT_ELEMENT_INVALID_NAME_FORMAT: { + code: 400, + message: "Error: Invalid %1 %2 name format.", + messageId: "SVC4556" + } +#---------SVC4557------------------------------ +#%1 - "Resource"/"Service"/"Product" +#%2 - "category name" + COMPONENT_CATEGORY_ALREADY_EXISTS: { + code: 409, + message: "Error: %1 category name '%2' already exists.", + messageId: "SVC4557" + } +#---------SVC4558------------------------------ +# %1 - "service"/"VF" +# %2 - "Resource name" + VALIDATED_RESOURCE_NOT_FOUND: { + code: 403, + message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource.", + messageId: "SVC4558" + } +#---------SVC4559------------------------------ +# %1 - "service"/"VF" +# %2 - "Resource name" + FOUND_ALREADY_VALIDATED_RESOURCE: { + code: 403, + message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use already available validated resource version.", + messageId: "SVC4559" + } +#---------SVC4560------------------------------ +# %1 - "service"/"VF" +# %2 - "Resource name" + FOUND_LIST_VALIDATED_RESOURCES: { + code: 403, + message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use one of available validated resource versions.", + messageId: "SVC4560" + } +#---------SVC4561------------------------------ +# %1 - "resource"/"product" +# %2 - "category" +# %2 - "category name" + COMPONENT_CATEGORY_NOT_FOUND: { + code: 404, + message: "Error: Requested %1 %2 '%3' was not found.", + messageId: "SVC4561" + } +#---------SVC4562------------------------------ +# %1 - "Resource"/"Product" +# %2 - "sub-category name" +# %2 - "category name" + COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY: { + code: 409, + message: "Error: %1 sub-category '%2' already exists under '%3' category.", + messageId: "SVC4562" + } +#---------SVC4563------------------------------ +# %1 - "Product" +# %2 - "grouping name" +# %2 - "sub-category name" + COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY: { + code: 409, + message: "Error: %1 grouping '%2' already exists under '%3' sub-category.", + messageId: "SVC4563" + } +#---------SVC4564------------------------------ +# %1 - product name + PRODUCT_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' product was not found.", + messageId: "SVC4564" + } +#---------SVC4565------------------------------ +# %1 - "HEAT" +# %2 - parameter type ("string" , "boolean" , "number") +# %3 - parameter name + INVALID_HEAT_PARAMETER_VALUE: { + code: 400, + message: "Error: Invalid %1 artifact. Invalid %2 value set for '%3' parameter.", + messageId: "SVC4565" + } +#---------SVC4566------------------------------ +# %1 - "HEAT" +# %2 - parameter type ("string" , "boolean" , "number") + INVALID_HEAT_PARAMETER_TYPE: { + code: 400, + message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.", + messageId: "SVC4566" + } +#---------SVC4567------------------------------ +# %1 - "YANG_XML" + INVALID_XML: { + code: 400, + message: "Error: Uploaded XML file for %1 artifact is invalid.", + messageId: "SVC4567" + } +#---------SVC4567------------------------------ +# %1 - "User Name and userId" +# %2 -"checked-out"/"in-certification" + CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: { + code: 409, + message: "Error: User cannot be deleted. User '%1' has %2 projects.", + messageId: "SVC4567" + } +#---------SVC4568------------------------------ +# %1 - "User Name and userId" +# %2 -"checked-out"/"in-certification" + CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: { + code: 409, + message: "Error: Role cannot be changed. User '%1' has %2 projects.", + messageId: "SVC4568" + } +#---------SVC4570------------------------------ + UPDATE_USER_ADMIN_CONFLICT: { + code: 409, + message: "Error: An administrator is not allowed to change his/her role.", + messageId: "SVC4570" + } +#---------SVC4571------------------------------ + SERVICE_CANNOT_CONTAIN_SUBCATEGORY: { + code: 400, + message: "Error: Sub category cannot be defined for service", + messageId: "SVC4571" + } +#---------SVC4572------------------------------ +# %1 - "Resource"/"Service" + COMPONENT_TOO_MUCH_CATEGORIES: { + code: 400, + message: "Error: %1 must have only 1 category", + messageId: "SVC4572" + } +#---------SVC4574------------------------------ + RESOURCE_TOO_MUCH_SUBCATEGORIES: { + code: 400, + message: "Error: Resource must have only 1 sub category", + messageId: "SVC4574" + } +#---------SVC4575------------------------------ + COMPONENT_MISSING_SUBCATEGORY: { + code: 400, + message: "Error: Missing sub category", + messageId: "SVC4575" + } + #---------SVC4576------------------------------ +# %1 - "component type" + UNSUPPORTED_ERROR: { + code: 400, + message: "Error : Requested component type %1 is unsupported.", + messageId: "SVC4576" + } + #---------SVC4577------------------------------ +# %1 - "resource type" + RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: { + code: 409, + message: "Error : Resource of type %1 cannot contain resource instances.", + messageId: "SVC4577" + } +#---------SVC4578------------------------------ +# %1 - "Resource"/"Service" +# %2 - resource/service name +# %3 - "artifact name" + DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS: { + code: 400, + message: "Error: %1 '%2' already has a deployment artifact named '%3'.", + messageId: "SVC4578" + } +#---------SVC4579------------------------------ +# %1 - "Category"/"Sub-Category"/"Group" +# %2 - category/sub-category/grouping name. + INVALID_GROUP_ASSOCIATION: { + code: 400, + message: "Error: Invalid group association. %1 '%2' was not found.", + messageId: "SVC4579" + } +#---------SVC4580------------------------------ + EMPTY_PRODUCT_CONTACTS_LIST: { + code: 400, + message: "Error: Invalid content. At least one Product Contact has to be specified.", + messageId: "SVC4580" + } +#---------SVC4581------------------------------ +# %1 - userId + INVALID_PRODUCT_CONTACT: { + code: 400, + message: "Error: Invalid content. User '%1' cannot be set as Product Contact.", + messageId: "SVC4581" + } +#---------SVC4582------------------------------ +# %1 - Product +# %2 - "abbreviated"/"full" + MISSING_ONE_OF_COMPONENT_NAMES: { + code: 400, + message: "Error: Invalid content. Missing %1 %2 name.", + messageId: "SVC4582" + } +#---------SVC4583------------------------------ +# %1 - "Icon" +# %2 - "resource"/"service"/"product" + COMPONENT_PARAMETER_CANNOT_BE_CHANGED: { + code: 400, + message: "Error: %1 cannot be changed once the %2 is certified.", + messageId: "SVC4583" + } +#---------SVC4584------------------------------ +# %1 - service/VF name +# %2 - "service" /"VF" +# %3 - resource instance origin type +# %4 - resource instance name +# %5 - requirement/capability +# %6 - requirement/capability name +# %7 - "fulfilled" (for req)/"consumed (for cap)" + REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION: { + code: 403, + message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.", + messageId: "SVC4584" + } +#---------SVC4585------------------------------ + INVALID_OCCURRENCES: { + code: 400, + message: "Error: Invalid occurrences format.", + messageId: "SVC4585" + } +#---------SVC4586------------------------------ +#---------SVC4586------------------------------ + INVALID_SERVICE_API_URL: { + code: 400, + message: 'Error: Invalid Service API URL. Please check whether your URL has a valid domain extension and does not contain the following characters - #?&@%+;,=$<>~^`\[]{}|"*!', + messageId: "SVC4586" + } +#---------SVC4587------------------------------ +# %1 - Data type name + DATA_TYPE_ALREADY_EXIST: { + code: 409, + message: 'Error: Data type %1 already exists.', + messageId: "SVC4587" + } +#---------SVC4588------------------------------ +# %1 - Data type name + DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: { + code: 400, + message: 'Error: Invalid Data type %1. Data type must have either a valid derived from declaration or at least one valid property', + messageId: "SVC4588" + } +#---------SVC4589------------------------------ +# %1 - Data type name + DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: { + code: 400, + message: "Error: Invalid Data type %1. 'properties' parameter cannot be empty if provided.", + messageId: "SVC4589" + } +#---------SVC4590------------------------------ +# %1 - Property type name +# %2 - Property name + INVALID_PROPERTY_TYPE: { + code: 400, + message: "Error: Invalid Property type %1 in property %2.", + messageId: "SVC4590" + } +#---------SVC4591------------------------------ +# %1 - Property inner type +# %2 - Property name + INVALID_PROPERTY_INNER_TYPE: { + code: 400, + message: "Error: Invalid property inner type %1, in property %2", + messageId: "SVC4591" + } +#---------SVC4592------------------------------ +# %1 - component instance name +# %2 - "resource instance"/"service instance" + COMPONENT_INSTANCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' %2 was not found.", + messageId: "SVC4592" + } +#---------SVC4593------------------------------ +# %1 - component instance name +# %2 - "resource instance"/"service instance" +# %3 - "resource/"service"/"product" +# %4 - container name + COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested '%1' %2 was not found on the %3 '%4'.", + messageId: "SVC4593" + } +#---------SVC4594------------------------------ +#%1 - requirement / capability +#%2 - requirement name + IMPORT_DUPLICATE_REQ_CAP_NAME: { + code: 400, + message: "Error: Imported TOSCA template contains more than one %1 named '%2'.", + messageId: "SVC4594" + } +#---------SVC4595------------------------------ +#%1 - requirement / capability +#%2 - requirement name +#%3 - parent containing the requirement + IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED: { + code: 400, + message: "Error: Imported TOSCA template contains %1 '%2' that is already defined by derived template %3.", + messageId: "SVC4595" + } +#---------SVC4596------------------------------ +# %1 - Data type name + DATA_TYPE_DERIVED_IS_MISSING: { + code: 400, + message: "Error: Invalid Content. The ancestor data type %1 cannot be found in the system.", + messageId: "SVC4596" + } +#---------SVC4597------------------------------ +# %1 - Data type name +# %2 - Property names + DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: { + code: 400, + message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.", + messageId: "SVC4597" + } +#---------SVC4598------------------------------ +# %1 - Data type name + DATA_TYPE_DUPLICATE_PROPERTY: { + code: 400, + message: "Error: Invalid Content. The data type %1 contains duplicate property.", + messageId: "SVC4598" + } +#---------SVC4599------------------------------ +# %1 - Data type name +# %2 - Property names + DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: { + code: 400, + message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.", + messageId: "SVC4599" + } +#---------SVC4600------------------------------ +# %1 - Data type name + DATA_TYPE_CANNOT_HAVE_PROPERTIES: { + code: 400, + message: "Error: Invalid Content. The data type %1 cannot have properties since it is of type scalar", + messageId: "SVC4600" + } +#---------SVC4601------------------------------ + NOT_TOPOLOGY_TOSCA_TEMPLATE: { + code: 400, + message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.", + messageId: "SVC4601" + } +#---------SVC4602-------------------------------- +# %1 - yaml file name +# %2 - node_template label +# %3 - node_template type + INVALID_NODE_TEMPLATE: { + code: 400, + message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL", + messageId: "SVC4602" + } +#---------SVC4603------------------------------ +# %1 - component type +# %2 - component name +# %3 - state + ILLEGAL_COMPONENT_STATE: { + code: 403, + message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.", + messageId: "SVC4603" + } +#---------SVC4604------------------------------ +# %1 - csar file name + CSAR_INVALID: { + code: 400, + message: "Error: TOSCA CSAR '%1' is invalid. 'TOSCA-Metadata/Tosca.meta' file must be provided.", + messageId: "SVC4604" + } +#---------SVC4605------------------------------ +# %1 - csar file name + CSAR_INVALID_FORMAT: { + code: 400, + message: "Error: TOSCA CSAR '%1' is invalid. Invalid 'TOSCA-Metadata/Tosca.meta' file format.", + messageId: "SVC4605" + } +#---------SVC4606------------------------------ +# %1 - property name +# %2 - property type +# %3 - property innerType +# %4 - default value is + INVALID_COMPLEX_DEFAULT_VALUE: { + code: 400, + message: "Error: Invalid default value of property %1. Data type is %2 with inner type %3 and default value found is %4.", + messageId: "SVC4606" + } +#---------SVC4607------------------------------ +# %1 - csar file name + CSAR_NOT_FOUND: { + code: 400, + message: "Error: TOSCA CSAR '%1' is not found.", + messageId: "SVC4607" + } +#---------SVC4608------------------------------ +# %1 - artifact name +# %2 - component type +# %3 - actual component type + MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE: { + code: 400, + message: "Error: Artifact %1 is only compatible with component of type %2, but component type is %3.", + messageId: "SVC4608" + } + +#---------SVC4609------------------------------ +# %1 - "INVALID_JSON" + INVALID_JSON: { + code: 400, + message: "Error: Uploaded JSON file for %1 artifact is invalid.", + messageId: "SVC4609" + } +#---------SVC4610------------------------------ +# %1 - csar file name +# %2 - missing file name + YAML_NOT_FOUND_IN_CSAR: { + code: 400, + message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.", + messageId: "SVC4610" + } +#---------SVC4611------------------------------ +# %1 - group name + GROUP_MEMBER_EMPTY: { + code: 400, + message: "Error: Invalid Content. Group %1 member list was provided but does not have values", + messageId: "SVC4611" + } +#---------SVC4612------------------------------ +# %1 - group name + GROUP_TYPE_ALREADY_EXIST: { + code: 409, + message: 'Error: Group type %1 already exists.', + messageId: "SVC4612" + } +#---------SVC4613------------------------------ +# %1 - group name +# %2 - VF name(component name) +# %3 - actual component type [VF] + GROUP_ALREADY_EXIST: { + code: 409, + message: "Error: Group with name '%1' already exists in %2 %3.", + messageId: "SVC4613" + } +#---------SVC4614------------------------------ +# %1 - group type + GROUP_TYPE_IS_INVALID: { + code: 400, + message: "Error: Invalid content. Group type %1 does not exist", + messageId: "SVC4614" + } +#---------SVC4615------------------------------ +# %1 - group name + GROUP_MISSING_GROUP_TYPE: { + code: 400, + message: "Error: Invalid Content. Missing Group Type for group '%1'", + messageId: "SVC4615" + } +#---------SVC4616------------------------------ +# %1 - member name +# %2 - group name +# %3 - VF name +# %4 - component type [VF ] + GROUP_INVALID_COMPONENT_INSTANCE: { + code: 400, + message: "Error: member %1 listed in group %2 is not part of %3 %4.", + messageId: "SVC4616" + } +#---------SVC4617------------------------------ +# %1 - member name +# %2 - group name +# %3 - group type + GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE: { + code: 400, + message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.", + messageId: "SVC4617" + } +#---------SVC4618------------------------------ +# %1 - missing file name +# %2 - csar file name + ARTIFACT_NOT_FOUND_IN_CSAR: { + code: 400, + message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided", + messageId: "SVC4618" + } +#---------SVC4619------------------------------ +# %1 - artifact name +# %2 - artifact type +# %3 - existing artifact type + ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR: { + code: 400, + message: "Error: artifact %1 in type %2 already exists in type %3.", + messageId: "SVC4619" + } +#---------SVC4620------------------------------ + FAILED_RETRIVE_ARTIFACTS_TYPES: { + code: 400, + message: "Error: Failed to retrieve list of suported artifact types.", + messageId: "SVC4620" + } +#---------SVC4621------------------------------ +# %1 - artifact name +# %2 - master + ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: { + code: 400, + message: "Error: artifact %1 already exists in master %2 .", + messageId: "SVC4621" + } +#---------SVC4622------------------------------ +# %1 - artifact name +# %2 - artifact type +# %3 - master name +# %4 - master type + ARTIFACT_NOT_VALID_IN_MASTER: { + code: 400, + message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.", + messageId: "SVC4622" + } +#---------SVC4623------------------------------ +# %1 - artifact name +# %2 - artifact type +# %3 - env name +# %4 - existing env + ARTIFACT_NOT_VALID_ENV: { + code: 400, + message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4", + messageId: "SVC4623" + } +#---------SVC4624------------------------------ +# %1 - groups names +# %2 - VF name +# %3 - component type [VF ] + GROUP_IS_MISSING: { + code: 400, + message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.", + messageId: "SVC4624" + } +#---------SVC4625------------------------------ +# %1 - groups name + GROUP_ARTIFACT_ALREADY_ASSOCIATED: { + code: 400, + message: "Error: Invalid Content. Artifact already associated to group '%1'.", + messageId: "SVC4625" + } +#---------SVC4626------------------------------ +# %1 - groups name + GROUP_ARTIFACT_ALREADY_DISSOCIATED: { + code: 400, + message: "Error: Invalid Content. Artifact already dissociated from group '%1'.", + messageId: "SVC4626" + } +#---------SVC4627------------------------------ +# %1 - property name +# %2 - group name +# %3 - group type name + GROUP_PROPERTY_NOT_FOUND: { + code: 400, + message: "Error: property %1 listed in group %2 is not exist in group type %3.", + messageId: "SVC4627" + } +#---------SVC4628------------------------------ +# %1 - csarUUID +# %2 - VF name + VSP_ALREADY_EXISTS: { + code: 400, + message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.", + messageId: "SVC4628" + } +#---------SVC4629------------------------------ +# %1 - VF name + MISSING_CSAR_UUID: { + code: 400, + message: "Error: The Csar UUID or payload name is missing for VF %1.", + messageId: "SVC4629" + } +#---------SVC4630------------------------------ +# %1 - VF name +# %2 - new csarUUID +# %3 - old csarUUID + RESOURCE_LINKED_TO_DIFFERENT_VSP: { + code: 400, + message: "Error: Resource %1 cannot be updated using CsarUUID %2 since the resource is linked to a different VSP with csarUUID %3.", + messageId: "SVC4630" + } +#---------SVC4631------------------------------ +# %1 - policy name + POLICY_TYPE_ALREADY_EXIST: { + code: 409, + message: "Error: Policy type %1 already exists.", + messageId: "SVC4631" + } +#---------SVC4632------------------------------ +# %1 - target name +# %2 - policy type name + TARGETS_NON_VALID: { + code: 400, + message: "Error: target %1 listed in policy type %2 is not a group or resource.", + messageId: "SVC4632" + } +#---------SVC4633------------------------------ +# %1 - policy name + TARGETS_EMPTY: { + code: 400, + message: "Error: Invalid Content. Policy %1 target list was provided but does not have values", + messageId: "SVC4633" + } +#---------SVC4634------------------------------ + DATA_TYPE_CANNOT_BE_EMPTY: { + code: 500, + message: "Error: Data types are empty. Please import the data types.", + messageId: "SVC4634" + } +#---------SVC4635------------------------------ +# %1 - csar uuid + RESOURCE_FROM_CSAR_NOT_FOUND: { + code: 400, + message: "Error: resource from csar uuid %1 not found", + messageId: "SVC4635" + } +#---------SVC4636------------------------------ +# %1 - Data type name + DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: { + code: 400, + message: 'Error: Data type %1 cannot be upgraded. The new data type does not contain old properties or the type of one of the properties has been changed.', + messageId: "SVC4636" + } \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/catalog-be/neo4j-errors-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/neo4j-errors-configuration.yaml new file mode 100644 index 0000000000..7a0d6dbfd4 --- /dev/null +++ b/catalog-be/src/test/resources/config/catalog-be/neo4j-errors-configuration.yaml @@ -0,0 +1,60 @@ +# Errors +errors: + Neo_ClientError_General_ReadOnly: "This is a read only database, writing or modifying the database is not allowed." + Neo_ClientError_LegacyIndex_NoSuchIndex: "The request (directly or indirectly) referred to a index that does not exist." + Neo_ClientError_Request_Invalid: "The client provided an invalid Request." + Neo_ClientError_Request_InvalidFormat: "The client provided a request that was missing required fields, or had values that are not allowed." + Neo_ClientError_Schema_ConstraintAlreadyExists: "Unable to perform operation because it would clash with a pre-existing constraint." + Neo_ClientError_Schema_ConstraintVerificationFailure: "Unable to create constraint because data that exists in the database violates it." + Neo_ClientError_Schema_ConstraintViolation: "A constraint imposed by the database was violated." + Neo_ClientError_Schema_IllegalTokenName: "A token name, such as a label, relationship type or property key, used is not valid. Tokens cannot be empty strings and cannot be null." + Neo_ClientError_Schema_IndexAlreadyExists: "Unable to perform operation because it would clash with a pre-existing index." + Neo_ClientError_Schema_IndexBelongsToConstraint: "A requested operation can not be performed on the specified index because the index is part of a constraint. If you want to drop the index, for instance, you must drop the constraint." + Neo_ClientError_Schema_IndexLimitReached: "The maximum number of index entries supported has been reached, no more entities can be indexed." + Neo_ClientError_Schema_LabelLimitReached: "The maximum number of labels supported has been reached, no more labels can be created." + Neo_ClientError_Schema_NoSuchConstraint: "The request (directly or indirectly) referred to a constraint that does not exist." + Neo_ClientError_Schema_NoSuchIndex: "The request (directly or indirectly) referred to an index that does not exist." + Neo_ClientError_Security_AuthenticationFailed: "The client provided an incorrect username and/or password." + Neo_ClientError_Security_AuthenticationRateLimit: "The client has provided incorrect authentication details too many times in a row." + Neo_ClientError_Security_AuthorizationFailed: "The client does not have privileges to perform the operation requested." + Neo_ClientError_Statement_ArithmeticError: "Invalid use of arithmetic, such as dividing by zero." + Neo_ClientError_Statement_ConstraintViolation: "A constraint imposed by the statement is violated by the data in the database." + Neo_ClientError_Statement_EntityNotFound: "The statement is directly referring to an entity that does not exist." + Neo_ClientError_Statement_InvalidArguments: "The statement is attempting to perform operations using invalid arguments" + Neo_ClientError_Statement_InvalidSemantics: "The statement is syntactically valid, but expresses something that the database cannot do." + Neo_ClientError_Statement_InvalidSyntax: "The statement contains invalid or unsupported syntax." + Neo_ClientError_Statement_InvalidType: "The statement is attempting to perform operations on values with types that are not supported by the operation." + Neo_ClientError_Statement_NoSuchLabel: "The statement is referring to a label that does not exist." + Neo_ClientError_Statement_NoSuchProperty: "The statement is referring to a property that does not exist." + Neo_ClientError_Statement_ParameterMissing: "The statement is referring to a parameter that was not provided in the Request." + Neo_ClientError_Transaction_ConcurrentRequest: "There were concurrent requests accessing the same transaction, which is not allowed." + Neo_ClientError_Transaction_EventHandlerThrewException: "A transaction event handler threw an exception. The transaction will be rolled back." + Neo_ClientError_Transaction_HookFailed: "Transaction hook failure." + Neo_ClientError_Transaction_InvalidType: "The transaction is of the wrong type to service the Request_ For instance, a transaction that has had schema modifications performed in it cannot be used to subsequently perform data operations, and vice versa." + Neo_ClientError_Transaction_MarkedAsFailed: "Transaction was marked as both successful and failed. Failure takes precedence and so this transaction was rolled back although it may have looked like it was going to be committed" + Neo_ClientError_Transaction_UnknownId: "The request referred to a transaction that does not exist." + Neo_ClientError_Transaction_ValidationFailed: "Transaction changes did not pass validation checks" + Neo_DatabaseError_General_CorruptSchemaRule: "A malformed schema rule was encountered. Please contact your support representative." + Neo_DatabaseError_General_FailedIndex: "The request (directly or indirectly) referred to an index that is in a failed state. The index needs to be dropped and recreated manually." + Neo_DatabaseError_General_UnknownFailure: "An unknown failure occurred." + Neo_DatabaseError_Schema_ConstraintCreationFailure: "Creating a requested constraint failed." + Neo_DatabaseError_Schema_ConstraintDropFailure: "The database failed to drop a requested constraint." + Neo_DatabaseError_Schema_IndexCreationFailure: "Failed to create an index." + Neo_DatabaseError_Schema_IndexDropFailure: "The database failed to drop a requested index." + Neo_DatabaseError_Schema_NoSuchLabel: "The request accessed a label that did not exist." + Neo_DatabaseError_Schema_NoSuchPropertyKey: "The request accessed a property that does not exist." + Neo_DatabaseError_Schema_NoSuchRelationshipType: "The request accessed a relationship type that does not exist." + Neo_DatabaseError_Schema_NoSuchSchemaRule: "The request referred to a schema rule that does not exist." + Neo_DatabaseError_Statement_ExecutionFailure: "The database was unable to execute the Statement." + Neo_DatabaseError_Transaction_CouldNotBegin: "The database was unable to start the Transaction." + Neo_DatabaseError_Transaction_CouldNotCommit: "The database was unable to commit the Transaction." + Neo_DatabaseError_Transaction_CouldNotRollback: "The database was unable to roll back the Transaction." + Neo_DatabaseError_Transaction_CouldNotWriteToLog: "The database was unable to write transaction to log." + Neo_DatabaseError_Transaction_ReleaseLocksFailed: "The transaction was unable to release one or more of its locks." + Neo_TransientError_General_DatabaseUnavailable: "The database is not currently available to serve your request, refer to the database logs for more details. Retrying your request at a later time may succeed." + Neo_TransientError_Network_UnknownFailure: "An unknown network failure occurred, a retry may resolve the issue." + Neo_TransientError_Schema_ModifiedConcurrently: "The database schema was modified while this transaction was running, the transaction should be retried." + Neo_TransientError_Security_ModifiedConcurrently: "The user was modified concurrently to this Request." + Neo_TransientError_Statement_ExternalResourceFailure: "The external resource is not available" + Neo_TransientError_Transaction_AcquireLockTimeout: "The transaction was unable to acquire a lock, for instance due to a timeout or the transaction thread being interrupted." + Neo_TransientError_Transaction_DeadlockDetected: "This transaction, and at least one more transaction, has acquired locks in a way that it will wait indefinitely, and the database has aborted it. Retrying this transaction will most likely be successful." \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/catalog-be/users-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/users-configuration.yaml new file mode 100644 index 0000000000..a6c23653f0 --- /dev/null +++ b/catalog-be/src/test/resources/config/catalog-be/users-configuration.yaml @@ -0,0 +1,2 @@ +userCredentials: + ci: 2a1f887d607d4515d4066fe0f5452a50:0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/configuration1.yaml b/catalog-be/src/test/resources/config/configuration1.yaml new file mode 100644 index 0000000000..12ab2c777f --- /dev/null +++ b/catalog-be/src/test/resources/config/configuration1.yaml @@ -0,0 +1,17 @@ +version: 1.0 +released: 2012-11-30 + +# Connection parameters +connection: + url: jdbc:mysql://localhost:3306/db + poolSize: 5 + +# Protocols +protocols: + - http + - https + +# Users +users: + tom: passwd + bob: passwd \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/elasticsearch.yml b/catalog-be/src/test/resources/config/elasticsearch.yml new file mode 100644 index 0000000000..a6a2c1b950 --- /dev/null +++ b/catalog-be/src/test/resources/config/elasticsearch.yml @@ -0,0 +1,387 @@ + +cluster.name: elasticsearch_1_5_2 + +discovery.zen.ping.multicast.enabled: false +discovery.zen.ping.unicast.enabled: true +discovery.zen.ping.unicast.hosts: elasticsearch_host + + + +##################### Elasticsearch Configuration Example ##################### + +# This file contains an overview of various configuration settings, +# targeted at operations staff. Application developers should +# consult the guide at . +# +# The installation procedure is covered at +# . +# +# Elasticsearch comes with reasonable defaults for most settings, +# so you can try it out without bothering with configuration. +# +# Most of the time, these defaults are just fine for running a production +# cluster. If you're fine-tuning your cluster, or wondering about the +# effect of certain configuration option, please _do ask_ on the +# mailing list or IRC channel [http://elasticsearch.org/community]. + +# Any element in the configuration can be replaced with environment variables +# by placing them in ${...} notation. For example: +# +# node.rack: ${RACK_ENV_VAR} + +# For information on supported formats and syntax for the config file, see +# + + +################################### Cluster ################################### + +# Cluster name identifies your cluster for auto-discovery. If you're running +# multiple clusters on the same network, make sure you're using unique names. +# +# cluster.name: elasticsearch + + +#################################### Node ##################################### + +# Node names are generated dynamically on startup, so you're relieved +# from configuring them manually. You can tie this node to a specific name: +# +# node.name: "Franz Kafka" + +# Every node can be configured to allow or deny being eligible as the master, +# and to allow or deny to store the data. +# +# Allow this node to be eligible as a master node (enabled by default): +# +# node.master: true +# +# Allow this node to store data (enabled by default): +# +# node.data: true + +# You can exploit these settings to design advanced cluster topologies. +# +# 1. You want this node to never become a master node, only to hold data. +# This will be the "workhorse" of your cluster. +# +# node.master: false +# node.data: true +# +# 2. You want this node to only serve as a master: to not store any data and +# to have free resources. This will be the "coordinator" of your cluster. +# +# node.master: true +# node.data: false +# +# 3. You want this node to be neither master nor data node, but +# to act as a "search load balancer" (fetching data from nodes, +# aggregating results, etc.) +# +# node.master: false +# node.data: false + +# Use the Cluster Health API [http://localhost:9200/_cluster/health], the +# Node Info API [http://localhost:9200/_nodes] or GUI tools +# such as , +# , +# and +# to inspect the cluster state. + +# A node can have generic attributes associated with it, which can later be used +# for customized shard allocation filtering, or allocation awareness. An attribute +# is a simple key value pair, similar to node.key: value, here is an example: +# +# node.rack: rack314 + +# By default, multiple nodes are allowed to start from the same installation location +# to disable it, set the following: +# node.max_local_storage_nodes: 1 + + +#################################### Index #################################### + +# You can set a number of options (such as shard/replica options, mapping +# or analyzer definitions, translog settings, ...) for indices globally, +# in this file. +# +# Note, that it makes more sense to configure index settings specifically for +# a certain index, either when creating it or by using the index templates API. +# +# See and +# +# for more information. + +# Set the number of shards (splits) of an index (5 by default): +# +# index.number_of_shards: 5 + +# Set the number of replicas (additional copies) of an index (1 by default): +# +# index.number_of_replicas: 1 + +# Note, that for development on a local machine, with small indices, it usually +# makes sense to "disable" the distributed features: +# +index.number_of_shards: 1 +index.number_of_replicas: 0 + +# These settings directly affect the performance of index and search operations +# in your cluster. Assuming you have enough machines to hold shards and +# replicas, the rule of thumb is: +# +# 1. Having more *shards* enhances the _indexing_ performance and allows to +# _distribute_ a big index across machines. +# 2. Having more *replicas* enhances the _search_ performance and improves the +# cluster _availability_. +# +# The "number_of_shards" is a one-time setting for an index. +# +# The "number_of_replicas" can be increased or decreased anytime, +# by using the Index Update Settings API. +# +# Elasticsearch takes care about load balancing, relocating, gathering the +# results from nodes, etc. Experiment with different settings to fine-tune +# your setup. + +# Use the Index Status API () to inspect +# the index status. + + +#################################### Paths #################################### + +# Path to directory containing configuration (this file and logging.yml): +# +path.conf: /src/test/resources + +# Path to directory where to store index data allocated for this node. +# +path.data: target/esdata +# +# Can optionally include more than one location, causing data to be striped across +# the locations (a la RAID 0) on a file level, favouring locations with most free +# space on creation. For example: +# +# path.data: /path/to/data1,/path/to/data2 + +# Path to temporary files: +# +path.work: /target/eswork + +# Path to log files: +# +path.logs: /target/eslogs + +# Path to where plugins are installed: +# +# path.plugins: /path/to/plugins + + +#################################### Plugin ################################### + +# If a plugin listed here is not installed for current node, the node will not start. +# +# plugin.mandatory: mapper-attachments,lang-groovy + + +################################### Memory #################################### + +# Elasticsearch performs poorly when JVM starts swapping: you should ensure that +# it _never_ swaps. +# +# Set this property to true to lock the memory: +# +# bootstrap.mlockall: true + +# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set +# to the same value, and that the machine has enough memory to allocate +# for Elasticsearch, leaving enough memory for the operating system itself. +# +# You should also make sure that the Elasticsearch process is allowed to lock +# the memory, eg. by using `ulimit -l unlimited`. + + +############################## Network And HTTP ############################### + +# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens +# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node +# communication. (the range means that if the port is busy, it will automatically +# try the next port). + +# Set the bind address specifically (IPv4 or IPv6): +# +# network.bind_host: 192.168.0.1 + +# Set the address other nodes will use to communicate with this node. If not +# set, it is automatically derived. It must point to an actual IP address. +# +# network.publish_host: 192.168.0.1 + +# Set both 'bind_host' and 'publish_host': +# +# network.host: 192.168.0.1 + +# Set a custom port for the node to node communication (9300 by default): +# +# transport.tcp.port: 9300 + +# Enable compression for all communication between nodes (disabled by default): +# +# transport.tcp.compress: true + +# Set a custom port to listen for HTTP traffic: +# +# http.port: 9200 + +# Set a custom allowed content length: +# +# http.max_content_length: 100mb + +# Disable HTTP completely: +# +# http.enabled: false + + +################################### Gateway ################################### + +# The gateway allows for persisting the cluster state between full cluster +# restarts. Every change to the state (such as adding an index) will be stored +# in the gateway, and when the cluster starts up for the first time, +# it will read its state from the gateway. + +# There are several types of gateway implementations. For more information, see +# . + +# The default gateway type is the "local" gateway (recommended): +# +# gateway.type: local + +# Settings below control how and when to start the initial recovery process on +# a full cluster restart (to reuse as much local data as possible when using shared +# gateway). + +# Allow recovery process after N nodes in a cluster are up: +# +gateway.recover_after_nodes: 1 + +# Set the timeout to initiate the recovery process, once the N nodes +# from previous setting are up (accepts time value): +# +# gateway.recover_after_time: 5m + +# Set how many nodes are expected in this cluster. Once these N nodes +# are up (and recover_after_nodes is met), begin recovery process immediately +# (without waiting for recover_after_time to expire): +# +gateway.expected_nodes: 1 + + +############################# Recovery Throttling ############################# + +# These settings allow to control the process of shards allocation between +# nodes during initial recovery, replica allocation, rebalancing, +# or when adding and removing nodes. + +# Set the number of concurrent recoveries happening on a node: +# +# 1. During the initial recovery +# +# cluster.routing.allocation.node_initial_primaries_recoveries: 4 +# +# 2. During adding/removing nodes, rebalancing, etc +# +# cluster.routing.allocation.node_concurrent_recoveries: 2 + +# Set to throttle throughput when recovering (eg. 100mb, by default 20mb): +# +# indices.recovery.max_bytes_per_sec: 20mb + +# Set to limit the number of open concurrent streams when +# recovering a shard from a peer: +# +# indices.recovery.concurrent_streams: 5 + + +################################## Discovery ################################## + +# Discovery infrastructure ensures nodes can be found within a cluster +# and master node is elected. Multicast discovery is the default. + +# Set to ensure a node sees N other master eligible nodes to be considered +# operational within the cluster. Its recommended to set it to a higher value +# than 1 when running more than 2 nodes in the cluster. +# +# discovery.zen.minimum_master_nodes: 1 + +# Set the time to wait for ping responses from other nodes when discovering. +# Set this option to a higher value on a slow or congested network +# to minimize discovery failures: +# +# discovery.zen.ping.timeout: 3s + +# For more information, see +# + +# Unicast discovery allows to explicitly control which nodes will be used +# to discover the cluster. It can be used when multicast is not present, +# or to restrict the cluster communication-wise. +# +# 1. Disable multicast discovery (enabled by default): +# +# discovery.zen.ping.multicast.enabled: false +# +# 2. Configure an initial list of master nodes in the cluster +# to perform discovery when new nodes (master or data) are started: +# +# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"] + +# EC2 discovery allows to use AWS EC2 API in order to perform discovery. +# +# You have to install the cloud-aws plugin for enabling the EC2 discovery. +# +# For more information, see +# +# +# See +# for a step-by-step tutorial. + +# GCE discovery allows to use Google Compute Engine API in order to perform discovery. +# +# You have to install the cloud-gce plugin for enabling the GCE discovery. +# +# For more information, see . + +# Azure discovery allows to use Azure API in order to perform discovery. +# +# You have to install the cloud-azure plugin for enabling the Azure discovery. +# +# For more information, see . + +################################## Slow Log ################################## + +# Shard level query and fetch threshold logging. + +#index.search.slowlog.threshold.query.warn: 10s +#index.search.slowlog.threshold.query.info: 5s +#index.search.slowlog.threshold.query.debug: 2s +#index.search.slowlog.threshold.query.trace: 500ms + +#index.search.slowlog.threshold.fetch.warn: 1s +#index.search.slowlog.threshold.fetch.info: 800ms +#index.search.slowlog.threshold.fetch.debug: 500ms +#index.search.slowlog.threshold.fetch.trace: 200ms + +#index.indexing.slowlog.threshold.index.warn: 10s +#index.indexing.slowlog.threshold.index.info: 5s +#index.indexing.slowlog.threshold.index.debug: 2s +#index.indexing.slowlog.threshold.index.trace: 500ms + +################################## GC Logging ################################ + +#monitor.jvm.gc.young.warn: 1000ms +#monitor.jvm.gc.young.info: 700ms +#monitor.jvm.gc.young.debug: 400ms + +#monitor.jvm.gc.old.warn: 10s +#monitor.jvm.gc.old.info: 5s +#monitor.jvm.gc.old.debug: 2s + diff --git a/catalog-be/src/test/resources/config/elasticsearch.yml.bak b/catalog-be/src/test/resources/config/elasticsearch.yml.bak new file mode 100644 index 0000000000..98c6864bf2 --- /dev/null +++ b/catalog-be/src/test/resources/config/elasticsearch.yml.bak @@ -0,0 +1,387 @@ + +cluster.name: elasticsearch_pavel + +discovery.zen.ping.multicast.enabled: false +discovery.zen.ping.unicast.enabled: true +discovery.zen.ping.unicast.hosts: elasticsearch_host + + + +##################### Elasticsearch Configuration Example ##################### + +# This file contains an overview of various configuration settings, +# targeted at operations staff. Application developers should +# consult the guide at . +# +# The installation procedure is covered at +# . +# +# Elasticsearch comes with reasonable defaults for most settings, +# so you can try it out without bothering with configuration. +# +# Most of the time, these defaults are just fine for running a production +# cluster. If you're fine-tuning your cluster, or wondering about the +# effect of certain configuration option, please _do ask_ on the +# mailing list or IRC channel [http://elasticsearch.org/community]. + +# Any element in the configuration can be replaced with environment variables +# by placing them in ${...} notation. For example: +# +# node.rack: ${RACK_ENV_VAR} + +# For information on supported formats and syntax for the config file, see +# + + +################################### Cluster ################################### + +# Cluster name identifies your cluster for auto-discovery. If you're running +# multiple clusters on the same network, make sure you're using unique names. +# +# cluster.name: elasticsearch + + +#################################### Node ##################################### + +# Node names are generated dynamically on startup, so you're relieved +# from configuring them manually. You can tie this node to a specific name: +# +# node.name: "Franz Kafka" + +# Every node can be configured to allow or deny being eligible as the master, +# and to allow or deny to store the data. +# +# Allow this node to be eligible as a master node (enabled by default): +# +# node.master: true +# +# Allow this node to store data (enabled by default): +# +# node.data: true + +# You can exploit these settings to design advanced cluster topologies. +# +# 1. You want this node to never become a master node, only to hold data. +# This will be the "workhorse" of your cluster. +# +# node.master: false +# node.data: true +# +# 2. You want this node to only serve as a master: to not store any data and +# to have free resources. This will be the "coordinator" of your cluster. +# +# node.master: true +# node.data: false +# +# 3. You want this node to be neither master nor data node, but +# to act as a "search load balancer" (fetching data from nodes, +# aggregating results, etc.) +# +# node.master: false +# node.data: false + +# Use the Cluster Health API [http://localhost:9200/_cluster/health], the +# Node Info API [http://localhost:9200/_nodes] or GUI tools +# such as , +# , +# and +# to inspect the cluster state. + +# A node can have generic attributes associated with it, which can later be used +# for customized shard allocation filtering, or allocation awareness. An attribute +# is a simple key value pair, similar to node.key: value, here is an example: +# +# node.rack: rack314 + +# By default, multiple nodes are allowed to start from the same installation location +# to disable it, set the following: +# node.max_local_storage_nodes: 1 + + +#################################### Index #################################### + +# You can set a number of options (such as shard/replica options, mapping +# or analyzer definitions, translog settings, ...) for indices globally, +# in this file. +# +# Note, that it makes more sense to configure index settings specifically for +# a certain index, either when creating it or by using the index templates API. +# +# See and +# +# for more information. + +# Set the number of shards (splits) of an index (5 by default): +# +# index.number_of_shards: 5 + +# Set the number of replicas (additional copies) of an index (1 by default): +# +# index.number_of_replicas: 1 + +# Note, that for development on a local machine, with small indices, it usually +# makes sense to "disable" the distributed features: +# +index.number_of_shards: 1 +index.number_of_replicas: 0 + +# These settings directly affect the performance of index and search operations +# in your cluster. Assuming you have enough machines to hold shards and +# replicas, the rule of thumb is: +# +# 1. Having more *shards* enhances the _indexing_ performance and allows to +# _distribute_ a big index across machines. +# 2. Having more *replicas* enhances the _search_ performance and improves the +# cluster _availability_. +# +# The "number_of_shards" is a one-time setting for an index. +# +# The "number_of_replicas" can be increased or decreased anytime, +# by using the Index Update Settings API. +# +# Elasticsearch takes care about load balancing, relocating, gathering the +# results from nodes, etc. Experiment with different settings to fine-tune +# your setup. + +# Use the Index Status API () to inspect +# the index status. + + +#################################### Paths #################################### + +# Path to directory containing configuration (this file and logging.yml): +# +path.conf: /src/test/resources + +# Path to directory where to store index data allocated for this node. +# +path.data: target/esdata +# +# Can optionally include more than one location, causing data to be striped across +# the locations (a la RAID 0) on a file level, favouring locations with most free +# space on creation. For example: +# +# path.data: /path/to/data1,/path/to/data2 + +# Path to temporary files: +# +path.work: /target/eswork + +# Path to log files: +# +path.logs: /target/eslogs + +# Path to where plugins are installed: +# +# path.plugins: /path/to/plugins + + +#################################### Plugin ################################### + +# If a plugin listed here is not installed for current node, the node will not start. +# +# plugin.mandatory: mapper-attachments,lang-groovy + + +################################### Memory #################################### + +# Elasticsearch performs poorly when JVM starts swapping: you should ensure that +# it _never_ swaps. +# +# Set this property to true to lock the memory: +# +# bootstrap.mlockall: true + +# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set +# to the same value, and that the machine has enough memory to allocate +# for Elasticsearch, leaving enough memory for the operating system itself. +# +# You should also make sure that the Elasticsearch process is allowed to lock +# the memory, eg. by using `ulimit -l unlimited`. + + +############################## Network And HTTP ############################### + +# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens +# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node +# communication. (the range means that if the port is busy, it will automatically +# try the next port). + +# Set the bind address specifically (IPv4 or IPv6): +# +# network.bind_host: 192.168.0.1 + +# Set the address other nodes will use to communicate with this node. If not +# set, it is automatically derived. It must point to an actual IP address. +# +# network.publish_host: 192.168.0.1 + +# Set both 'bind_host' and 'publish_host': +# +# network.host: 192.168.0.1 + +# Set a custom port for the node to node communication (9300 by default): +# +# transport.tcp.port: 9300 + +# Enable compression for all communication between nodes (disabled by default): +# +# transport.tcp.compress: true + +# Set a custom port to listen for HTTP traffic: +# +# http.port: 9200 + +# Set a custom allowed content length: +# +# http.max_content_length: 100mb + +# Disable HTTP completely: +# +# http.enabled: false + + +################################### Gateway ################################### + +# The gateway allows for persisting the cluster state between full cluster +# restarts. Every change to the state (such as adding an index) will be stored +# in the gateway, and when the cluster starts up for the first time, +# it will read its state from the gateway. + +# There are several types of gateway implementations. For more information, see +# . + +# The default gateway type is the "local" gateway (recommended): +# +# gateway.type: local + +# Settings below control how and when to start the initial recovery process on +# a full cluster restart (to reuse as much local data as possible when using shared +# gateway). + +# Allow recovery process after N nodes in a cluster are up: +# +gateway.recover_after_nodes: 1 + +# Set the timeout to initiate the recovery process, once the N nodes +# from previous setting are up (accepts time value): +# +# gateway.recover_after_time: 5m + +# Set how many nodes are expected in this cluster. Once these N nodes +# are up (and recover_after_nodes is met), begin recovery process immediately +# (without waiting for recover_after_time to expire): +# +gateway.expected_nodes: 1 + + +############################# Recovery Throttling ############################# + +# These settings allow to control the process of shards allocation between +# nodes during initial recovery, replica allocation, rebalancing, +# or when adding and removing nodes. + +# Set the number of concurrent recoveries happening on a node: +# +# 1. During the initial recovery +# +# cluster.routing.allocation.node_initial_primaries_recoveries: 4 +# +# 2. During adding/removing nodes, rebalancing, etc +# +# cluster.routing.allocation.node_concurrent_recoveries: 2 + +# Set to throttle throughput when recovering (eg. 100mb, by default 20mb): +# +# indices.recovery.max_bytes_per_sec: 20mb + +# Set to limit the number of open concurrent streams when +# recovering a shard from a peer: +# +# indices.recovery.concurrent_streams: 5 + + +################################## Discovery ################################## + +# Discovery infrastructure ensures nodes can be found within a cluster +# and master node is elected. Multicast discovery is the default. + +# Set to ensure a node sees N other master eligible nodes to be considered +# operational within the cluster. Its recommended to set it to a higher value +# than 1 when running more than 2 nodes in the cluster. +# +# discovery.zen.minimum_master_nodes: 1 + +# Set the time to wait for ping responses from other nodes when discovering. +# Set this option to a higher value on a slow or congested network +# to minimize discovery failures: +# +# discovery.zen.ping.timeout: 3s + +# For more information, see +# + +# Unicast discovery allows to explicitly control which nodes will be used +# to discover the cluster. It can be used when multicast is not present, +# or to restrict the cluster communication-wise. +# +# 1. Disable multicast discovery (enabled by default): +# +# discovery.zen.ping.multicast.enabled: false +# +# 2. Configure an initial list of master nodes in the cluster +# to perform discovery when new nodes (master or data) are started: +# +# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"] + +# EC2 discovery allows to use AWS EC2 API in order to perform discovery. +# +# You have to install the cloud-aws plugin for enabling the EC2 discovery. +# +# For more information, see +# +# +# See +# for a step-by-step tutorial. + +# GCE discovery allows to use Google Compute Engine API in order to perform discovery. +# +# You have to install the cloud-gce plugin for enabling the GCE discovery. +# +# For more information, see . + +# Azure discovery allows to use Azure API in order to perform discovery. +# +# You have to install the cloud-azure plugin for enabling the Azure discovery. +# +# For more information, see . + +################################## Slow Log ################################## + +# Shard level query and fetch threshold logging. + +#index.search.slowlog.threshold.query.warn: 10s +#index.search.slowlog.threshold.query.info: 5s +#index.search.slowlog.threshold.query.debug: 2s +#index.search.slowlog.threshold.query.trace: 500ms + +#index.search.slowlog.threshold.fetch.warn: 1s +#index.search.slowlog.threshold.fetch.info: 800ms +#index.search.slowlog.threshold.fetch.debug: 500ms +#index.search.slowlog.threshold.fetch.trace: 200ms + +#index.indexing.slowlog.threshold.index.warn: 10s +#index.indexing.slowlog.threshold.index.info: 5s +#index.indexing.slowlog.threshold.index.debug: 2s +#index.indexing.slowlog.threshold.index.trace: 500ms + +################################## GC Logging ################################ + +#monitor.jvm.gc.young.warn: 1000ms +#monitor.jvm.gc.young.info: 700ms +#monitor.jvm.gc.young.debug: 400ms + +#monitor.jvm.gc.old.warn: 10s +#monitor.jvm.gc.old.info: 5s +#monitor.jvm.gc.old.debug: 2s + diff --git a/catalog-be/src/test/resources/config/mysql-type-empty-nodes.zip b/catalog-be/src/test/resources/config/mysql-type-empty-nodes.zip new file mode 100644 index 0000000000..d317bccd1e Binary files /dev/null and b/catalog-be/src/test/resources/config/mysql-type-empty-nodes.zip differ diff --git a/catalog-be/src/test/resources/config/mysql-type-no-nodes.zip b/catalog-be/src/test/resources/config/mysql-type-no-nodes.zip new file mode 100644 index 0000000000..09999faed5 Binary files /dev/null and b/catalog-be/src/test/resources/config/mysql-type-no-nodes.zip differ diff --git a/catalog-be/src/test/resources/config/mysql-type-no-version.zip b/catalog-be/src/test/resources/config/mysql-type-no-version.zip new file mode 100644 index 0000000000..fa1319f311 Binary files /dev/null and b/catalog-be/src/test/resources/config/mysql-type-no-version.zip differ diff --git a/catalog-be/src/test/resources/config/mysql-type-only-yaml.zip b/catalog-be/src/test/resources/config/mysql-type-only-yaml.zip new file mode 100644 index 0000000000..b4b1946940 Binary files /dev/null and b/catalog-be/src/test/resources/config/mysql-type-only-yaml.zip differ diff --git a/catalog-be/src/test/resources/config/mysql-type-with-scripts.zip b/catalog-be/src/test/resources/config/mysql-type-with-scripts.zip new file mode 100644 index 0000000000..d689b668a1 Binary files /dev/null and b/catalog-be/src/test/resources/config/mysql-type-with-scripts.zip differ diff --git a/catalog-be/src/test/resources/config/mysql-type.yml b/catalog-be/src/test/resources/config/mysql-type.yml new file mode 100644 index 0000000000..f1985a0bdc --- /dev/null +++ b/catalog-be/src/test/resources/config/mysql-type.yml @@ -0,0 +1,82 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03 +description: MySQL RDBMS installation on a specific mounted volume path. +template_name: mysql-type +template_version: 1.1.1-SNAPSHOT +template_author: FastConnect + +imports: + - "tosca-normative-types:1.0.0.wd03-SNAPSHOT" + +node_types: + alien.nodes.Mysql: + derived_from: tosca.nodes.Database + description: > + A node to install MySQL v5.5 database with data + on a specific attached volume. + capabilities: + host: + type: alien.capabilities.MysqlDatabase + properties: + valid_node_types: [ tosca.nodes.WebApplication ] + requirements: + - host: tosca.nodes.Compute + type: tosca.relationships.HostedOn + tags: + icon: /images/mysql.png + properties: + db_port: + type: integer + default: 3306 + description: The port on which the underlying database service will listen to data. + db_name: + type: string + required: true + default: wordpress + description: The logical name of the database. + db_user: + type: string + default: pass + description: The special user account used for database administration. + db_password: + type: string + default: pass + description: The password associated with the user account provided in the ‘db_user’ property. + bind_address: + type: boolean + default: true + required: false + description: If true,the server accepts TCP/IP connections on all server host IPv4 interfaces. + storage_path: + type: string + default: /mountedStorage + constraints: + - valid_values: [ "/mountedStorage", "/var/mysql" ] + interfaces: + Standard: + create: scripts/install_mysql.sh + start: + inputs: + VOLUME_HOME: { get_property: [SELF, storage_path] } + PORT: { get_property: [SELF, db_port] } + DB_NAME: { get_property: [SELF, db_name] } + DB_USER: { get_property: [SELF, db_user] } + DB_PASSWORD: { get_property: [SELF, db_password] } + BIND_ADRESS: { get_property: [SELF, bind_address] } + implementation: scripts/start_mysql.sh + fastconnect.cloudify.extensions: + start_detection: + inputs: + PORT: { get_property: [SELF, db_port] } + implementation: scripts/mysql_start_detection.groovy + artifacts: + - scripts: scripts + type: tosca.artifacts.File + +capability_types: + alien.capabilities.MysqlDatabase: + derived_from: tosca.capabilities.Container + +artifact_types: + tosca.artifacts.GroovyScript: + description: A groovy script (.groovy file) + file_ext: [groovy] diff --git a/catalog-be/src/test/resources/config/mysql-type.zip b/catalog-be/src/test/resources/config/mysql-type.zip new file mode 100644 index 0000000000..b4b1946940 Binary files /dev/null and b/catalog-be/src/test/resources/config/mysql-type.zip differ diff --git a/catalog-be/src/test/resources/config/normative-types-root.zip b/catalog-be/src/test/resources/config/normative-types-root.zip new file mode 100644 index 0000000000..b0c39962d1 Binary files /dev/null and b/catalog-be/src/test/resources/config/normative-types-root.zip differ diff --git a/catalog-be/src/test/resources/config/sample.yaml b/catalog-be/src/test/resources/config/sample.yaml new file mode 100644 index 0000000000..12ab2c777f --- /dev/null +++ b/catalog-be/src/test/resources/config/sample.yaml @@ -0,0 +1,17 @@ +version: 1.0 +released: 2012-11-30 + +# Connection parameters +connection: + url: jdbc:mysql://localhost:3306/db + poolSize: 5 + +# Protocols +protocols: + - http + - https + +# Users +users: + tom: passwd + bob: passwd \ No newline at end of file diff --git a/catalog-be/src/test/resources/config/sampleNoProtocol.yaml b/catalog-be/src/test/resources/config/sampleNoProtocol.yaml new file mode 100644 index 0000000000..6197232aa4 --- /dev/null +++ b/catalog-be/src/test/resources/config/sampleNoProtocol.yaml @@ -0,0 +1,17 @@ +version: 1.0 +released: 2012-11-30 + +# Connection parameters +connection: + url: jdbc:mysql://localhost:3306/db + poolSize: 5 + +# Protocols +#protocols: +# - http +# - https + +# Users +users: + tom: passwd + bob: passwd \ No newline at end of file diff --git a/catalog-be/src/test/resources/elasticsearch.yml b/catalog-be/src/test/resources/elasticsearch.yml new file mode 100644 index 0000000000..eba942dc31 --- /dev/null +++ b/catalog-be/src/test/resources/elasticsearch.yml @@ -0,0 +1,391 @@ + +elasticSearch.local: true +elasticSearch.transportclient: false +cluster.name: elasticsearch_1_5_2222 + +discovery.zen.ping.multicast.enabled: false +discovery.zen.ping.unicast.enabled: true +discovery.zen.ping.unicast.hosts: 1.2.3.4 +transport.client.initial_nodes: + - 1.2.3.4:9300 + +#plugin.types: "DeleteByQueryPlugin" + +##################### Elasticsearch Configuration Example ##################### + +# This file contains an overview of various configuration settings, +# targeted at operations staff. Application developers should +# consult the guide at . +# +# The installation procedure is covered at +# . +# +# Elasticsearch comes with reasonable defaults for most settings, +# so you can try it out without bothering with configuration. +# +# Most of the time, these defaults are just fine for running a production +# cluster. If you're fine-tuning your cluster, or wondering about the +# effect of certain configuration option, please _do ask_ on the +# mailing list or IRC channel [http://elasticsearch.org/community]. + +# Any element in the configuration can be replaced with environment variables +# by placing them in ${...} notation. For example: +# +# node.rack: ${RACK_ENV_VAR} + +# For information on supported formats and syntax for the config file, see +# + + +################################### Cluster ################################### + +# Cluster name identifies your cluster for auto-discovery. If you're running +# multiple clusters on the same network, make sure you're using unique names. +# +# cluster.name: elasticsearch + + +#################################### Node ##################################### + +# Node names are generated dynamically on startup, so you're relieved +# from configuring them manually. You can tie this node to a specific name: +# +# node.name: "Franz Kafka" + +# Every node can be configured to allow or deny being eligible as the master, +# and to allow or deny to store the data. +# +# Allow this node to be eligible as a master node (enabled by default): +# +# node.master: true +# +# Allow this node to store data (enabled by default): +# +# node.data: true + +# You can exploit these settings to design advanced cluster topologies. +# +# 1. You want this node to never become a master node, only to hold data. +# This will be the "workhorse" of your cluster. +# +# node.master: false +# node.data: true +# +# 2. You want this node to only serve as a master: to not store any data and +# to have free resources. This will be the "coordinator" of your cluster. +# +# node.master: true +# node.data: false +# +# 3. You want this node to be neither master nor data node, but +# to act as a "search load balancer" (fetching data from nodes, +# aggregating results, etc.) +# +# node.master: false +# node.data: false + +# Use the Cluster Health API [http://localhost:9200/_cluster/health], the +# Node Info API [http://localhost:9200/_nodes] or GUI tools +# such as , +# , +# and +# to inspect the cluster state. + +# A node can have generic attributes associated with it, which can later be used +# for customized shard allocation filtering, or allocation awareness. An attribute +# is a simple key value pair, similar to node.key: value, here is an example: +# +# node.rack: rack314 + +# By default, multiple nodes are allowed to start from the same installation location +# to disable it, set the following: +# node.max_local_storage_nodes: 1 + + +#################################### Index #################################### + +# You can set a number of options (such as shard/replica options, mapping +# or analyzer definitions, translog settings, ...) for indices globally, +# in this file. +# +# Note, that it makes more sense to configure index settings specifically for +# a certain index, either when creating it or by using the index templates API. +# +# See and +# +# for more information. + +# Set the number of shards (splits) of an index (5 by default): +# +# index.number_of_shards: 5 + +# Set the number of replicas (additional copies) of an index (1 by default): +# +# index.number_of_replicas: 1 + +# Note, that for development on a local machine, with small indices, it usually +# makes sense to "disable" the distributed features: +# +index.number_of_shards: 1 +index.number_of_replicas: 0 + +# These settings directly affect the performance of index and search operations +# in your cluster. Assuming you have enough machines to hold shards and +# replicas, the rule of thumb is: +# +# 1. Having more *shards* enhances the _indexing_ performance and allows to +# _distribute_ a big index across machines. +# 2. Having more *replicas* enhances the _search_ performance and improves the +# cluster _availability_. +# +# The "number_of_shards" is a one-time setting for an index. +# +# The "number_of_replicas" can be increased or decreased anytime, +# by using the Index Update Settings API. +# +# Elasticsearch takes care about load balancing, relocating, gathering the +# results from nodes, etc. Experiment with different settings to fine-tune +# your setup. + +# Use the Index Status API () to inspect +# the index status. + + +#################################### Paths #################################### +path.home: /src/test/resources +# Path to directory containing configuration (this file and logging.yml): +# +path.conf: /src/test/resources + +# Path to directory where to store index data allocated for this node. +# +path.data: target/esdata +# +# Can optionally include more than one location, causing data to be striped across +# the locations (a la RAID 0) on a file level, favouring locations with most free +# space on creation. For example: +# +# path.data: /path/to/data1,/path/to/data2 + +# Path to temporary files: +# +path.work: /target/eswork + +# Path to log files: +# +path.logs: /target/eslogs + +# Path to where plugins are installed: +# +# path.plugins: /path/to/plugins + + +#################################### Plugin ################################### + +# If a plugin listed here is not installed for current node, the node will not start. +# +# plugin.mandatory: mapper-attachments,lang-groovy + + +################################### Memory #################################### + +# Elasticsearch performs poorly when JVM starts swapping: you should ensure that +# it _never_ swaps. +# +# Set this property to true to lock the memory: +# +# bootstrap.mlockall: true + +# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set +# to the same value, and that the machine has enough memory to allocate +# for Elasticsearch, leaving enough memory for the operating system itself. +# +# You should also make sure that the Elasticsearch process is allowed to lock +# the memory, eg. by using `ulimit -l unlimited`. + + +############################## Network And HTTP ############################### + +# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens +# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node +# communication. (the range means that if the port is busy, it will automatically +# try the next port). + +# Set the bind address specifically (IPv4 or IPv6): +# +# network.bind_host: 192.168.0.1 + +# Set the address other nodes will use to communicate with this node. If not +# set, it is automatically derived. It must point to an actual IP address. +# +# network.publish_host: 192.168.0.1 + +# Set both 'bind_host' and 'publish_host': +# +# network.host: 192.168.0.1 + +# Set a custom port for the node to node communication (9300 by default): +# +# transport.tcp.port: 9300 + +# Enable compression for all communication between nodes (disabled by default): +# +# transport.tcp.compress: true + +# Set a custom port to listen for HTTP traffic: +# +# http.port: 9200 + +# Set a custom allowed content length: +# +# http.max_content_length: 100mb + +# Disable HTTP completely: +# +# http.enabled: false + + +################################### Gateway ################################### + +# The gateway allows for persisting the cluster state between full cluster +# restarts. Every change to the state (such as adding an index) will be stored +# in the gateway, and when the cluster starts up for the first time, +# it will read its state from the gateway. + +# There are several types of gateway implementations. For more information, see +# . + +# The default gateway type is the "local" gateway (recommended): +# +# gateway.type: local + +# Settings below control how and when to start the initial recovery process on +# a full cluster restart (to reuse as much local data as possible when using shared +# gateway). + +# Allow recovery process after N nodes in a cluster are up: +# +gateway.recover_after_nodes: 1 + +# Set the timeout to initiate the recovery process, once the N nodes +# from previous setting are up (accepts time value): +# +# gateway.recover_after_time: 5m + +# Set how many nodes are expected in this cluster. Once these N nodes +# are up (and recover_after_nodes is met), begin recovery process immediately +# (without waiting for recover_after_time to expire): +# +gateway.expected_nodes: 1 + + +############################# Recovery Throttling ############################# + +# These settings allow to control the process of shards allocation between +# nodes during initial recovery, replica allocation, rebalancing, +# or when adding and removing nodes. + +# Set the number of concurrent recoveries happening on a node: +# +# 1. During the initial recovery +# +# cluster.routing.allocation.node_initial_primaries_recoveries: 4 +# +# 2. During adding/removing nodes, rebalancing, etc +# +# cluster.routing.allocation.node_concurrent_recoveries: 2 + +# Set to throttle throughput when recovering (eg. 100mb, by default 20mb): +# +# indices.recovery.max_bytes_per_sec: 20mb + +# Set to limit the number of open concurrent streams when +# recovering a shard from a peer: +# +# indices.recovery.concurrent_streams: 5 + + +################################## Discovery ################################## + +# Discovery infrastructure ensures nodes can be found within a cluster +# and master node is elected. Multicast discovery is the default. + +# Set to ensure a node sees N other master eligible nodes to be considered +# operational within the cluster. Its recommended to set it to a higher value +# than 1 when running more than 2 nodes in the cluster. +# +# discovery.zen.minimum_master_nodes: 1 + +# Set the time to wait for ping responses from other nodes when discovering. +# Set this option to a higher value on a slow or congested network +# to minimize discovery failures: +# +# discovery.zen.ping.timeout: 3s + +# For more information, see +# + +# Unicast discovery allows to explicitly control which nodes will be used +# to discover the cluster. It can be used when multicast is not present, +# or to restrict the cluster communication-wise. +# +# 1. Disable multicast discovery (enabled by default): +# +# discovery.zen.ping.multicast.enabled: false +# +# 2. Configure an initial list of master nodes in the cluster +# to perform discovery when new nodes (master or data) are started: +# +# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"] + +# EC2 discovery allows to use AWS EC2 API in order to perform discovery. +# +# You have to install the cloud-aws plugin for enabling the EC2 discovery. +# +# For more information, see +# +# +# See +# for a step-by-step tutorial. + +# GCE discovery allows to use Google Compute Engine API in order to perform discovery. +# +# You have to install the cloud-gce plugin for enabling the GCE discovery. +# +# For more information, see . + +# Azure discovery allows to use Azure API in order to perform discovery. +# +# You have to install the cloud-azure plugin for enabling the Azure discovery. +# +# For more information, see . + +################################## Slow Log ################################## + +# Shard level query and fetch threshold logging. + +#index.search.slowlog.threshold.query.warn: 10s +#index.search.slowlog.threshold.query.info: 5s +#index.search.slowlog.threshold.query.debug: 2s +#index.search.slowlog.threshold.query.trace: 500ms + +#index.search.slowlog.threshold.fetch.warn: 1s +#index.search.slowlog.threshold.fetch.info: 800ms +#index.search.slowlog.threshold.fetch.debug: 500ms +#index.search.slowlog.threshold.fetch.trace: 200ms + +#index.indexing.slowlog.threshold.index.warn: 10s +#index.indexing.slowlog.threshold.index.info: 5s +#index.indexing.slowlog.threshold.index.debug: 2s +#index.indexing.slowlog.threshold.index.trace: 500ms + +################################## GC Logging ################################ + +#monitor.jvm.gc.young.warn: 1000ms +#monitor.jvm.gc.young.info: 700ms +#monitor.jvm.gc.young.debug: 400ms + +#monitor.jvm.gc.old.warn: 10s +#monitor.jvm.gc.old.info: 5s +#monitor.jvm.gc.old.debug: 2s + diff --git a/catalog-be/src/test/resources/logback-test.xml b/catalog-be/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..d2b9bff23f --- /dev/null +++ b/catalog-be/src/test/resources/logback-test.xml @@ -0,0 +1,13 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/catalog-be/src/test/resources/mock_vf.csar b/catalog-be/src/test/resources/mock_vf.csar new file mode 100644 index 0000000000..4b37f44c73 Binary files /dev/null and b/catalog-be/src/test/resources/mock_vf.csar differ diff --git a/catalog-be/src/test/resources/normativeTypes/importToscaProperties.yml b/catalog-be/src/test/resources/normativeTypes/importToscaProperties.yml new file mode 100644 index 0000000000..f856603397 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/importToscaProperties.yml @@ -0,0 +1,452 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.vl.LinkTest: + derived_from: tosca.nodes.Root + properties: + string_prop01: + type: map + description : another description + default: {keyA : val1 , keyB : val2} + entry_schema: + description: This is my property + type: string + string_prop02: + type: map + description : another description + default: {keyA : "val1" , keyB : "val2"} + entry_schema: + description: This is my property + type: string + string_prop03: + type: map + description : another description + default: {"keyA" : "val1" , keyB : val2} + entry_schema: + description: This is my property + type: string + string_prop04: + type: map + description : another description + default: {"keyA" : 10 , keyB : true } + entry_schema: + description: This is my property + type: string + string_prop05: + type: map + description : another description + default: {"keyA" : , keyB : "Big" } + entry_schema: + description: This is my property + type: string + string_prop06: + type: map + description : another description + default: {"keyA" : aaaA , keyB : null } + entry_schema: + description: This is my property + type: string + string_prop07: + type: map + description : another description + default: {"keyA" : NULL , keyB : Null } + entry_schema: + description: This is my property + type: string + string_prop08: + type: map + description : another description + default: {"keyA" : "" , keyB : "abcd" } + entry_schema: + description: This is my property + type: string + string_prop09: + type: map + description : another description + default: {"keyA" : " " , keyB : "abcd" } + entry_schema: + description: This is my property + type: string + string_prop10: + type: map + description : another description + default: {"keyA" : " aaaa" , keyB : " bbbb" } + entry_schema: + description: This is my property + type: string + string_prop11: + type: map + description : another description + default: {"keyA" : "aaaa " , keyB : "bbbb " } + entry_schema: + description: This is my property + type: string + string_prop12: + type: map + description : another description + default: {"keyA" : " aaaa " , keyB : " bbbb ccccc " } + entry_schema: + description: This is my property + type: string + string_prop13: + type: map + description : another description + default: + keyA : "aaaa" + entry_schema: + description: This is my property + type: string + string_prop14: + type: map + description : another description + default: + keyA : " aaaa " + entry_schema: + description: This is my property + type: string + string_prop15: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop16: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop17: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop18: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop19: + type: map + description : another description + default: + keyA : AbcD + entry_schema: + description: This is my property + type: string + string_prop20: + type: map + description : another description + default: + keyA : aaaa + keya : aaaa + Keya : Aaaa + KEYA : nnnn + entry_schema: + description: This is my property + type: string + string_prop21: + type: map + description : another description + default: + keyA : NULL + keyB : null + keyC : Null + entry_schema: + description: This is my property + type: string + string_prop22: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: string + integer_prop01: + type: map + description : another description + default: {keyA : 1 , keyB : 1000} + entry_schema: + description: This is my property + type: integer + integer_prop02: + type: map + description : another description + default: {keyA : Null , keyB : NULL ,keyC : null } + entry_schema: + description: This is my property + type: integer + integer_prop03: + type: map + description : another description + default: {keyA : , keyB : -600} + entry_schema: + description: This is my property + type: integer + integer_prop03: + type: map + description : another description + default: {keyA : 800 , keyB : -600} + entry_schema: + description: This is my property + type: integer + integer_prop04: + type: map + description : another description + default: {keyA : , keyB : -600} + entry_schema: + description: This is my property + type: integer + integer_prop05: + type: map + description : another description + default: {keyA : 100 , keyB : 0 } + entry_schema: + description: This is my property + type: integer + integer_prop06: + type: map + description : another description + default: {keyA : 100 , keyB : 00} + entry_schema: + description: This is my property + type: integer + integer_prop07: + type: map + description : another description + default: {keyA : 100 , keyB : 100 } + entry_schema: + description: This is my property + type: integer + integer_prop08: + type: map + description : another description + default: + keyA : 100 + keyB : 200 + entry_schema: + description: This is my property + type: integer + integer_prop09: + type: map + description : another description + default: + keyA : 100 + keyB : 200 + entry_schema: + description: This is my property + type: integer + integer_prop10: + type: map + description : another description + default: + keyA : null + keyA : Null + keyB : 1111 + keyB : 2222 + entry_schema: + description: This is my property + type: integer + integer_prop11: + type: map + description : another description + default: + keyA : null + keyB : Null + keyC : NULL + keyD : + entry_schema: + description: This is my property + type: integer + integer_prop12: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: integer + integer_prop13: + type: map + description : another description + default: {keyA : 100 , keyA : 200} + entry_schema: + description: This is my property + type: integer + boolean_prop01: + type: map + description : another description + default: {keyA : true , keyB : false , keyC : false } + entry_schema: + description: This is my property + type: boolean + boolean_prop02: + type: map + description : another description + default: {keyA : TRUE , keyB : FALSE , keyC : False } + entry_schema: + description: This is my property + type: boolean + boolean_prop03: + type: map + description : another description + default: + keyA : null + keyB : Null + keyC : NULL + keyD : + entry_schema: + description: This is my property + type: boolean + boolean_prop04: + type: map + description : another description + default: {keyA : Null , keyB : NULL ,keyC : null ,keyD : } + entry_schema: + description: This is my property + type: boolean + boolean_prop05: + type: map + description : another description + default: {keyA : true , keyB : false , keyC : false } + entry_schema: + description: This is my property + type: boolean + boolean_prop06: + type: map + description : another description + default: + keyA : true + keyB : true + keyC : false + entry_schema: + description: This is my property + type: boolean + boolean_prop07: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: boolean + boolean_prop08: + type: map + description : another description + default: + keyA : false + keyA : true + keyB : true + keyB : false + entry_schema: + description: This is my property + type: boolean + boolean_prop09: + type: map + description : another description + default: {keyA : true,keyA : false,keyB : false,keyB : true} + entry_schema: + description: This is my property + type: boolean + float_prop01: + type: map + description : another description + default: {keyA : 1.20 , keyB : 3.56f , keyC : 33} + entry_schema: + description: This is my property + type: float + float_prop02: + type: map + description : another description + default: {keyA : 0.00, keyB : 0.0 , keyC : 0 } + entry_schema: + description: This is my property + type: float + float_prop03: + type: map + description : another description + default: {keyA : null, keyB : Null , keyC : NULL , keyD : } + entry_schema: + description: This is my property + type: float + float_prop04: + type: map + description : another description + default: {keyA : 1.20 , keyB : 3.56f , keyC : 33 } + entry_schema: + description: This is my property + type: float + float_prop05: + type: map + description : another description + default: + keyA : 33 + keyB : 1.2000 + keyC : 3.607f + keyD : 0 + entry_schema: + description: This is my property + type: float + float_prop06: + type: map + description : another description + default: + keyA : 33 + keyB : 1.2000 + keyC : 3.607f + entry_schema: + description: This is my property + type: float + float_prop07: + type: map + description : another description + default: + keyA : null + keyB : Null + keyC : NULL + keyD : + entry_schema: + description: This is my property + type: float + float_prop08: + type: map + description : another description + default: + entry_schema: + description: This is my property + type: float + float_prop09: + type: map + description : another description + default: + keyA : 3.5 + keyA : 0.01 + keyB : 3.6 + keyB : + entry_schema: + description: This is my property + type: float + float_prop10: + type: map + description : another description + default: {keyA : 0.0002} + entry_schema: + description: This is my property + type: float + float_prop11: + type: map + description : another description + default: {keyA : 0.000 , keyA : 003.56f, keyB : 33} + entry_schema: + description: This is my property + type: float + capabilities: + link: + type: tosca.capabilities.network.Linkable \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/importToscaWithAttribute.yml b/catalog-be/src/test/resources/normativeTypes/importToscaWithAttribute.yml new file mode 100644 index 0000000000..5a51e9e198 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/importToscaWithAttribute.yml @@ -0,0 +1,41 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.MyComputeTest: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + status: supported + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + myAttr: + type: list + description: this is my description + entry_schema: + type: string + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-all-map-test.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-all-map-test.yml new file mode 100644 index 0000000000..4cf82d8b8f --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-all-map-test.yml @@ -0,0 +1,30 @@ +tosca.nodes.BlockStorage: + allTestTag: tosca.nodes.Root + properties: + mapTestTag: + stringTestTag: stringVal1 + listTestTag: + - allTestTag: 1 MB + - listTestTag: 2 MB + - stringTestTag: stringVal2 + volume_id: + type: string + required: false + allTestTag: + - greater_or_equal: 1 MB + - stringTestTag: stringVal3 + allTestTag: + mapTestTag: string + required: true + snapshot_id: + stringTestTag: stringVal4 + required: false + listTestTag: + - testTag1: 1 MB + - mapTestTag: + - testTag1: 1 MB + - type: stringVal2 + capabilities: + mapTestTag: + type: tosca.capabilities.Attachment + allTestTag: false \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-DBMS.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-DBMS.yml new file mode 100644 index 0000000000..28919d38e4 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-DBMS.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.DBMS: + derived_from: tosca.nodes.SoftwareComponent + properties: + root_password: + type: string + required: false + description: the optional root password for the DBMS service + port: + type: integer + required: false + description: the port the DBMS service will listen to for data and requests + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [ tosca.nodes.Database ] diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-Root.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-Root.yml new file mode 100644 index 0000000000..e9b1de9518 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-Root.yml @@ -0,0 +1,23 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.Root: + description: The TOSCA Node Type all other TOSCA base Node Types derive from + attributes: + tosca_id: + type: string + tosca_name: + type: string + state: + type: string + capabilities: + feature: + type: tosca.capabilities.Node + requirements: + - dependency : + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + occurrences: [ 0, UNBOUNDED ] + interfaces: + Standard: + type: tosca.interfaces.node.lifecycle.Standard diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-blockStorage.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-blockStorage.yml new file mode 100644 index 0000000000..a82965215f --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-blockStorage.yml @@ -0,0 +1,18 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.BlockStorage: + derived_from: tosca.nodes.Root + properties: + size: + type: scalar-unit.size + constraints: + - greater_or_equal: 1 MB + volume_id: + type: string + required: false + snapshot_id: + type: string + required: false + capabilities: + attachment: + type: tosca.capabilities.Attachment diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-compute.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-compute.yml new file mode 100644 index 0000000000..00b07fb908 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-compute.yml @@ -0,0 +1,35 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.Compute: + derived_from: tosca.nodes.Root + attributes: + private_address: + type: string + public_address: + type: string + networks: + type: map + entry_schema: + type: tosca.datatypes.network.NetworkInfo + ports: + type: map + entry_schema: + type: tosca.datatypes.network.PortInfo + requirements: + - local_storage: + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + occurrences: [0, UNBOUNDED] + capabilities: + host: + type: tosca.capabilities.Container + valid_source_types: [tosca.nodes.SoftwareComponent] + endpoint : + type: tosca.capabilities.Endpoint.Admin + os: + type: tosca.capabilities.OperatingSystem + scalable: + type: tosca.capabilities.Scalable + binding: + type: tosca.capabilities.network.Bindable diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-database.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-database.yml new file mode 100644 index 0000000000..5166150c73 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-database.yml @@ -0,0 +1,27 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.Database: + derived_from: tosca.nodes.Root + properties: + name: + type: string + description: the logical name of the database + port: + type: integer + description: the port the underlying database service will listen to for data + user: + type: string + description: the optional user account name for DB administration + required: false + password: + type: string + description: the optional password for the DB user account + required: false + requirements: + - host: + capability: tosca.capabilities.Container + node: tosca.nodes.DBMS + relationship: tosca.relationships.HostedOn + capabilities: + database_endpoint: + type: tosca.capabilities.Endpoint.Database diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-port.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-port.yml new file mode 100644 index 0000000000..2d1540b27b --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-port.yml @@ -0,0 +1,31 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.network.Port: + derived_from: tosca.nodes.Root + properties: + ip_address: + type: string + required: false + order: + type: integer + required: true + default: 0 + constraints: + - greater_or_equal: 0 + is_default: + type: boolean + required: false + default: false + ip_range_start: + type: string + required: false + ip_range_end: + type: string + required: false + requirements: + - link: + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + relationship: tosca.relationships.network.BindsTo diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-softwareComponent.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-softwareComponent.yml new file mode 100644 index 0000000000..9beb93a75a --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-softwareComponent.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.SoftwareComponent: + derived_from: tosca.nodes.Root + properties: + # domain-specific software component version + component_version: + type: version + required: false + #admin_credential: + # type: tosca.datatypes.Credential + # required: false + requirements: + - host: + capability: tosca.capabilities.Container + node: tosca.nodes.Compute + relationship: tosca.relationships.HostedOn diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-new-webServer.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-new-webServer.yml new file mode 100644 index 0000000000..7c957b5247 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-new-webServer.yml @@ -0,0 +1,11 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + tosca.nodes.WebServer: + derived_from: tosca.nodes.SoftwareComponent + capabilities: + # Private, layer 4 endpoints + data_endpoint: tosca.capabilities.Endpoint + admin_endpoint: tosca.capabilities.Endpoint.Admin + host: + type: tosca.capabilities.Container + valid_source_types: [ tosca.nodes.WebApplication ] \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/normative-types-string-list-test.yml b/catalog-be/src/test/resources/normativeTypes/normative-types-string-list-test.yml new file mode 100644 index 0000000000..0a292b3418 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/normative-types-string-list-test.yml @@ -0,0 +1,29 @@ +tosca.nodes.BlockStorage: + derived_from: tosca.nodes.Root + properties: + listTestTag: + stringTestTag: stringVal1 + listTestTag: + - listTestTag: 1 MB + - listTestTag: 2 MB + - stringTestTag: stringVal2 + volume_id: + type: string + required: false + stringTestTag: + - greater_or_equal: 1 MB + - stringTestTag: stringVal3 + stringTestTag: + listTestTag: string + required: false + snapshot_id: + stringTestTag: stringVal4 + required: false + listTestTag: + - testTag1: 1 MB + - listTestTag: + - testTag1: 1 MB + - type: stringVal2 + capabilities: + attachment: + type: tosca.capabilities.Attachment diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_duplicateNode.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_duplicateNode.yml new file mode 100644 index 0000000000..be16f471fc --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_duplicateNode.yml @@ -0,0 +1,23 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + node_templates: + mongo_server: + type: tosca.nodes.Database + mongo_server: + type: tosca.nodes.Compute + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_empty.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_empty.yml new file mode 100644 index 0000000000..43ad624300 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_empty.yml @@ -0,0 +1,17 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_inputs.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_inputs.yml new file mode 100644 index 0000000000..fbc64e05fe --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_inputs.yml @@ -0,0 +1,103 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + inputs: + vf_module_id: + hidden: false + immutable: false + type: string + description: Unique ID for this VF Module instance + default: dummy + cmd_fw_srv_grp_id: + hidden: false + immutable: false + type: string + description: uuid of the server group + default: be97d566-35c1-4bc6-a9dd-a5f193cba314 + nimbus_hsl_interface_type: + hidden: false + immutable: false + type: string + description: service_interface_type for ServiceInstance + default: other + cmd_fw_names: + hidden: false + immutable: false + type: list + description: Comma Delimited List of Names for ServiceInstance VMs + default: + - ZRDM2FCMD01CMD001 + - ' ZRDM2FCMD01CMD002' + - ' ZRDM2FCMD01CMD003' + - ' ZRDM2FCMD01CMD004' + entry_schema: + type: string + cmd_fw_shc_max_retries: + hidden: false + immutable: false + type: integer + description: max_retries for the ServiceHealthCheck + default: 2 + cmd_fw_shc_url_path: + hidden: false + immutable: false + type: string + description: url_path for the ServiceHealthCheck + default: local-ip + node_templates: + nodejs: + type: tosca.nodes.WebServer + requirements: + - host: + node: app_server + mongo_db: + type: tosca.nodes.Database + requirements: + - host: mongo_dbms + mongo_dbms: + type: tosca.nodes.DBMS + properties: + root_password: + get_input: nimbus_hsl_interface_type + # fixed_ips: + # - ip_address: + # get_input: app2_int_ota_apps_ip_1 + # subnet_id: + # get_input: pmaa_dpu_subnet_id + # - ip_address: + # get_input: app2_int_ota_apps_ip_3 + # subnet_id: + # get_input: pmaa_dpu_subnet_id + # name: + # get_input: + # - mnsoamvfw_names + # - get_input: index + # metadata: + # pmaa.sb_nic: + # address: + # get_input: pmaa_dpu_fixed_ip + # cidr: + # get_input: pmaa_dpu_cidr + # gateway: + # get_input: pmaa_dpu_gateway + #port: + # get_input: cmd_fw_shc_max_retries + requirements: + - host: mongo_server + app_server: + type: tosca.nodes.Compute + mongo_server: + type: tosca.nodes.Compute + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_nodeEmpty.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_nodeEmpty.yml new file mode 100644 index 0000000000..3f8f3d15f8 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_nodeEmpty.yml @@ -0,0 +1,18 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_nodeVF.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_nodeVF.yml new file mode 100644 index 0000000000..4f1966315a --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_nodeVF.yml @@ -0,0 +1,38 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + node_templates: + my_node: + type: org.openecomp.resource.vf.Resource19 + nodejs: + type: tosca.nodes.WebServer + requirements: + - host: + node: app_server + mongo_db: + type: tosca.nodes.Database + requirements: + - host: mongo_dbms + mongo_dbms: + type: tosca.nodes.DBMS + requirements: + - host: mongo_server + app_server: + type: tosca.nodes.Compute + mongo_server: + type: tosca.nodes.Compute + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_notValidNode.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_notValidNode.yml new file mode 100644 index 0000000000..a4534fc03d --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_notValidNode.yml @@ -0,0 +1,36 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + node_templates: + nodejs: + type: tosca.nodes.KUKU + requirements: + - host: + node: app_server + mongo_db: + type: tosca.nodes.Database + requirements: + - host: mongo_dbms + mongo_dbms: + type: tosca.nodes.DBMS + requirements: + - host: mongo_server + app_server: + type: tosca.nodes.Compute + mongo_server: + type: tosca.nodes.Compute + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_notValidRelationNode.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_notValidRelationNode.yml new file mode 100644 index 0000000000..f606769387 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_notValidRelationNode.yml @@ -0,0 +1,36 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + node_templates: + nodejs: + type: tosca.nodes.WebServer + requirements: + - host: + node: KUKU + mongo_db: + type: tosca.nodes.Database + requirements: + - host: mongo_dbms + mongo_dbms: + type: tosca.nodes.DBMS + requirements: + - host: mongo_server + app_server: + type: tosca.nodes.Compute + mongo_server: + type: tosca.nodes.Compute + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/normativeTypes/topology_template_sample.yml b/catalog-be/src/test/resources/normativeTypes/topology_template_sample.yml new file mode 100644 index 0000000000..4b685a4497 --- /dev/null +++ b/catalog-be/src/test/resources/normativeTypes/topology_template_sample.yml @@ -0,0 +1,36 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 + +description: > + This TOSCA simple profile deploys nodejs, mongodb, each on a separate server + with monitoring enabled for nodejs server where a sample nodejs application is running. + +topology_template: + node_templates: + nodejs: + type: tosca.nodes.WebServer + requirements: + - host: + node: app_server + mongo_db: + type: tosca.nodes.Database + requirements: + - host: mongo_dbms + mongo_dbms: + type: tosca.nodes.DBMS + requirements: + - host: mongo_server + app_server: + type: tosca.nodes.Compute + mongo_server: + type: tosca.nodes.Compute + + + + outputs: + nodejs_url: + description: URL for the nodejs server, http://:3000 + value: { get_attribute: [ app_server, private_address ] } + mongodb_url: + description: URL for the mongodb server. + value: { get_attribute: [ mongo_server, private_address ] } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/capabilityTypes.yml b/catalog-be/src/test/resources/types/capabilityTypes.yml new file mode 100644 index 0000000000..58d661b17e --- /dev/null +++ b/catalog-be/src/test/resources/types/capabilityTypes.yml @@ -0,0 +1,148 @@ +tosca.capabilities.Root: + description: The TOSCA root Capability Type all other TOSCA base Capability Types derive from +tosca.capabilities.Attachment: + derived_from: tosca.capabilities.Root +tosca.capabilities.Node: + derived_from: tosca.capabilities.Root +tosca.capabilities.Container: + derived_from: tosca.capabilities.Root + properties: + num_cpus: + type: integer + required: false + constraints: + - greater_or_equal: 1 + cpu_frequency: + type: scalar-unit.frequency + required: false + constraints: + - greater_or_equal: 0.1 GHz + disk_size: + type: scalar-unit.size + required: false + constraints: + - greater_or_equal: 0 MB + mem_size: + type: scalar-unit.size + required: false + constraints: + - greater_or_equal: 0 MB +tosca.capabilities.Endpoint: + derived_from: tosca.capabilities.Root + properties: + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + secure: + type: boolean + default: false + url_path: + type: string + required: false + port_name: + type: string + required: false + network_name: + type: string + required: false + default: PRIVATE + initiator: + type: string + default: source + constraints: + - valid_values: [ source, target, peer ] + ports: + type: map + required: false + constraints: + - min_length: 1 + entry_schema: + type: PortSpec + attributes: + ip_address: + type: string +tosca.capabilities.DatabaseEndpoint: + derived_from: tosca.capabilities.Endpoint +tosca.capabilities.Endpoint.Public: + derived_from: tosca.capabilities.Endpoint + properties: + # Change the default network_name to use the first public network found + network_name: PUBLIC + floating: + description: > + indicates that the public address should be allocated from a pool of floating IPs that are associated with the network. + type: boolean + default: false + status: experimental + dns_name: + description: The optional name to register with DNS + type: string + required: false + status: experimental +tosca.capabilities.Endpoint.Admin: + derived_from: tosca.capabilities.Endpoint + # Change Endpoint secure indicator to true from its default of false + properties: + secure: true +tosca.capabilities.Endpoint.Database: + derived_from: tosca.capabilities.Endpoint +tosca.capabilities.OperatingSystem: + derived_from: tosca.capabilities.Root + properties: + architecture: + type: string + required: false + type: + type: string + required: false + distribution: + type: string + required: false + version: + type: version + required: false +tosca.capabilities.Scalable: + derived_from: tosca.capabilities.Root + properties: + min_instances: + type: integer + default: 1 + max_instances: + type: integer + default: 1 + default_instances: + type: integer +tosca.capabilities.network.Bindable: + derived_from: tosca.capabilities.Node + + +tosca.capabilities.Container.Docker: + derived_from: tosca.capabilities.Container + properties: + version: + type: list + required: false + entry_schema: version + publish_all: + type: boolean + default: false + required: false + publish_ports: + type: list + entry_schema: PortSpec + required: false + expose_ports: + type: list + entry_schema: PortSpec + required: false + volumes: + type: list + entry_schema: string + required: false +tosca.capabilities.network.Linkable: + derived_from: tosca.capabilities.Root + + diff --git a/catalog-be/src/test/resources/types/capabilityTypes.zip b/catalog-be/src/test/resources/types/capabilityTypes.zip new file mode 100644 index 0000000000..4f945a7d1f Binary files /dev/null and b/catalog-be/src/test/resources/types/capabilityTypes.zip differ diff --git a/catalog-be/src/test/resources/types/categoryTypes.yml b/catalog-be/src/test/resources/types/categoryTypes.yml new file mode 100644 index 0000000000..c853f9a52c --- /dev/null +++ b/catalog-be/src/test/resources/types/categoryTypes.yml @@ -0,0 +1,74 @@ +services: + Mobility: + name: "Mobility" + icons: ['mobility'] + Network_L1_3: + name: "Network L1-3" + icons: ['network_l_1-3'] + Network_L4: + name: "Network L4" + icons: ['network_l_4'] + VoIP_Call_Control: + name: "VoIP Call Control" + icons: ['call_controll'] +resources: + NetworkLayer23: + name: "Network Layer 2-3" + subcategories: + Router: + name: "Router" + icons: ['router'] + Gateway: + name: "Gateway" + icons: ['gateway'] + WAN_Connectors: + name: "WAN Connectors" + icons: ['connector'] + LAN_Connectors: + name: "LAN Connectors" + icons: ['connector'] + NetworkLayer4: + name: "Network Layer 4+" + subcategories: + Common_Network_Resources: + name: "Common Network Resources" + icons: ['network', 'loadBalancer'] + ApplicationLayer4: + name: "Application Layer 4+" + subcategories: + Border_Elements: + name: "Border Elements" + icons: ['borderElement'] + Application_Servers: + name: "Application Servers" + icons: ['applicationServer', 'server'] + Web_Server: + name: "Web Server" + icons: ['applicationServer', 'server'] + Call_Control: + name: "Call Control" + icons: ['call_controll'] + Media_Servers: + name: "Media Servers" + icons: ['applicationServer', 'server'] + Load_Balancer: + name: "Load Balancer" + icons: ['loadBalancer'] + Database: + name: "Database" + icons: ['database'] + Generic: + name: "Generic" + subcategories: + Infrastructure: + name: "Infrastructure" + icons: ['objectStorage', 'compute'] + Abstract: + name: "Abstract" + icons: ['objectStorage', 'compute'] + Network_Elements: + name: "Network Elements" + icons: ['port', 'network', 'router'] + Database: + name: "Database" + icons: ['database'] diff --git a/catalog-be/src/test/resources/types/categoryTypes.zip b/catalog-be/src/test/resources/types/categoryTypes.zip new file mode 100644 index 0000000000..2e08a6b43c Binary files /dev/null and b/catalog-be/src/test/resources/types/categoryTypes.zip differ diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeDeriveFromIntegerWithProperty.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeDeriveFromIntegerWithProperty.yml new file mode 100644 index 0000000000..7040f8717a --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeDeriveFromIntegerWithProperty.yml @@ -0,0 +1,8 @@ +integer: + +mytypes.phonenumber: + derived_from: integer + description: my phone number datatype + properties: + countrycode: + type: integer diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeDerivedFromRootNoProperties.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeDerivedFromRootNoProperties.yml new file mode 100644 index 0000000000..ce72cf52c4 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeDerivedFromRootNoProperties.yml @@ -0,0 +1,4 @@ +# define a new datatype that derives from existing type and extends it +mytypes.phonenumber.extended: + derived_from: tosca.datatypes.Root + description: custom phone number type that extends the basic phonenumber type diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeDuplicateProperty.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeDuplicateProperty.yml new file mode 100644 index 0000000000..32ed904882 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeDuplicateProperty.yml @@ -0,0 +1,11 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode1: + type: integer + number: + type: integer + areacode1: + type: integer diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeForGroup.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeForGroup.yml new file mode 100644 index 0000000000..e811a1ff30 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeForGroup.yml @@ -0,0 +1,40 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +integer: + derived_from: tosca.datatypes.Root + +string: + derived_from: tosca.datatypes.Root + +boolean: + derived_from: tosca.datatypes.Root + +float: + derived_from: tosca.datatypes.Root + +list: + derived_from: tosca.datatypes.Root + +map: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false + token_type: + type: string + default: password + token: + type: string + keys: + type: map + required: false + entry_schema: + type: string + user: + type: string + required: false \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part1.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part1.yml new file mode 100644 index 0000000000..b8cdc3bf62 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part1.yml @@ -0,0 +1,15 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol1: + type: string + required: false + protocol2: + type: string + required: false diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part2.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part2.yml new file mode 100644 index 0000000000..5a5be60ee3 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdatePropertyRemoved_part2.yml @@ -0,0 +1,12 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol1: + type: string + required: false \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part1.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part1.yml new file mode 100644 index 0000000000..f7aaff2236 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part1.yml @@ -0,0 +1,19 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential2: + derived_from: tosca.datatypes.Root + properties: + protocol2: + type: string + required: false + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part2.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part2.yml new file mode 100644 index 0000000000..e1897d1f72 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentDerivedDataType_part2.yml @@ -0,0 +1,19 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential2: + derived_from: tosca.datatypes.Root + properties: + protocol2: + type: string + required: false + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Credential2 + properties: + protocol: + type: string + required: false \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part1.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part1.yml new file mode 100644 index 0000000000..d5784d1e61 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part1.yml @@ -0,0 +1,20 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +integer: + derived_from: tosca.datatypes.Root + +map: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + keys: + type: map + required: false + entry_schema: + type: integer diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part2.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part2.yml new file mode 100644 index 0000000000..4a5539dcaa --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentEntryType_part2.yml @@ -0,0 +1,20 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +integer: + derived_from: tosca.datatypes.Root + +map: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + keys: + type: map + required: false + entry_schema: + type: string diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part1.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part1.yml new file mode 100644 index 0000000000..70e4976b2f --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part1.yml @@ -0,0 +1,22 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +integer: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential2: + derived_from: tosca.datatypes.Root + properties: + protocol2: + type: string + required: false + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: integer + required: false diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part2.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part2.yml new file mode 100644 index 0000000000..71e26a7320 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithDifferentPropertyType_part2.yml @@ -0,0 +1,19 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential2: + derived_from: tosca.datatypes.Root + properties: + protocol2: + type: string + required: false + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part1.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part1.yml new file mode 100644 index 0000000000..71e26a7320 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part1.yml @@ -0,0 +1,19 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential2: + derived_from: tosca.datatypes.Root + properties: + protocol2: + type: string + required: false + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part2.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part2.yml new file mode 100644 index 0000000000..b4945fcd7f --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeUpdateWithExistingPropertyNameInAncestor_part2.yml @@ -0,0 +1,25 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +string: + derived_from: tosca.datatypes.Root + +integer: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential2: + derived_from: tosca.datatypes.Root + properties: + protocol2: + type: string + required: false + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Credential2 + properties: + protocol: + type: integer + required: false + protocol2: + type: integer + required: false diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypeWithPropertyTypeThisDataType.yml b/catalog-be/src/test/resources/types/datatypes/dataTypeWithPropertyTypeThisDataType.yml new file mode 100644 index 0000000000..c142b1d2c4 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypeWithPropertyTypeThisDataType.yml @@ -0,0 +1,9 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: mytypes.phonenumber diff --git a/catalog-be/src/test/resources/types/datatypes/dataTypes.yml b/catalog-be/src/test/resources/types/datatypes/dataTypes.yml new file mode 100644 index 0000000000..188c85bef3 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/dataTypes.yml @@ -0,0 +1,129 @@ +tosca.datatypes.Root: + description: The TOSCA root Data Type all other TOSCA base Data Types derive from + +integer: + derived_from: tosca.datatypes.Root + +string: + derived_from: tosca.datatypes.Root + +boolean: + derived_from: tosca.datatypes.Root + +float: + derived_from: tosca.datatypes.Root + +list: + derived_from: tosca.datatypes.Root + +map: + derived_from: tosca.datatypes.Root + +tosca.datatypes.Credential: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false + token_type: + type: string + default: password + token: + type: string + keys: + type: map + required: false + entry_schema: + type: string + user: + type: string + required: false + +tosca.datatypes.TimeInterval: + derived_from: tosca.datatypes.Root + properties: + start_time: + type: timestamp + required: true + end_time: + type: timestamp + required: true + +tosca.datatypes.network.NetworkInfo: + derived_from: tosca.datatypes.Root + properties: + network_name: + type: string + network_id: + type: string + addresses: + type: list + entry_schema: + type: string + +tosca.datatypes.network.PortInfo: + derived_from: tosca.datatypes.Root + properties: + port_name: + type: string + port_id: + type: string + network_id: + type: string + mac_address: + type: string + addresses: + type: list + entry_schema: + type: string + +tosca.datatypes.network.PortDef: + derived_from: integer + constraints: + - in_range: [ 1, 65535 ] + +tosca.datatypes.network.PortSpec: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: true + default: tcp + constraints: + - valid_values: [ udp, tcp, igmp ] + target: + type: tosca.datatypes.network.PortDef + target_range: + type: range + constraints: + - in_range: [ 1, 65535 ] + source: + type: tosca.datatypes.network.PortDef + source_range: + type: range + constraints: + - in_range: [ 1, 65535 ] + +tosca.datatypes.complexEntryTypeMapList: + derived_from: tosca.datatypes.Root + properties: + protocol: + type: string + required: false + token_type: + type: string + default: password + token: + type: string + keys: + type: map + required: false + entry_schema: + type: tosca.datatypes.Credential + addresses: + type: list + entry_schema: + type: tosca.datatypes.Credential + user: + type: string + required: false diff --git a/catalog-be/src/test/resources/types/datatypes/derived3levelDataType.yml b/catalog-be/src/test/resources/types/datatypes/derived3levelDataType.yml new file mode 100644 index 0000000000..f185167b80 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/derived3levelDataType.yml @@ -0,0 +1,37 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: integer + +# define a new datatype that derives from existing type and extends it +mytypes.phonenumber.extended: + derived_from: mytypes.phonenumber + description: custom phone number type that extends the basic phonenumber type + properties: + phone_description: + type: string + constraints: + - max_length: 128 + + + + +mytypes.phonenumber.extended.extended: + derived_from: mytypes.phonenumber.extended + description: custom phone number type that extends the basic phonenumber type + properties: + email: + type: string + constraints: + - max_length: 128 + complex1: + type: mytypes.phonenumber.extended + constraints: + - max_length: 128 + + \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/datatypes/derivedDataType.yml b/catalog-be/src/test/resources/types/datatypes/derivedDataType.yml new file mode 100644 index 0000000000..1c4ca88ff9 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/derivedDataType.yml @@ -0,0 +1,19 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: integer + +# define a new datatype that derives from existing type and extends it +mytypes.phonenumber.extended: + derived_from: mytypes.phonenumber + description: custom phone number type that extends the basic phonenumber type + properties: + phone_description: + type: string + constraints: + - max_length: 128 diff --git a/catalog-be/src/test/resources/types/datatypes/derivedDataTypeNoProperties.yml b/catalog-be/src/test/resources/types/datatypes/derivedDataTypeNoProperties.yml new file mode 100644 index 0000000000..2e6b35978e --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/derivedDataTypeNoProperties.yml @@ -0,0 +1,15 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: integer + +# define a new datatype that derives from existing type and extends it +mytypes.phonenumber.extended: + derived_from: mytypes.phonenumber + description: custom phone number type that extends the basic phonenumber type + diff --git a/catalog-be/src/test/resources/types/datatypes/derivedInvalidDataType.yml b/catalog-be/src/test/resources/types/datatypes/derivedInvalidDataType.yml new file mode 100644 index 0000000000..d76cc5f219 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/derivedInvalidDataType.yml @@ -0,0 +1,15 @@ +mytypes.phonenumber2: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: integer + +# define a new datatype that derives from existing type and extends it +mytypes.phonenumber.extended: + derived_from: mytypes.phonenumber3 + description: custom phone number type that extends the basic phonenumber type + diff --git a/catalog-be/src/test/resources/types/datatypes/emptyDataType.yml b/catalog-be/src/test/resources/types/datatypes/emptyDataType.yml new file mode 100644 index 0000000000..6a0318eca4 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/emptyDataType.yml @@ -0,0 +1,4 @@ +mytypes.phonenumber.empty: + description: my phone number datatype + properties: + diff --git a/catalog-be/src/test/resources/types/datatypes/emptyDataTypeNoPropertiesTag.yml b/catalog-be/src/test/resources/types/datatypes/emptyDataTypeNoPropertiesTag.yml new file mode 100644 index 0000000000..933c14f778 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/emptyDataTypeNoPropertiesTag.yml @@ -0,0 +1,3 @@ +mytypes.phonenumber.empty: + description: my phone number datatype + diff --git a/catalog-be/src/test/resources/types/datatypes/exitingPropertyAtAncestor.yml b/catalog-be/src/test/resources/types/datatypes/exitingPropertyAtAncestor.yml new file mode 100644 index 0000000000..0e46cc2a98 --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/exitingPropertyAtAncestor.yml @@ -0,0 +1,19 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: integer + +# define a new datatype that derives from existing type and extends it +mytypes.phonenumber.extended: + derived_from: mytypes.phonenumber + description: custom phone number type that extends the basic phonenumber type + properties: + areacode: + type: integer + + diff --git a/catalog-be/src/test/resources/types/datatypes/invalidDataType.yml b/catalog-be/src/test/resources/types/datatypes/invalidDataType.yml new file mode 100644 index 0000000000..d5ad5a93ba --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/invalidDataType.yml @@ -0,0 +1 @@ +mytypes.phonenumber.empty diff --git a/catalog-be/src/test/resources/types/datatypes/oneDataType.yml b/catalog-be/src/test/resources/types/datatypes/oneDataType.yml new file mode 100644 index 0000000000..114236fb3e --- /dev/null +++ b/catalog-be/src/test/resources/types/datatypes/oneDataType.yml @@ -0,0 +1,9 @@ +mytypes.phonenumber: + description: my phone number datatype + properties: + countrycode: + type: integer + areacode: + type: integer + number: + type: integer diff --git a/catalog-be/src/test/resources/types/interfaceLifecycleTypes.yml b/catalog-be/src/test/resources/types/interfaceLifecycleTypes.yml new file mode 100644 index 0000000000..1b67118934 --- /dev/null +++ b/catalog-be/src/test/resources/types/interfaceLifecycleTypes.yml @@ -0,0 +1,11 @@ +tosca.interfaces.node.lifecycle.Standard: + create: + description: Standard lifecycle create operation. + configure: + description: Standard lifecycle configure operation. + start: + description: Standard lifecycle start operation. + stop: + description: Standard lifecycle stop operation. + delete: + description: Standard lifecycle delete operation. \ No newline at end of file diff --git a/catalog-be/src/test/resources/types/interfaceLifecycleTypes.zip b/catalog-be/src/test/resources/types/interfaceLifecycleTypes.zip new file mode 100644 index 0000000000..9bcf93ab7d Binary files /dev/null and b/catalog-be/src/test/resources/types/interfaceLifecycleTypes.zip differ diff --git a/catalog-be/src/test/resources/valid_vf.csar b/catalog-be/src/test/resources/valid_vf.csar new file mode 100644 index 0000000000..01bf159071 Binary files /dev/null and b/catalog-be/src/test/resources/valid_vf.csar differ -- cgit 1.2.3-korg