diff options
author | Michael Lando <ml636r@att.com> | 2017-02-19 10:28:42 +0200 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2017-02-19 10:51:01 +0200 |
commit | 451a3400b76511393c62a444f588a4ed15f4a549 (patch) | |
tree | e4f5873a863d1d3e55618eab48b83262f874719d /catalog-model/src/test/java/org/openecomp | |
parent | 5abfe4e1fb5fae4bbd5fbc340519f52075aff3ff (diff) |
Initial OpenECOMP SDC commit
Change-Id: I0924d5a6ae9cdc161ae17c68d3689a30d10f407b
Signed-off-by: Michael Lando <ml636r@att.com>
Diffstat (limited to 'catalog-model/src/test/java/org/openecomp')
25 files changed, 12241 insertions, 0 deletions
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java new file mode 100644 index 0000000000..f18aa61b74 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ModelTestBase.java @@ -0,0 +1,46 @@ +/*- + * ============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.model; + +import org.openecomp.sdc.be.config.Configuration; +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 ModelTestBase { + + protected static ConfigurationManager configurationManager; + + public static void init() { + if (ConfigurationManager.getConfigurationManager() == null) { + String appConfigDir = "src/test/resources/config"; + ConfigurationSource configurationSource = new FSConfigurationSource( + ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + Configuration configuration = new Configuration(); + configuration.setTitanInMemoryGraph(true); + + configurationManager.setConfiguration(configuration); + } + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java new file mode 100644 index 0000000000..dd102e7ed5 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/JsonObjectTest.java @@ -0,0 +1,80 @@ +/*- + * ============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.model.operations; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.UploadArtifactInfo; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonObjectTest { + + private ObjectMapper mapper; + UploadResourceInfo inputObjectRef; + private final String INPUT_RESOURCE_STRING = "{ \"payloadData\" : \"My Test Object\", \"payloadName\" : \"TestName\", " + + " \"description\":\"my_description\",\"tags\":[\"tag1\"], " + + "\"artifactList\" : [ { \"artifactName\" : \"myArtifact0\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", " + + " \"artifactDescription\" : \"This is Description\", \"artifactData\" : null }, " + + "{ \"artifactName\" : \"myArtifact1\", \"artifactPath\" : \"scripts/\", \"artifactType\" : \"PUPPET\", \"artifactDescription\" : \"This is Description\", " + + " \"artifactData\" : null } ], \"contactId\" : null, \"name\" : null, \"resourceIconPath\" : null, \"vendorName\" : null, \"vendorRelease\" : null , \"resourceType\" : \"VFC\" }"; + + @Before + public void setup() { + mapper = new ObjectMapper(); + ArrayList<UploadArtifactInfo> artifactList = new ArrayList<UploadArtifactInfo>(); + for (int i = 0; i < 2; i++) { + UploadArtifactInfo artifactInfo = new UploadArtifactInfo("myArtifact" + i, "scripts/", + ArtifactTypeEnum.PUPPET, "This is Description"); + artifactList.add(artifactInfo); + } + ArrayList<String> tags = new ArrayList<>(); + tags.add("tag1"); + inputObjectRef = new UploadResourceInfo("My Test Object", "TestName", "my_description", null, tags, + artifactList); + + } + + @Test + public void testStringToUploadResourceInfo() throws JsonParseException, JsonMappingException, IOException { + UploadResourceInfo resourceObjectTest = mapper.readValue(INPUT_RESOURCE_STRING, UploadResourceInfo.class); + assertEquals(inputObjectRef, resourceObjectTest); + + } + + // @Test + public void testUploadResourceInfoToString() throws JsonParseException, JsonMappingException, IOException { + String refAsString = mapper.writeValueAsString(inputObjectRef); + String unFormattedString = refAsString.replace("\n", "").replace("\t", "").replace(" ", ""); + + assertEquals(unFormattedString, INPUT_RESOURCE_STRING.replace("\n", "").replace("\t", "").replace(" ", "")); + + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java new file mode 100644 index 0000000000..3e871f1fa0 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java @@ -0,0 +1,216 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.Point; +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.operations.api.IAdditionalInformationOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.exception.DeleteReferencedObjectException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.thinkaurelius.titan.core.TitanGraph; +//import com.tinkerpop.blueprints.Vertex; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class AdditionalInformationOperationTest extends ModelTestBase { + + private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + private static String USER_ID = "muuserid"; + private static String CATEGORY_NAME = "category/mycategory"; + + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "additional-information-operation") + private IAdditionalInformationOperation additionalInformationOperation; + + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); + + } + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + + } + + @Test + public void testDummy() { + + assertTrue(additionalInformationOperation != null); + + } + + private int getNumberOfVerticesOnGraph() { + Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + int i = 0; + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + i++; + } + + } + + titanDao.commit(); + + return i; + } + + @Test + public void testCreateAndDeleteResource() { + + int before = getNumberOfVerticesOnGraph(); + + Resource newResource = createResource(USER_ID, CATEGORY_NAME, "testCreateAndDeleteResource", "0.1", null, false, + true); + String resourceId = newResource.getUniqueId(); + + Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId); + assertTrue(deleteResource.isLeft()); + + int after = getNumberOfVerticesOnGraph(); + + assertEquals("check number of vertices not changed", before, after); + } + + private Resource buildResourceMetadata(String userId, String category, String resourceName, + String resourceVersion) { + + Resource resource = new Resource(); + resource.setName(resourceName); + resource.setVersion(resourceVersion); + ; + resource.setDescription("description 1"); + resource.setAbstract(false); + resource.setCreatorUserId(userId); + resource.setContactId("contactId@sdc.com"); + resource.setVendorName("vendor 1"); + resource.setVendorRelease("1.0.0"); + String[] categoryArr = category.split("/"); + resource.addCategory(categoryArr[0], categoryArr[1]); + resource.setIcon("images/my.png"); + // List<String> tags = new ArrayList<String>(); + // tags.add("TAG1"); + // tags.add("TAG2"); + // resource.setTags(tags); + return resource; + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + } + + public Resource createResource(String userId, String category, String resourceName, String resourceVersion, + String parentResourceName, boolean isAbstract, boolean isHighestVersion) { + + List<String> derivedFrom = new ArrayList<String>(); + if (parentResourceName != null) { + derivedFrom.add(parentResourceName); + } + Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion); + + resource.setAbstract(isAbstract); + resource.setHighestVersion(isHighestVersion); + + Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true); + + assertTrue(result.isLeft()); + Resource resultResource = result.left().value(); + + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + resultResource.getLifecycleState()); + + return resultResource; + + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java new file mode 100644 index 0000000000..0143e50dc7 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java @@ -0,0 +1,574 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +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.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.resources.data.ArtifactData; +import org.openecomp.sdc.be.resources.data.HeatParameterData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.UniqueIdData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ArtifactOperationTest extends ModelTestBase { + + private static final String ARTIFACT_NAME = "myHeatArtifact"; + + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "service-operation") + private ServiceOperation serviceOperation; + + @javax.annotation.Resource + private IGraphLockOperation graphLockOperation; + + @javax.annotation.Resource + private ArtifactOperation artifactOperation; + + @javax.annotation.Resource(name = "requirement-operation") + private RequirementOperation requirementOperation; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @javax.annotation.Resource(name = "capability-operation") + private CapabilityOperation capabilityOperation; + + @javax.annotation.Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + @javax.annotation.Resource(name = "component-instance-operation") + private ComponentInstanceOperation resourceInstanceOperation; + + @javax.annotation.Resource(name = "lifecycle-operation") + private LifecycleOperation lifecycleOperation; + + private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName()); + + private static String RESOURCE_ID = "resourceId"; + private static String RESOURCE_ID_2 = "resourceId2"; + + private static String USER_ID = "muserid"; + private static String CATEGORY_NAME = "category/mycategory"; + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + } + + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null); + } + +// @Test + public void testAddArtifactToServiceVersionAndUUIDNotNull() { + CategoryDefinition category = new CategoryDefinition(); + category.setName(CATEGORY_NAME); + + String serviceName = "servceTest2"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug("{}", serviceAfterSave); + String serviceId = serviceAfterSave.getUniqueId(); + + ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache"); + + assertEquals("add informational artifact version : " + artifactInfo.getArtifactVersion(), "1", + artifactInfo.getArtifactVersion()); + + assertNotNull("add informational artifact version : " + artifactInfo.getArtifactUUID(), + artifactInfo.getArtifactUUID()); + + Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts(); + for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { + String artifactId = entry.getValue().getUniqueId(); + String description = entry.getValue().getDescription(); + + artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); + } + service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + artifacts = service.left().value().getArtifacts(); + assertEquals(0, artifacts.size()); + + Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId); + + Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, + null, ArtifactData.class); + assertTrue(byCriteria.isRight()); + assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); + + serviceOperation.deleteService(serviceAfterSave.getUniqueId()); + + } + +// @Test + public void testUpdateArtifactToServiceVersionNotChanged() { + CategoryDefinition category = new CategoryDefinition(); + category.setName(CATEGORY_NAME); + String serviceName = "servceTest2"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug("{}", serviceAfterSave); + String serviceId = serviceAfterSave.getUniqueId(); + + ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache"); + + String version = artifactInfo.getArtifactVersion(); + String artUuid = artifactInfo.getArtifactUUID(); + assertEquals("add informational artifact version : " + version, "1", version); + + artifactInfo.setDescription("jghlsk new desfnjdh"); + + Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.updateArifactOnResource( + artifactInfo, serviceId, artifactInfo.getUniqueId(), NodeTypeEnum.Service, false); + String newVersion = artifact.left().value().getArtifactVersion(); + String newArtUuid = artifactInfo.getArtifactUUID(); + assertEquals("add informational artifact version : " + newVersion, newVersion, version); + assertEquals("add informational artifact uuid : " + newArtUuid, newArtUuid, artUuid); + + Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts(); + for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { + String artifactId = entry.getValue().getUniqueId(); + String description = entry.getValue().getDescription(); + + artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); + } + service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + artifacts = service.left().value().getArtifacts(); + assertEquals(0, artifacts.size()); + + Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId); + + Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, + null, ArtifactData.class); + assertTrue(byCriteria.isRight()); + assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); + + serviceOperation.deleteService(serviceAfterSave.getUniqueId()); + + } + + @Test + public void testCreateDeleteArtifactWithHeatParams() { + + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); + + List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters(); + assertNotNull(heatParameters); + assertTrue(heatParameters.size() == 1); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), + parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); + + Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource( + RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, true, false); + assertTrue(removeArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao.getNode(artifactData.getUniqueIdKey(), + artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterDelete.isRight()); + + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao + .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); + + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + } + + @Test + public void testUpdateArtifactWithHeatParams() { + + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); + + List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters(); + assertNotNull(heatParameters); + assertTrue(heatParameters.size() == 1); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), + parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); + + // update to artifact without params + ArtifactDefinition artifactNoParams = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); + artifactNoParams.setUniqueId(artifactWithHeat.getUniqueId()); + artifactNoParams.setArtifactType("HEAT"); + artifactNoParams.setArtifactVersion("2"); + artifactNoParams.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource( + artifactNoParams, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), + artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterUpdate.isLeft()); + ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); + assertTrue(artifactNoParams.getArtifactVersion() + .equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion())); + + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao + .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); + + artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, + true, false); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + } + + @Test + public void testUpdateArtifactMetadataWithHeatParams() { + + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); + + List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters(); + assertNotNull(heatParameters); + assertTrue(heatParameters.size() == 1); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), + parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); + + // update to artifact without params + artifactWithHeat.setArtifactVersion("2"); + artifactWithHeat.setArtifactChecksum(null); + artifactWithHeat.setPayloadData(null); + + Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource( + artifactWithHeat, RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either<ArtifactData, TitanOperationStatus> artifactAfterUpdate = titanDao.getNode(artifactData.getUniqueIdKey(), + artifactData.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterUpdate.isLeft()); + ArtifactData artifactAfterUpdateValue = artifactAfterUpdate.left().value(); + assertTrue(artifactWithHeat.getArtifactVersion() + .equals(artifactAfterUpdateValue.getArtifactDataDefinition().getArtifactVersion())); + + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao + .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource( + RESOURCE_ID_2, (String) artifactAfterUpdateValue.getUniqueId(), NodeTypeEnum.Resource, true, false); + removeArifact = artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), + NodeTypeEnum.Resource, true, false); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + + } + + @Test + public void updateHeatArtifactWithTwoResources() { + ArtifactDefinition artifactWithHeat = createResourceWithHeat(); + + ResourceMetadataData resource2 = createResource(RESOURCE_ID_2); + Map<String, Object> props = new HashMap<String, Object>(); + props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), ArtifactGroupTypeEnum.DEPLOYMENT.name()); + Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(resource2, + new ArtifactData(artifactWithHeat), GraphEdgeLabels.ARTIFACT_REF, props); + assertTrue(createRelation.isLeft()); + + List<HeatParameterDefinition> heatParameters = artifactWithHeat.getHeatParameters(); + assertNotNull(heatParameters); + assertTrue(heatParameters.size() == 1); + HeatParameterDefinition parameter = heatParameters.get(0); + HeatParameterData parameterData = new HeatParameterData(parameter); + Either<HeatParameterData, TitanOperationStatus> parameterNode = titanDao.getNode(parameterData.getUniqueIdKey(), + parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNode.isLeft()); + + ArtifactDefinition atifactToUpdate = new ArtifactDefinition(artifactWithHeat); + + // update to artifact without params + atifactToUpdate.setArtifactVersion("2"); + atifactToUpdate.setArtifactChecksum(null); + atifactToUpdate.setPayloadData(null); + + HeatParameterDefinition heatParamUpdate = new HeatParameterDefinition(parameter); + List<HeatParameterDefinition> heatParametersUpdated = new ArrayList<HeatParameterDefinition>(); + heatParamUpdate.setCurrentValue("55"); + heatParametersUpdated.add(heatParamUpdate); + atifactToUpdate.setHeatParameters(heatParametersUpdated); + + Either<ArtifactDefinition, StorageOperationStatus> updateArifact = artifactOperation.updateArifactOnResource( + atifactToUpdate, RESOURCE_ID_2, atifactToUpdate.getUniqueId(), NodeTypeEnum.Resource, false); + assertTrue(updateArifact.isLeft()); + + // verify old artifact and parameter still exist + ArtifactData artifactData = new ArtifactData(artifactWithHeat); + Either<ArtifactData, TitanOperationStatus> origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), + artifactData.getUniqueId(), ArtifactData.class); + assertTrue(origArtifact.isLeft()); + ArtifactData origArtifactData = origArtifact.left().value(); + assertTrue(artifactWithHeat.getArtifactVersion() + .equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion())); + + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterDelete = titanDao + .getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + // verify new artifact and new parameter + ArtifactDefinition artifactDefinitionUpdated = updateArifact.left().value(); + ArtifactData artifactDataUpdated = new ArtifactData(artifactDefinitionUpdated); + Either<ArtifactData, TitanOperationStatus> updatedArtifact = titanDao + .getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); + assertTrue(updatedArtifact.isLeft()); + ArtifactData updatedArtifactData = updatedArtifact.left().value(); + assertTrue(atifactToUpdate.getArtifactVersion() + .equals(updatedArtifactData.getArtifactDataDefinition().getArtifactVersion())); + assertFalse( + ((String) updatedArtifactData.getUniqueId()).equalsIgnoreCase((String) origArtifactData.getUniqueId())); + + List<HeatParameterDefinition> heatParametersAfterUpdate = artifactDefinitionUpdated.getHeatParameters(); + assertNotNull(heatParametersAfterUpdate); + assertTrue(heatParametersAfterUpdate.size() == 1); + HeatParameterDefinition UpdatedHeatParameter = heatParametersAfterUpdate.get(0); + assertFalse(UpdatedHeatParameter.getUniqueId().equalsIgnoreCase((String) parameterData.getUniqueId())); + Either<HeatParameterData, TitanOperationStatus> parameterNodeAfterUpdate = titanDao.getNode( + new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), UpdatedHeatParameter.getUniqueId(), + HeatParameterData.class); + assertTrue(parameterNodeAfterUpdate.isLeft()); + + // delete new artifact + Either<ArtifactDefinition, StorageOperationStatus> removeArifact = artifactOperation.removeArifactFromResource( + RESOURCE_ID_2, artifactDefinitionUpdated.getUniqueId(), NodeTypeEnum.Resource, true, false); + assertTrue(removeArifact.isLeft()); + + // verify old artifact and parameter still exist + origArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + assertTrue(origArtifact.isLeft()); + origArtifactData = origArtifact.left().value(); + assertTrue(artifactWithHeat.getArtifactVersion() + .equals(origArtifactData.getArtifactDataDefinition().getArtifactVersion())); + + parameterNodeAfterDelete = titanDao.getNode(parameterData.getUniqueIdKey(), parameterData.getUniqueId(), + HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isLeft()); + + // verify new artifact is deleted + Either<ArtifactData, TitanOperationStatus> artifactAfterDelete = titanDao + .getNode(artifactDataUpdated.getUniqueIdKey(), artifactDataUpdated.getUniqueId(), ArtifactData.class); + assertTrue(artifactAfterDelete.isRight()); + + parameterNodeAfterDelete = titanDao.getNode(new HeatParameterData(UpdatedHeatParameter).getUniqueIdKey(), + new HeatParameterData(UpdatedHeatParameter).getUniqueId(), HeatParameterData.class); + assertTrue(parameterNodeAfterDelete.isRight()); + + artifactOperation.removeArifactFromResource(RESOURCE_ID, artifactWithHeat.getUniqueId(), NodeTypeEnum.Resource, + true, false); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID), ResourceMetadataData.class); + titanDao.deleteNode(new UniqueIdData(NodeTypeEnum.Resource, RESOURCE_ID_2), ResourceMetadataData.class); + } + + private ArtifactDefinition createResourceWithHeat() { + ResourceMetadataData resource = createResource(RESOURCE_ID); + ArtifactDefinition artifactDefinition = createArtifactDefinition(USER_ID, RESOURCE_ID, ARTIFACT_NAME); + artifactDefinition.setArtifactType("HEAT"); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); + HeatParameterDefinition heatParam = new HeatParameterDefinition(); + heatParam.setCurrentValue("11"); + heatParam.setDefaultValue("22"); + heatParam.setDescription("desc"); + heatParam.setName("myParam"); + heatParam.setType("number"); + heatParams.add(heatParam); + artifactDefinition.setHeatParameters(heatParams); + + Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation + .addArifactToComponent(artifactDefinition, RESOURCE_ID, NodeTypeEnum.Resource, true, false); + assertTrue(artifact.isLeft()); + ArtifactDefinition artifactWithHeat = artifact.left().value(); + return artifactWithHeat; + } + + private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { + ArtifactDefinition artifactInfo = createArtifactDefinition(userId, serviceId, artifactName); + + Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation + .addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); + assertTrue(artifact.isLeft()); + return artifact.left().value(); + } + + private ArtifactDefinition createArtifactDefinition(String userId, String serviceId, String artifactName) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".sh"); + artifactInfo.setArtifactType("SHELL"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + 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(artifactName); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); + return artifactInfo; + } + + public Service createService(String userId, CategoryDefinition category, String serviceName, String serviceVersion, + boolean isHighestVersion) { + + Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); + + service.setHighestVersion(isHighestVersion); + + Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true); + + log.info(result.toString()); + assertTrue(result.isLeft()); + Service resultService = result.left().value(); + + // assertEquals("check resource unique id", + // UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion), + // resultService.getUniqueId()); + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + resultService.getLifecycleState()); + + return resultService; + } + + private Service buildServiceMetadata(String userId, CategoryDefinition category, String serviceName, + String serviceVersion) { + + Service service = new Service(); + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setDescription("description 1"); + + service.setCreatorUserId(userId); + service.setContactId("contactId@sdc.com"); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + service.setTags(tags); + return service; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + if (role != null && !role.isEmpty()) { + userData.setRole(role); + } else { + userData.setRole("ADMIN"); + } + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + public ResourceMetadataData createResource(String resourceName) { + + ResourceMetadataData serviceData1 = new ResourceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); + Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, + ResourceMetadataData.class); + + assertTrue("check resource created", createNode.isLeft()); + return createNode.left().value(); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java new file mode 100644 index 0000000000..5b8420d5dc --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperationTest.java @@ -0,0 +1,345 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +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.Map.Entry; + +import javax.annotation.Resource; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +// @TestExecutionListeners(listeners = { +// DependencyInjectionTestExecutionListener.class, +// DirtiesContextTestExecutionListener.class, +// TransactionalTestExecutionListener.class }) +public class CapabilityTypeOperationTest extends ModelTestBase { + + @Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + @BeforeClass + public static void setupBeforeClass() { + // ExternalConfiguration.setAppName("catalog-model"); + // String appConfigDir = "src/test/resources/config/catalog-model"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); + + // configurationManager = new ConfigurationManager( + // new ConfigurationSource() { + // + // @Override + // public <T> T getAndWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // return null; + // } + // + // @Override + // public <T> void addWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // + // } + // }); + // + // Configuration configuration = new Configuration(); + // configuration.setTitanInMemoryGraph(true); + // + // configurationManager.setConfiguration(configuration); + ModelTestBase.init(); + + } + + @Test + public void testDummy() { + + assertTrue(capabilityTypeOperation != null); + + } + + @Test + public void testAddCapabilityType() { + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType("tosca.capabilities.Container1"); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition, true); + assertEquals("check capability type added", true, addCapabilityType1.isLeft()); + + CapabilityTypeDefinition capabilityTypeAdded = addCapabilityType1.left().value(); + compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded); + + Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeByUid = capabilityTypeOperation + .getCapabilityTypeByUid(capabilityTypeAdded.getUniqueId()); + compareBetweenCreatedToSent(capabilityTypeByUid.left().value(), capabilityTypeDefinition); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType2 = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition, true); + assertEquals("check capability type failed", true, addCapabilityType2.isRight()); + assertEquals("check returned error", StorageOperationStatus.SCHEMA_VIOLATION, + addCapabilityType2.right().value()); + + } + + @Test + public void testAddDerviedCapabilityType() { + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType("tosca.capabilities.Container2"); + capabilityTypeDefinition.setDerivedFrom("derivedFrom"); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition, true); + // assertEquals("check capability type parent not exist", + // StorageOperationStatus.INVALID_ID, + // addCapabilityType1.right().value()); + // TODO: esofer change to INVALID_ID + assertEquals("check capability type parent not exist", StorageOperationStatus.INVALID_ID, + addCapabilityType1.right().value()); + } + + public CapabilityTypeDefinition createCapability(String capabilityTypeName) { + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType(capabilityTypeName); + + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + + String propName1 = "disk_size"; + String propName2 = "num_cpus"; + + PropertyDefinition property1 = buildProperty1(); + + properties.put(propName1, property1); + + PropertyDefinition property2 = buildProperty2(); + + properties.put(propName2, property2); + + capabilityTypeDefinition.setProperties(properties); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition, true); + + CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); + Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation + .getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId(), true); + assertEquals("check capability type fetched", true, capabilityType.isLeft()); + CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); + + Map<String, PropertyDefinition> fetchedProps = fetchedCTD.getProperties(); + + compareProperties(fetchedProps, properties); + + return fetchedCTD; + + } + + @Test + public void testAddCapabilityTypeWithProperties() { + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType("tosca.capabilities.Container3"); + + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + + String propName1 = "disk_size"; + String propName2 = "num_cpus"; + + PropertyDefinition property1 = buildProperty1(); + + properties.put(propName1, property1); + + PropertyDefinition property2 = buildProperty2(); + + properties.put(propName2, property2); + + capabilityTypeDefinition.setProperties(properties); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition, true); + + CapabilityTypeDefinition capabilityTypeDefinitionCreated = addCapabilityType1.left().value(); + Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation + .getCapabilityType(capabilityTypeDefinitionCreated.getUniqueId()); + assertEquals("check capability type fetched", true, capabilityType.isLeft()); + CapabilityTypeDefinition fetchedCTD = capabilityType.left().value(); + + Map<String, PropertyDefinition> fetchedProps = fetchedCTD.getProperties(); + + compareProperties(fetchedProps, properties); + } + + private void compareProperties(Map<String, PropertyDefinition> first, Map<String, PropertyDefinition> second) { + + assertTrue("check properties are full or empty", + ((first == null && second == null) || (first != null && second != null))); + if (first != null) { + assertEquals("check properties size", first.size(), second.size()); + + for (Entry<String, PropertyDefinition> entry : first.entrySet()) { + + String propName = entry.getKey(); + PropertyDefinition secondPD = second.get(propName); + assertNotNull("Cannot find property " + propName + " in " + second, secondPD); + + PropertyDefinition firstPD = entry.getValue(); + + comparePropertyDefinition(firstPD, secondPD); + } + + } + + } + + @Test + public void testGetCapabilityTypeNotFound() { + + Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityType = capabilityTypeOperation + .getCapabilityType("not_exists"); + assertEquals("check not found is returned", StorageOperationStatus.NOT_FOUND, capabilityType.right().value()); + + } + + private void comparePropertyDefinition(PropertyDefinition first, PropertyDefinition second) { + + assertTrue("check objects are full or empty", + ((first == null && second == null) || (first != null && second != null))); + if (first != null) { + assertTrue("check property default value", compareValue(first.getDefaultValue(), second.getDefaultValue())); + assertTrue("check property description", compareValue(first.getDescription(), second.getDescription())); + assertTrue("check property type", compareValue(first.getType(), second.getType())); + compareList(first.getConstraints(), second.getConstraints()); + } + + } + + private void compareList(List<PropertyConstraint> first, List<PropertyConstraint> second) { + + assertTrue("check lists are full or empty", + ((first == null && second == null) || (first != null && second != null))); + if (first != null) { + assertEquals("check list size", first.size(), second.size()); + } + } + + private PropertyDefinition buildProperty2() { + PropertyDefinition property2 = new PropertyDefinition(); + property2.setDefaultValue("2"); + property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); + property2.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints3 = new ArrayList<PropertyConstraint>(); + List<String> range = new ArrayList<String>(); + range.add("1"); + range.add("4"); + + InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); + constraints3.add(propertyConstraint3); + // property2.setConstraints(constraints3); + property2.setConstraints(constraints3); + return property2; + } + + private PropertyDefinition buildProperty1() { + PropertyDefinition property1 = new PropertyDefinition(); + property1.setDefaultValue("10"); + property1.setDescription( + "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property1.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + constraints.add(propertyConstraint1); + + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + constraints.add(propertyConstraint2); + + property1.setConstraints(constraints); + return property1; + } + + private void compareBetweenCreatedToSent(CapabilityTypeDefinition x, CapabilityTypeDefinition y) { + + assertTrue(compareValue(x.getDerivedFrom(), y.getDerivedFrom())); + assertTrue(compareValue(x.getType(), y.getType())); + assertTrue(compareValue(x.getDescription(), y.getDescription())); + + } + + public boolean compareValue(String first, String second) { + + if (first == null && second == null) { + return true; + } + if (first != null) { + return first.equals(second); + } else { + return false; + } + } + + public void setOperations(TitanGenericDao titanDao, CapabilityTypeOperation capabilityTypeOperation) { + this.titanDao = titanDao; + this.capabilityTypeOperation = capabilityTypeOperation; + + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java new file mode 100644 index 0000000000..2dcb1ee72e --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java @@ -0,0 +1,543 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; + +import javax.annotation.Resource; + +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; +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.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.operations.impl.ServiceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.operations.impl.util.ResourceCreationUtils; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.CapabilityData; +import org.openecomp.sdc.be.resources.data.CapabilityInstData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ComponentInstanceOperationSpringTest extends ModelTestBase { + private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperationSpringTest.class.getName()); + @Resource(name = "component-instance-operation") + private ComponentInstanceOperation componentInstanceOperation; + + @Resource(name = "component-instance-operation") + private ComponentInstanceOperation resourceInstanceOperation; + + @Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + @Resource(name = "capability-operation") + public CapabilityOperation capabilityOperation; + + @Resource(name = "service-operation") + private ServiceOperation serviceOperation; + + @Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @Resource(name = "lifecycle-operation") + private LifecycleOperation lifecycleOperation; + + TitanGenericDao titanGenericDao; + + private static String CATEGORY_NAME = "category/mycategory"; + + User rfcUser; + + @BeforeClass + public static void setupBeforeClass() { + ModelTestBase.init(); + + } + + @Before + public void cleanUp() { + titanGenericDao = componentInstanceOperation.titanGenericDao; + Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + titanGenericDao.commit(); + deleteAndCreateCategory(CATEGORY_NAME); + UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", + ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); + rfcUser = convertUserDataToUser(modifierData); + } + + @Test + public void testAddCapabilityPropertyValuesToResourceInstance() { + String rootName = "Root123"; + org.openecomp.sdc.be.model.Resource rootResource = createResource(rfcUser.getUserId(), CATEGORY_NAME, rootName, + "1.0", null, false, true); + + // certification request + Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false); + assertTrue(requestCertificationResult.isLeft()); + + org.openecomp.sdc.be.model.Resource resultResource = (org.openecomp.sdc.be.model.Resource) requestCertificationResult + .left().value(); + + // start certification + Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> startCertificationResult = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Resource, resultResource, rfcUser, rfcUser, false); + assertEquals(true, startCertificationResult.isLeft()); + + Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> certifiedResourceRes = lifecycleOperation + .certifyComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false); + assertTrue(certifiedResourceRes.isLeft()); + + CapabilityTypeDefinition capabilityType = buildCapabilityType(); + Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityTypeRes = capabilityTypeOperation + .addCapabilityType(capabilityType); + assertTrue(capabilityTypeRes.isLeft()); + + CapabilityData capData = FactoryUtils.createCapabilityData(); + CapabilityDefinition capabilityDefinitionRoot = FactoryUtils + .convertCapabilityDataToCapabilityDefinitionRoot(capData); + + Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRootRes = capabilityOperation.addCapability( + (String) certifiedResourceRes.left().value().getUniqueId(), capabilityDefinitionRoot.getName(), + capabilityDefinitionRoot); + assertTrue(addCapabilityRootRes.isLeft()); + + String resourceName = "tosca.nodes.Apache.2.0"; + + CapabilityDefinition capabilityDefinition = FactoryUtils + .convertCapabilityDataToCapabilityDefinitionAddProperties(capData); + org.openecomp.sdc.be.model.Resource resource = createResource(rfcUser.getUserId(), CATEGORY_NAME, resourceName, + "0.1", rootName, false, true); + + Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation + .addCapability((String) resource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition); + assertTrue(addCapabilityRes.isLeft()); + List<ComponentInstanceProperty> properties = addCapabilityRes.left().value().getProperties(); + assertTrue(properties.size() == 2); + + Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> clonedResourceRes = resourceOperation + .cloneComponent(resource, "0.2", false); + assertTrue(clonedResourceRes.isLeft()); + org.openecomp.sdc.be.model.Resource clonedResource = clonedResourceRes.left().value(); + + ComponentInstance instance = buildResourceInstance(clonedResource.getUniqueId(), "1", "tosca.nodes.Apache"); + + Service origService = createService(rfcUser.getUserId(), CATEGORY_NAME, "my-service", "1.0", true); + Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), + false); + assertTrue(service2.isLeft()); + origService = service2.left().value(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + String json = prettyGson.toJson(origService); + log.debug(json); + + Service fullService = origService; + + Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation + .addComponentInstanceToContainerComponent((String) origService.getUniqueId(), NodeTypeEnum.Service, "1", + true, instance, NodeTypeEnum.Resource, false); + assertTrue(status.isLeft()); + + ComponentInstance resourceInstance = status.left().value(); + CapabilityDefinition capability = addCapabilityRes.left().value(); + capability.setName(capabilityDefinition.getName()); + List<ComponentInstanceProperty> propertyValues = FactoryUtils.createComponentInstancePropertyList(); + capability.setProperties(propertyValues); + + Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCPVsToRiRes = componentInstanceOperation + .addCapabilityPropertyValuesToResourceInstance(resourceInstance.getUniqueId(), capability, true); + assertTrue(addCPVsToRiRes.isLeft()); + + Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", + false); + assertTrue(createService.isLeft()); + Map<String, List<CapabilityDefinition>> capabilitiesMap = createService.left().value().getCapabilities(); + assertTrue(capabilitiesMap != null && capabilitiesMap.size() == 1); + Map<String, CapabilityDefinition> capabilities = capabilitiesMap.values().iterator().next().stream() + .collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity())); + assertTrue(capabilities.containsKey("Cap1") && capabilities.containsKey("Cap2")); + + // String outputFile = exportGraphMl(); + + } + + public String exportGraphMl() { + String result = null; + String outputFile = "C:\\Output" + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + TitanGraph graph = titanGenericDao.getGraph().left().value(); + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + graph.tx().commit(); + } catch (Exception e) { + graph.tx().rollback(); + e.printStackTrace(); + } + return result; + + } + + private CapabilityTypeDefinition buildCapabilityType() { + CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); + Map<String, PropertyDefinition> properties = new HashMap(); + + capabilityType.setType(Constants.DEFAULT_CAPABILITY_TYPE); + capabilityType.setProperties(properties); + + PropertyDefinition host = new PropertyDefinition(); + host.setUniqueId(UUID.randomUUID().toString()); + host.setName("host"); + host.setDefaultValue("captypehost"); + host.setType("string"); + + host.setSchema(new SchemaDefinition()); + host.getSchema().setProperty(new PropertyDataDefinition()); + host.getSchema().getProperty().setType("string"); + + PropertyDefinition port = new PropertyDefinition(); + port.setName("port"); + port.setDefaultValue("captypeport"); + port.setUniqueId(UUID.randomUUID().toString()); + port.setType("string"); + + port.setSchema(new SchemaDefinition()); + port.getSchema().setProperty(new PropertyDataDefinition()); + port.getSchema().getProperty().setType("string"); + + PropertyDefinition rootproperty = new PropertyDefinition(); + rootproperty.setName("captypeproperty"); + rootproperty.setDefaultValue("captypevalue"); + rootproperty.setUniqueId(UUID.randomUUID().toString()); + rootproperty.setType("string"); + + rootproperty.setSchema(new SchemaDefinition()); + rootproperty.getSchema().setProperty(new PropertyDataDefinition()); + rootproperty.getSchema().getProperty().setType("string"); + + properties.put("host", host); + properties.put("port", port); + properties.put("captypeproperty", rootproperty); + return capabilityType; + } + + private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) { + CapabilityInstData capabilityInstance = new CapabilityInstData(); + Long creationTime = System.currentTimeMillis(); + String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName()); + capabilityInstance.setCreationTime(creationTime); + capabilityInstance.setModificationTime(creationTime); + capabilityInstance.setUniqueId(uniqueId); + return capabilityInstance; + } + + private ComponentInstance buildResourceInstance(String respurceUid, String instanceNumber, String name) { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(name); + resourceInstance.setDescription("desc1"); + resourceInstance.setPosX("20"); + resourceInstance.setPosY("40"); + resourceInstance.setComponentUid(respurceUid); + resourceInstance.setCreationTime(System.currentTimeMillis()); + resourceInstance.setModificationTime(System.currentTimeMillis()); + resourceInstance.setNormalizedName(ResourceInstanceOperationTest.normaliseComponentInstanceName(name)); + return resourceInstance; + } + + public ResourceMetadataData createResource(String resourceName, TitanGenericDao titanGenericDao) { + ResourceMetadataData serviceData1 = new ResourceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); + Either<ResourceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1, + ResourceMetadataData.class); + assertTrue("check service created", createNode.isLeft()); + return createNode.left().value(); + } + + public ServiceMetadataData createServiceMetadataData(String serviceName, TitanGenericDao titanGenericDao) { + ServiceMetadataData serviceData1 = new ServiceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(serviceName); + Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1, + ServiceMetadataData.class); + assertTrue("check service created", createNode.isLeft()); + return createNode.left().value(); + } + + public Service createService(String userId, String category, String serviceName, String serviceVersion, + boolean isHighestVersion) { + Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); + service.setHighestVersion(isHighestVersion); + Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true); + assertTrue(result.isLeft()); + Service resultService = result.left().value(); + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + resultService.getLifecycleState()); + return resultService; + } + + private Service buildServiceMetadata(String userId, String category, String serviceName, String serviceVersion) { + Service service = new Service(); + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setDescription("description 1"); + service.setCreatorUserId(userId); + service.setContactId("contactId@sdc.com"); + CategoryDefinition categoryDef = new CategoryDefinition(); + categoryDef.setName(category); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(categoryDef); + service.setCategories(categories); + service.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + service.setTags(tags); + return service; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateServiceCategory(category, titanGenericDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanGenericDao); + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + if (role != null && !role.isEmpty()) { + userData.setRole(role); + } else { + userData.setRole("ADMIN"); + } + titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanGenericDao.createNode(userData, UserData.class); + titanGenericDao.commit(); + return userData; + } + + public org.openecomp.sdc.be.model.Resource createResource(String userId, String category, String resourceName, + String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) { + + String propName1 = "disk_size"; + String propName2 = "num_cpus"; + + List<String> derivedFrom = new ArrayList<String>(); + if (parentResourceName != null) { + derivedFrom.add(parentResourceName); + } + org.openecomp.sdc.be.model.Resource resource = buildResourceMetadata(userId, category, resourceName, + resourceVersion); + + resource.setAbstract(isAbstract); + resource.setHighestVersion(isHighestVersion); + + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + + PropertyDefinition property1 = new PropertyDefinition(); + property1.setDefaultValue("10"); + property1.setDescription( + "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property1.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + log.debug("{}", propertyConstraint1); + + constraints.add(propertyConstraint1); + + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + constraints.add(propertyConstraint2); + + property1.setConstraints(constraints); + + properties.put(propName1, property1); + + PropertyDefinition property2 = new PropertyDefinition(); + property2.setDefaultValue("2"); + property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); + property2.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints3 = new ArrayList<PropertyConstraint>(); + List<String> range = new ArrayList<String>(); + range.add("1"); + range.add("4"); + + InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); + constraints3.add(propertyConstraint3); + property2.setConstraints(constraints3); + properties.put(propName2, property2); + + resource.setDerivedFrom(derivedFrom); + + resource.setProperties(convertMapToList(properties)); + + Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> result = resourceOperation + .createResource(resource, true); + + assertTrue(result.isLeft()); + org.openecomp.sdc.be.model.Resource resultResource = result.left().value(); + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + resultResource.getLifecycleState()); + + String resourceId = resultResource.getUniqueId(); + + Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, + resourceId); + + assertTrue(either.isLeft()); + PropertyDefinition propertyDefinition = either.left().value(); + assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue()); + assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription()); + assertEquals("check property type", property1.getType(), propertyDefinition.getType()); + assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId()); + assertEquals("check property consitraints size", property1.getConstraints().size(), + propertyDefinition.getConstraints().size()); + + return resultResource; + } + + private org.openecomp.sdc.be.model.Resource buildResourceMetadata(String userId, String category, + String resourceName, String resourceVersion) { + + org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); + resource.setName(resourceName); + resource.setVersion(resourceVersion); + ; + resource.setDescription("description 1"); + resource.setAbstract(false); + resource.setCreatorUserId(userId); + resource.setContactId("contactId@sdc.com"); + resource.setVendorName("vendor 1"); + resource.setVendorRelease("1.0.0"); + resource.setToscaResourceName(resourceName); + String[] categoryArr = category.split("/"); + resource.addCategory(categoryArr[0], categoryArr[1]); + resource.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + resource.setTags(tags); + return resource; + } + + public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) { + if (properties == null) { + return null; + } + + List<PropertyDefinition> definitions = new ArrayList<>(); + for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { + String name = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + propertyDefinition.setName(name); + definitions.add(propertyDefinition); + } + + return definitions; + } + + private User convertUserDataToUser(UserData modifierData) { + User modifier = new User(); + modifier.setUserId(modifierData.getUserId()); + modifier.setEmail(modifierData.getEmail()); + modifier.setFirstName(modifierData.getFirstName()); + modifier.setLastName(modifierData.getLastName()); + modifier.setRole(modifierData.getRole()); + return modifier; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java new file mode 100644 index 0000000000..e77c9f0291 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java @@ -0,0 +1,136 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.lang3.tuple.ImmutablePair; +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.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.CapabilityData; +import org.openecomp.sdc.be.resources.data.CapabilityInstData; +import org.openecomp.sdc.be.resources.data.RequirementData; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; + +import fj.data.Either; + +public class ComponentInstanceOperationTest { + + @InjectMocks + ComponentInstanceOperation componentInstanceOperation = new ComponentInstanceOperation(); + @InjectMocks + private TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + + @Before + public void beforeTest() { + Mockito.reset(titanGenericDao); + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGetCapabilities() { + + ComponentInstance ri = FactoryUtils.createResourceInstance(); + CapabilityData capData = FactoryUtils.createCapabilityData(); + Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue( + capData); + + Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), + Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())) + .thenReturn(childNodesReturned); + + // ImmutablePair<ComponentInstance, List<ImmutablePair<CapabilityData, + // GraphEdge>>> instanceAndCapabilities = + // componentInstanceOperation.getCapabilities(ri, + // NodeTypeEnum.Resource); + + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation + .getCapabilities(ri, NodeTypeEnum.Resource); + + // assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId())); + assertTrue(instanceAndCapabilities.left().value().size() == 1); + assertTrue(instanceAndCapabilities.left().value().get(0).left.getUniqueId().equals(capData.getUniqueId())); + + } + + @Test + public void testGetRequirements() { + ComponentInstance ri = FactoryUtils.createResourceInstance(); + RequirementData reqData = FactoryUtils.createRequirementData(); + Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue( + reqData); + + Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), + Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())) + .thenReturn(childNodesReturned); + + // ImmutablePair<ComponentInstance, List<ImmutablePair<RequirementData, + // GraphEdge>>> instanceAndCapabilities = + // componentInstanceOperation.getRequirements(ri, + // NodeTypeEnum.Resource); + Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation + .getRequirements(ri, NodeTypeEnum.Resource); + + // assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId())); + // assertTrue(instanceAndCapabilities.right.size() == 1); + // assertTrue(instanceAndCapabilities.right.get(0).left.getUniqueId().equals(reqData.getUniqueId())); + + assertTrue(instanceAndCapabilities.left().value().size() == 1); + assertTrue(instanceAndCapabilities.left().value().get(0).left.getUniqueId().equals(reqData.getUniqueId())); + + } + + private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) { + CapabilityInstData capabilityInstance = new CapabilityInstData(); + Long creationTime = System.currentTimeMillis(); + String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName()); + + capabilityInstance.setCreationTime(creationTime); + capabilityInstance.setModificationTime(creationTime); + capabilityInstance.setUniqueId(uniqueId); + + return capabilityInstance; + } + + private Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> prepareChildNodeRetValue( + GraphNode data) { + ImmutablePair<GraphNode, GraphEdge> pair = new ImmutablePair<>(data, FactoryUtils.createGraphEdge()); + List<ImmutablePair<GraphNode, GraphEdge>> retList = new ArrayList<>(); + retList.add(pair); + return Either.left(retList); + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java new file mode 100644 index 0000000000..14018d31f9 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java @@ -0,0 +1,395 @@ +/*- + * ============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.model.operations.impl; + +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 java.util.Map.Entry; +import java.util.stream.Collectors; + +import com.thinkaurelius.titan.core.TitanTransaction; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +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.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +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.operations.api.ICapabilityOperation; +import org.openecomp.sdc.be.model.operations.api.IRequirementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.CapabilityData; +import org.openecomp.sdc.be.resources.data.CapabilityInstData; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.be.resources.data.PropertyData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; +import org.openecomp.sdc.be.resources.data.RequirementData; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; + +import fj.data.Either; + +public class ComponentOperationTest { + @InjectMocks + ComponentOperation compOperation = getAnnonimusImpl(); + + ComponentInstanceOperation componentInstanceOperation = Mockito.mock(ComponentInstanceOperation.class); + TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + ICapabilityOperation capabilityOperation = Mockito.mock(ICapabilityOperation.class); + IRequirementOperation requirementOperation = Mockito.mock(IRequirementOperation.class); + + @Before + public void beforeTest() { + Mockito.reset(componentInstanceOperation, requirementOperation, capabilityOperation); + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGetCapabilities() { + Resource vf = FactoryUtils.createVF(); + ComponentInstance ri = FactoryUtils.createResourceInstance(); + CapabilityData capData = FactoryUtils.createCapabilityData(); + + FactoryUtils.addComponentInstanceToVF(vf, ri); + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList = prepareCompOperationReturnValue( + ri, capData); + + prepareMocksForCapabilitiesMethods(ri, capDataList); + + Map<String, List<CapabilityDefinition>> capabilities = compOperation + .getCapabilities(vf, NodeTypeEnum.Resource, false).left().value(); + assertTrue(capabilities.size() == 1); + Entry<String, List<CapabilityDefinition>> entry = capabilities.entrySet().iterator().next(); + assertTrue(entry.getKey().equals(capData.getType())); + assertTrue(entry.getValue().size() == 1); + assertTrue(entry.getValue().get(0).getUniqueId().equals(capData.getUniqueId())); + } + + @Test + public void testGetRequirments() { + Resource vf = FactoryUtils.createVF(); + ComponentInstance ri = FactoryUtils.createResourceInstance(); + + RequirementData reqData = FactoryUtils.createRequirementData(); + + FactoryUtils.addComponentInstanceToVF(vf, ri); + + Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList = prepareCompOperationReturnValue( + ri, reqData); + + prepareMocksForRequirmenetsMethods(ri, reqDataEdgeList); + + Map<String, List<RequirementDefinition>> requirements = compOperation + .getRequirements(vf, NodeTypeEnum.Resource, false).left().value(); + assertTrue(requirements.size() == 1); + Entry<String, List<RequirementDefinition>> entry = requirements.entrySet().iterator().next(); + assertTrue(entry.getKey().equals(FactoryUtils.Constants.DEFAULT_CAPABILITY_TYPE)); + assertTrue(entry.getValue().size() == 1); + assertTrue(entry.getValue().get(0).getUniqueId().equals(reqData.getUniqueId())); + } + + private void prepareMocksForRequirmenetsMethods(ComponentInstance ri, + Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList) { + + when(componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource)).thenReturn(reqDataEdgeList); + when(requirementOperation.getRequirement(Mockito.anyString())).then(createReqDefAnswer()); + } + + private void prepareMocksForCapabilitiesMethods(ComponentInstance ri, + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList) { + when(componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource)).thenReturn(capDataList); + when(capabilityOperation.getCapabilityByCapabilityData(Mockito.any(CapabilityData.class))) + .then(createCapDefByDataAnswer()); + List<ImmutablePair<CapabilityInstData, GraphEdge>> capInstList = new ArrayList<>(); + CapabilityInstData curCapabilityInst = FactoryUtils.createCapabilityInstData(); + GraphEdge edge = new GraphEdge(); + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), + capDataList.left().value().get(0).getLeft().getUniqueId()); + edge.setProperties(properties); + ImmutablePair<CapabilityInstData, GraphEdge> pair = new ImmutablePair<CapabilityInstData, GraphEdge>( + curCapabilityInst, edge); + capInstList.add(pair); + when(titanGenericDao.getChildrenNodes( + UniqueIdBuilder.getKeyByNodeType( + NodeTypeEnum.getByNameIgnoreCase(ri.getOriginType().getInstanceType().trim())), + ri.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, + CapabilityInstData.class)).thenReturn(Either.left(capInstList)); + + when(titanGenericDao.getChild( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), + curCapabilityInst.getUniqueId(), GraphEdgeLabels.INSTANCE_OF, NodeTypeEnum.Capability, + CapabilityData.class)).thenReturn(Either.left(capDataList.left().value().get(0))); + + PropertyValueData propertyValueData = FactoryUtils.createPropertyData(); + ImmutablePair<PropertyValueData, GraphEdge> propPair = new ImmutablePair<PropertyValueData, GraphEdge>( + propertyValueData, null); + List<ImmutablePair<PropertyValueData, GraphEdge>> propPairList = new ArrayList<>(); + propPairList.add(propPair); + when(titanGenericDao.getChildrenNodes( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), + curCapabilityInst.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, + PropertyValueData.class)).thenReturn(Either.left(propPairList)); + + CapabilityDefinition capDef = FactoryUtils + .convertCapabilityDataToCapabilityDefinitionAddProperties(capDataList.left().value().get(0).getLeft()); + List<PropertyDefinition> propDefList = capDef.getProperties().stream().filter(p -> p.getName().equals("host")) + .collect(Collectors.toList()); + PropertyDefinition propDef = propDefList.get(0); + PropertyData propData = FactoryUtils.convertCapabilityDefinitionToCapabilityData(propDef); + + ImmutablePair<PropertyData, GraphEdge> defPropPair = new ImmutablePair<PropertyData, GraphEdge>(propData, edge); + + when(titanGenericDao.getChild( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(propertyValueData.getLabel())), + propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, + PropertyData.class)).thenReturn(Either.left(defPropPair)); + List<CapabilityDefinition> capDefList = new ArrayList<>(); + capDefList.add(capDef); + when(componentInstanceOperation.updateCapDefPropertyValues(Mockito.any(ComponentInstance.class), + Mockito.any(List.class))).thenReturn(Either.left(capDefList)); + } + + private <Data> Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> prepareCompOperationReturnValue( + ComponentInstance ri, Data data) { + ImmutablePair<Data, GraphEdge> dataEdgePair = new ImmutablePair<>(data, new GraphEdge()); + List<ImmutablePair<Data, GraphEdge>> dataEdgeList = new ArrayList<>(); + dataEdgeList.add(dataEdgePair); + return Either.left(dataEdgeList); + } + + private Answer<Either<RequirementDefinition, TitanOperationStatus>> createReqDefAnswer() { + return new Answer<Either<RequirementDefinition, TitanOperationStatus>>() { + + @Override + public Either<RequirementDefinition, TitanOperationStatus> answer(InvocationOnMock invocation) + throws Throwable { + String reqDataId = (String) invocation.getArguments()[0]; + return Either.left(FactoryUtils.convertRequirementDataIDToRequirementDefinition(reqDataId)); + } + }; + } + + private Answer<Either<CapabilityDefinition, TitanOperationStatus>> createCapDefByDataAnswer() { + return new Answer<Either<CapabilityDefinition, TitanOperationStatus>>() { + + @Override + public Either<CapabilityDefinition, TitanOperationStatus> answer(InvocationOnMock invocation) + throws Throwable { + CapabilityData capData = (CapabilityData) invocation.getArguments()[0]; + return Either.left(FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData)); + } + }; + } + + private ComponentOperation getAnnonimusImpl() { + return new ComponentOperation() { + + @Override + protected StorageOperationStatus validateCategories(Component currentComponent, Component component, + ComponentMetadataData componentData, NodeTypeEnum type) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected <T extends Component> StorageOperationStatus updateDerived(Component component, + Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, + boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected ComponentMetadataData getMetaDataFromComponent(Component component) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, + Map<String, Object> additionalParams, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + // @Override + // public <T> Either<T, StorageOperationStatus> + // getComponent_tx(String id, boolean inTransaction) { + // // TODO Auto-generated method stub + // return null; + // } + + @Override + public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, + boolean recursively, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, + boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Component getDefaultComponent() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isComponentExist(String componentId) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { + // TODO Auto-generated method stub + return null; + } + + @Override + TitanOperationStatus setComponentCategoriesFromGraph(Component component) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String componentName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, + boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion() { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, + LifecycleStateEnum targetLifecycle, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Either<T, StorageOperationStatus> getComponent(String id, + ComponentParametersView componentParametersView, boolean inTrasnaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, + boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, + boolean inTransaction, ComponentParametersView filterParametersView) { + // TODO Auto-generated method stub + return null; + } + + }; + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java new file mode 100644 index 0000000000..a529074db6 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ElementOperationTest.java @@ -0,0 +1,109 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactType; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.impl.ElementOperation; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ElementOperationTest extends ModelTestBase { + + @javax.annotation.Resource(name = "element-operation") + private ElementOperation elementOperation; + + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + private static String CATEGORY = "category"; + private static String SUBCATEGORY = "subcategory"; + + @BeforeClass + public static void setupBeforeClass() { + // ExternalConfiguration.setAppName("catalog-model"); + // String appConfigDir = "src/test/resources/config/catalog-model"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); + + ModelTestBase.init(); + + } + + @Test + public void testGetArtifactsTypes() { + + List<String> artifactTypesCfg = new ArrayList<String>(); + artifactTypesCfg.add("type1"); + artifactTypesCfg.add("type2"); + artifactTypesCfg.add("type3"); + artifactTypesCfg.add("type4"); + configurationManager.getConfiguration().setArtifactTypes(artifactTypesCfg); + Either<List<ArtifactType>, ActionStatus> allArtifactTypes = elementOperation.getAllArtifactTypes(); + assertTrue(allArtifactTypes.isLeft()); + assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); + + artifactTypesCfg.remove(0); + allArtifactTypes = elementOperation.getAllArtifactTypes(); + assertTrue(allArtifactTypes.isLeft()); + assertEquals(artifactTypesCfg.size(), allArtifactTypes.left().value().size()); + + artifactTypesCfg.add("type5"); + } + + // @Test + public void testGetResourceAndServiceCategoty() { + String id = OperationTestsUtil.deleteAndCreateResourceCategory(CATEGORY, SUBCATEGORY, titanDao); + + Either<CategoryDefinition, ActionStatus> res = elementOperation.getCategory(NodeTypeEnum.ResourceNewCategory, + id); + assertTrue(res.isLeft()); + CategoryDefinition categoryDefinition = (CategoryDefinition) res.left().value(); + assertEquals(CATEGORY, categoryDefinition.getName()); + assertEquals(SUBCATEGORY, categoryDefinition.getSubcategories().get(0).getName()); + + id = OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY, titanDao); + + res = elementOperation.getCategory(NodeTypeEnum.ServiceNewCategory, id); + assertTrue(res.isLeft()); + categoryDefinition = (CategoryDefinition) res.left().value(); + assertEquals(CATEGORY, categoryDefinition.getName()); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java new file mode 100644 index 0000000000..6765557bab --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java @@ -0,0 +1,289 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.heat.HeatParameterType; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation; +import org.openecomp.sdc.be.resources.data.HeatParameterData; +import org.openecomp.sdc.be.resources.data.HeatParameterValueData; + +import fj.data.Either; + +public class HeatParametersOperationTest extends ModelTestBase { + + HeatParametersOperation heatParametersOperation = new HeatParametersOperation(); + + TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + + @Before + public void setup() { + heatParametersOperation.setTitanGenericDao(titanGenericDao); + + } + + @Test + public void addPropertyToResourceTest() { + + String propName = "myProp"; + HeatParameterDefinition property = buildHeatPropertyDefinition(); + + HeatParameterData propertyData = new HeatParameterData(property); + + Either<HeatParameterData, TitanOperationStatus> either = Either.left(propertyData); + + GraphRelation graphRelation = new GraphRelation(); + Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation); + + when(titanGenericDao.createNode((HeatParameterData) anyObject(), eq(HeatParameterData.class))) + .thenReturn(either); + when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), + eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); + + Either<HeatParameterData, TitanOperationStatus> result = heatParametersOperation.addPropertyToGraph(propName, + property, "resourceId.artifactId", NodeTypeEnum.ArtifactRef); + + assertTrue(result.isLeft()); + + } + + @Test + public void addPropertyListToResourceTest() { + + HeatParameterDefinition property = buildHeatPropertyDefinition(); + HeatParameterDefinition property2 = buildHeatPropertyDefinition(); + property2.setName("p2"); + + List<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>(); + parameters.add(property); + parameters.add(property2); + + HeatParameterData propertyData = new HeatParameterData(property); + + Either<HeatParameterData, TitanOperationStatus> either = Either.left(propertyData); + + GraphRelation graphRelation = new GraphRelation(); + Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation); + + when(titanGenericDao.createNode((HeatParameterData) anyObject(), eq(HeatParameterData.class))) + .thenReturn(either); + when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), + eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult); + + StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters, + "resourceId.artifactId", NodeTypeEnum.ArtifactRef); + + assertEquals(StorageOperationStatus.OK, result); + + } + + @Test + public void testStringValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.STRING, "50aaa")); + } + + @Test + public void testNumberValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "50")); + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "50.5")); + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "0x11")); + + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "aaa")); + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.NUMBER, "?>!")); + } + + @Test + public void testJsonValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.JSON, "{ \"member\" : \"50\"}")); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition( + HeatParameterType.JSON.getType(), "{ \"member\" : \"50\"}"); + StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals(HeatParameterType.JSON.getType(), propertyDefinition.getType()); + + } + + @Test + public void testListValues() { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.COMMA_DELIMITED_LIST, "one, two")); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition( + HeatParameterType.COMMA_DELIMITED_LIST.getType(), "one, two"); + StorageOperationStatus operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals(HeatParameterType.COMMA_DELIMITED_LIST.getType(), propertyDefinition.getType()); + assertEquals("one, two", propertyDefinition.getDefaultValue()); + } + + @Test + public void testBooleanValues() { + + String[] trueArray = { "true", "t", "1", "on", "y", "yes" }; + String[] falseArray = { "false", "f", "0", "off", "n", "no" }; + + for (int i = 0; i < trueArray.length; i++) { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition( + HeatParameterType.BOOLEAN.getType(), trueArray[i]); + StorageOperationStatus operationStatus = heatParametersOperation + .validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("true", propertyDefinition.getDefaultValue()); + + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), + trueArray[i].toUpperCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("true", propertyDefinition.getDefaultValue()); + + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, trueArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), + trueArray[i].toLowerCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("true", propertyDefinition.getDefaultValue()); + } + + for (int i = 0; i < falseArray.length; i++) { + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); + HeatParameterDefinition propertyDefinition = buildHeatBooleanPropertyDefinition( + HeatParameterType.BOOLEAN.getType(), falseArray[i]); + StorageOperationStatus operationStatus = heatParametersOperation + .validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("false", propertyDefinition.getDefaultValue()); + + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), + falseArray[i].toUpperCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("false", propertyDefinition.getDefaultValue()); + + assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, falseArray[i])); + propertyDefinition = buildHeatBooleanPropertyDefinition(HeatParameterType.BOOLEAN.getType(), + falseArray[i].toLowerCase()); + operationStatus = heatParametersOperation.validateAndUpdateProperty(propertyDefinition); + assertEquals(StorageOperationStatus.OK, operationStatus); + assertEquals("false", propertyDefinition.getDefaultValue()); + } + + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "true")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "t")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "1")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "on")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "y")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "yes")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "false")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "f")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "0")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "off")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "n")); + // assertTrue(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, + // "no")); + + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, "blabla")); + assertFalse(heatParametersOperation.isValidValue(HeatParameterType.BOOLEAN, "2")); + } + + private HeatParameterDefinition buildHeatPropertyDefinition() { + HeatParameterDefinition parameter = new HeatParameterDefinition(); + + parameter.setName("p1"); + parameter.setType("string"); + parameter.setDefaultValue("def"); + parameter.setCurrentValue("current"); + parameter.setDescription("description"); + + return parameter; + } + + private HeatParameterDefinition buildHeatBooleanPropertyDefinition(String type, String boolValue) { + HeatParameterDefinition parameter = new HeatParameterDefinition(); + + parameter.setName("parameter1"); + parameter.setType(type); + parameter.setDefaultValue(boolValue); + parameter.setDescription("description"); + + return parameter; + } + + @Test + public void addPropertyToResourceInstanceTest() { + + HeatParameterDefinition property = buildHeatPropertyDefinition(); + + HeatParameterValueData propertyData = new HeatParameterValueData(); + propertyData.setUniqueId("bla"); + propertyData.setValue("value1"); + + Either<HeatParameterValueData, TitanOperationStatus> either = Either.left(propertyData); + + GraphRelation graphRelation = new GraphRelation(); + Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation); + + when(titanGenericDao.createNode((HeatParameterValueData) anyObject(), eq(HeatParameterValueData.class))) + .thenReturn(either); + when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), + eq(GraphEdgeLabels.PARAMETER_VALUE), anyMap())).thenReturn(relationResult); + when(titanGenericDao.createRelation((GraphNode) anyObject(), (GraphNode) anyObject(), + eq(GraphEdgeLabels.PARAMETER_IMPL), anyMap())).thenReturn(relationResult); + + Either<HeatParameterValueData, TitanOperationStatus> result = heatParametersOperation + .addHeatValueToGraph(property, "artifactLabel", "resourceInstanceId.artifactId", "resourceInstanceId"); + + assertTrue(result.isLeft()); + + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java new file mode 100644 index 0000000000..e1eb7db070 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java @@ -0,0 +1,272 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class InterfaceOperationTest { + private static Logger log = LoggerFactory.getLogger(InterfaceOperationTest.class.getName()); + private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + private static String USER_ID = "muserId"; + private static String CATEGORY_NAME = "category/mycategory"; + // InterfaceLifecycleOperation interfaceOperation = new + // InterfaceLifecycleOperation(); + + // TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "interface-operation") + private InterfaceLifecycleOperation interfaceOperation; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + // @Resource(name = "artifact-operation") + // private ArtifactOperation artifactOperation; + + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); + } + + @BeforeClass + public static void setupBeforeClass() { + // ExternalConfiguration.setAppName("catalog-model"); + // String appConfigDir = "src/test/resources/config/catalog-model"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); + + ModelTestBase.init(); + + } + + @Test + public void testDummy() { + + assertTrue(interfaceOperation != null); + + } + + @Test + public void addInterfaceToResourceTest() { + + String capabilityTypeName = "mycapability1"; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute1"; + String rootName = "Root100"; + String softwareCompName = "tosca.nodes.SoftwareComponent"; + String computeNodeName = "tosca.nodes.Compute"; + String myResourceVersion = "300.0"; + String reqRelationship = "myrelationship"; + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "100.0", null, + true, true); + + String interfaceName = "standard"; + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); + + Operation op = buildOperationDefinition(); + Map<String, Operation> operations = new HashMap<String, Operation>(); + operations.put("Create", op); + interfaceDefinition.setOperations(operations); + + Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation + .addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); + + assertTrue(result.isLeft()); + log.debug("{}", result.left().value()); + + Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation + .getResource(rootResource.getUniqueId()); + assertTrue(getResourceRes.isLeft()); + Resource resourceWithInterface = getResourceRes.left().value(); + Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); + assertNotNull(interfaces); + assertFalse(interfaces.isEmpty()); + InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); + assertNotNull(interfaceDefinition2.getOperations()); + assertFalse(interfaceDefinition2.getOperations().isEmpty()); + + } + + @Test + public void updateInterfaceToResourceTest() { + + String reqName = "host"; + String rootName = "Root200"; + String softwareCompName = "tosca.nodes.SoftwareComponent"; + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "200.0", null, + true, true); + + String interfaceName = "standard"; + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); + + Operation op = buildOperationDefinition(); + Map<String, Operation> operations = new HashMap<String, Operation>(); + operations.put("create", op); + interfaceDefinition.setOperations(operations); + + Either<InterfaceDefinition, StorageOperationStatus> result = interfaceOperation + .addInterfaceToResource(interfaceDefinition, rootResource.getUniqueId(), "standard"); + + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId()); + + assertTrue(fetchRootResource.isLeft()); + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "400.0", rootResource.getName(), true, true); + + assertTrue(result.isLeft()); + log.debug("{}", result.left().value()); + + addImplementationToOperation(op); + // String resourceId, String interfaceName, String + // operationName,Operation interf + + Either<Operation, StorageOperationStatus> opResult = interfaceOperation + .updateInterfaceOperation(softwareComponent.getUniqueId(), "standard", "create", op); + // PrintGraph pg = new PrintGraph(); + // System.out.println(pg.buildGraphForWebgraphWiz(titanDao.getGraph().left().value())); + assertTrue(opResult.isLeft()); + log.debug("{}", opResult.left().value()); + + Either<Resource, StorageOperationStatus> getResourceRes = resourceOperation + .getResource(softwareComponent.getUniqueId()); + assertTrue(getResourceRes.isLeft()); + Resource resourceWithInterface = getResourceRes.left().value(); + Map<String, InterfaceDefinition> interfaces = resourceWithInterface.getInterfaces(); + assertNotNull(interfaces); + assertFalse(interfaces.isEmpty()); + InterfaceDefinition interfaceDefinition2 = interfaces.get(interfaceName); + assertNotNull(interfaceDefinition2.getOperations()); + assertFalse(interfaceDefinition2.getOperations().isEmpty()); + Operation operation = interfaceDefinition2.getOperations().get("create"); + assertNotNull(operation); + assertNotNull(operation.getImplementation()); + } + + private void addImplementationToOperation(Operation op) { + ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); + artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); + artifactDataDef.setArtifactName("create_myRoot.sh"); + artifactDataDef.setArtifactLabel("create_myRoot"); + artifactDataDef.setArtifactType("SHELL"); + artifactDataDef.setDescription("good description"); + artifactDataDef.setEsId("esId"); + artifactDataDef.setUniqueId(op.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); + ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); + op.setImplementation(artifactDef); + } + + private InterfaceDefinition buildInterfaceDefinition() { + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType("tosca.interfaces.standard"); + interfaceDefinition.setCreationDate(new Long(101232)); + + return interfaceDefinition; + } + + private Operation buildOperationDefinition() { + Operation op = new Operation(); + op.setCreationDate(new Long(101232)); + op.setDescription("asda"); + + return op; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java new file mode 100644 index 0000000000..2b090f6f9f --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java @@ -0,0 +1,1991 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.Operation; +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.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.operations.impl.util.ResourceCreationUtils; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.CapabilityData; +import org.openecomp.sdc.be.resources.data.ComponentInstanceData; +import org.openecomp.sdc.be.resources.data.InterfaceData; +import org.openecomp.sdc.be.resources.data.OperationData; +import org.openecomp.sdc.be.resources.data.RequirementData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.thinkaurelius.titan.core.TitanGraph; +//import com.tinkerpop.blueprints.Vertex; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class LifecycleOperationTest extends ModelTestBase { + private static Logger log = LoggerFactory.getLogger(LifecycleOperationTest.class.getName()); + private static final String CAPABILITY_HOSTED_ON = "HostedOn"; + + private static final String INTERFACE_OPERATION_CREATE = "create"; + + private static final String INTERFACE_NAME = "standard"; + + private static final String CATEGORY_NAME = "category/mycategory"; + + private static final String SERVICE_NAME = "myService"; + + private static final String REQUIREMENT_NAME = "requirementName"; + + private static final String CAPABILITY_NAME = "capName"; + + private static final String USER_ID = "muserId"; + + @javax.annotation.Resource + private TitanGenericDao titanGenericDao; + + @javax.annotation.Resource + private ResourceOperation resourceOperation; + + @javax.annotation.Resource + private ServiceOperation serviceOperation; + + @javax.annotation.Resource + private LifecycleOperation lifecycleOperation; + + @javax.annotation.Resource + private CapabilityTypeOperation capabilityTypeOperation; + + @javax.annotation.Resource + private ArtifactOperation artifactOperation; + + @javax.annotation.Resource + private InterfaceLifecycleOperation interfaceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @javax.annotation.Resource(name = "capability-operation") + private CapabilityOperation capabilityOperation; + + @javax.annotation.Resource(name = "component-instance-operation") + private ComponentInstanceOperation resourceInstanceOperation; + + @javax.annotation.Resource(name = "requirement-operation") + private RequirementOperation requirementOperation; + + User checkoutUser; + User checkinUser; + User rfcUser; + User testerUser; + User adminUser; + + @Rule + public TestName name = new TestName(); + + @BeforeClass + public static void initLifecycleOperation() { + ModelTestBase.init(); + // new ConfigurationSource() { + // + // @Override + // public <T> T getAndWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // return null; + // } + // + // @Override + // public <T> void addWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // + // } + // }); + // + + } + + @Before + public void setupBefore() { + clearGraph(); + UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "co", + ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); + checkoutUser = convertUserDataToUser(modifierData); + + modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "ci", + ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); + checkinUser = convertUserDataToUser(modifierData); + + modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", + ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); + rfcUser = convertUserDataToUser(modifierData); + + modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "tester", + ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "TESTER"); + testerUser = convertUserDataToUser(modifierData); + + modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "admin", + ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN"); + adminUser = convertUserDataToUser(modifierData); + + modifierData = deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, "ADMIN"); + adminUser = convertUserDataToUser(modifierData); + + String[] category = CATEGORY_NAME.split("/"); + OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY_NAME, titanGenericDao); + OperationTestsUtil.deleteAndCreateResourceCategory(category[0], category[1], titanGenericDao); + + } + + @After + public void teardown() { + clearGraph(); + } + + private void clearGraph() { + Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + // graph.removeVertex(vertex); + vertex.remove(); + } + + } + titanGenericDao.commit(); + } + + @Test + public void getOwnerTest() { + + Resource resultResource = createTestResource(checkoutUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals("check modifier", checkoutUser.getUserId(), resourceOwner.getUserId()); + + } + + /*********************** CHECKOUT ***************************************************************/ + + @Test + public void checkoutCertifiedTest() { + + Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); + String origUniqueId = resultResource.getUniqueId(); + Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId); + Resource origResource = origResourceResult.left().value(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkout + Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); + Resource checkoutResource = checkoutResponse.left().value(); + + assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(checkoutResource.getVersion(), "1.1"); + assertEquals(checkoutResource.getCreatorUserId(), adminUser.getUserId()); + assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkoutUser)); + + // assert original resource not deleted + Either<Resource, StorageOperationStatus> getOrigResource = resourceOperation.getResource(origUniqueId); + assertEquals("check resource created", true, getOrigResource.isLeft()); + // assertEquals("assert original resource not changed", origResource, + // getOrigResource.left().value()); + } + + @Test + public void checkoutDefaultTest() { + + Resource resultResource = createTestResource(checkinUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkout + Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); + Resource checkoutResource = checkoutResponse.left().value(); + + assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(checkoutResource.getVersion(), "0.2"); + assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); + assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); + assertEquals(checkoutResource.isHighestVersion(), true); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkoutUser)); + + // assert original resource not deleted + Either<Resource, StorageOperationStatus> getOrigResource = resourceOperation.getResource(origUniqueId); + assertEquals("check resource created", true, getOrigResource.isLeft()); + // assertEquals("assert original resource not changed", origResource, + // getOrigResource.left().value()); + assertEquals("assert original resource not highest version", false, + getOrigResource.left().value().isHighestVersion()); + } + + @Test + public void checkoutFullResourceTest() { + + Resource origResource = createFullTestResource(checkinUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + String origUniqueId = origResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkout + Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); + Resource checkoutResource = checkoutResponse.left().value(); + + assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(checkoutResource.getVersion(), "0.2"); + assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); + assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); + assertEquals(checkoutResource.isHighestVersion(), true); + + assertNotNull(checkoutResource.getArtifacts()); + assertFalse(checkoutResource.getArtifacts().isEmpty()); + assertNotNull(checkoutResource.getInterfaces()); + assertFalse(checkoutResource.getInterfaces().isEmpty()); + Map<String, InterfaceDefinition> interfaces = checkoutResource.getInterfaces(); + assertTrue(interfaces.containsKey(INTERFACE_NAME)); + InterfaceDefinition interfaceDef = interfaces.get(INTERFACE_NAME); + Map<String, Operation> operations = interfaceDef.getOperations(); + assertNotNull(operations); + assertFalse(operations.isEmpty()); + assertTrue(operations.containsKey(INTERFACE_OPERATION_CREATE)); + Operation op = operations.get(INTERFACE_OPERATION_CREATE); + assertNotNull(op.getImplementation()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkoutUser)); + + // assert original resource not deleted + Either<Resource, StorageOperationStatus> getOrigResource = resourceOperation.getResource(origUniqueId); + assertEquals("check resource created", true, getOrigResource.isLeft()); + // assertEquals("assert original resource not changed", origResource, + // getOrigResource.left().value()); + assertEquals("assert original resource not highest version", false, + getOrigResource.left().value().isHighestVersion()); + } + + @Test + public void getResourceOwnerResourceNotExistTest() { + + // create resource metadata + Resource resource = buildResourceMetadata(adminUser.getUserId(), CATEGORY_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setUniqueId("my-resource.0.1"); + + Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource("my-resource.0.1"); + assertEquals("assert resource not exist", true, origResourceResult.isRight()); + + // get resource owner + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner("my-resource.0.1", + NodeTypeEnum.Resource, false); + + assertEquals("assert no owner", true, getOwnerResponse.isRight()); + StorageOperationStatus status = getOwnerResponse.right().value(); + + assertEquals(StorageOperationStatus.INVALID_ID, status); + + } + + @Test + public void checkoutResourceTwice() { + + Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); + String origUniqueId = resultResource.getUniqueId(); + Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId); + Resource origResource = origResourceResult.left().value(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // first checkout + Either<Resource, StorageOperationStatus> checkoutResponse1 = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse1.isLeft()); + + // second checkout + Either<Resource, StorageOperationStatus> checkoutResponse2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false); + assertEquals("check checkout failed", true, checkoutResponse2.isRight()); + assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value()); + + } + + /******** SERVICE */ + @Test + public void checkoutServiceDefaultTest() { + + Service resultResource = createTestService(checkinUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkout + Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation + .checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); + Component checkoutResource = checkoutResponse.left().value(); + + assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(checkoutResource.getVersion(), "0.2"); + assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); + assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); + assertEquals(checkoutResource.isHighestVersion(), true); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkoutUser)); + + // assert original resource not deleted + Either<Service, StorageOperationStatus> getOrigResource = serviceOperation.getService(origUniqueId); + assertEquals("check resource created", true, getOrigResource.isLeft()); + // assertEquals("assert original resource not changed", origResource, + // getOrigResource.left().value()); + assertEquals("assert original resource not highest version", false, + getOrigResource.left().value().isHighestVersion()); + } + + @Test + public void checkoutFullServiceTest() { + + Service origService = createTestService(checkinUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + String origUniqueId = origService.getUniqueId(); + + // add artifacts + addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "install_apache"); + addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "start_apache"); + + // add resource instances + ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); + riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, + resourceOperation, propertyOperation, resourceInstanceOperation); + riTest.addResourceInstancesAndRelation(origService.getUniqueId()); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + Either<Service, StorageOperationStatus> serviceBeforeCheckout = serviceOperation.getService(origUniqueId, true); + assertTrue(serviceBeforeCheckout.isLeft()); + origService = serviceBeforeCheckout.left().value(); + + // checkout + Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation + .checkoutComponent(NodeTypeEnum.Service, origService, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse.isLeft()); + Service checkoutResource = (Service) checkoutResponse.left().value(); + + assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(checkoutResource.getVersion(), "0.2"); + assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId()); + assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId()); + assertEquals(checkoutResource.isHighestVersion(), true); + + assertNotNull(checkoutResource.getArtifacts()); + assertFalse(checkoutResource.getArtifacts().isEmpty()); + assertNotNull(checkoutResource.getComponentInstances()); + assertFalse(checkoutResource.getComponentInstances().isEmpty()); + assertNotNull(checkoutResource.getComponentInstancesRelations()); + assertFalse(checkoutResource.getComponentInstancesRelations().isEmpty()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkoutUser)); + + // assert original resource not deleted + Either<Service, StorageOperationStatus> getOrigResource = serviceOperation.getService(origUniqueId); + assertEquals("check service created", true, getOrigResource.isLeft()); + // assertEquals("assert original resource not changed", origResource, + // getOrigResource.left().value()); + assertEquals("assert original service not highest version", false, + getOrigResource.left().value().isHighestVersion()); + } + + @Test + public void checkoutServiceTwice() { + + Service resultResource = createTestService(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); + String origUniqueId = resultResource.getUniqueId(); + Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId); + Service origResource = origResourceResult.left().value(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // first checkout + Either<? extends Component, StorageOperationStatus> checkoutResponse1 = lifecycleOperation + .checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkoutResponse1.isLeft()); + + // second checkout + Either<? extends Component, StorageOperationStatus> checkoutResponse2 = lifecycleOperation + .checkoutComponent(NodeTypeEnum.Service, origResource, checkoutUser, resourceOwner, false); + assertEquals("check checkout failed", true, checkoutResponse2.isRight()); + assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value()); + + } + + /**************************** CHECKIN ********************************************************************/ + + @Test + public void checkinDefaultTest() { + + Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkin + Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkinResponse.isLeft()); + Resource checkinResource = checkinResponse.left().value(); + + assertEquals(checkinResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(checkinResource.getVersion(), "0.1"); + assertEquals(checkinResource.getCreatorUserId(), adminUser.getUserId()); + assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Resource, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkinUser)); + + } + + @Test + public void checkinFromRfcTest() { + + Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkin + Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false); + assertEquals("check resource object is returned", true, checkinResponse.isLeft()); + + // rfc + Either<Resource, StorageOperationStatus> rfcResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, checkinResponse.left().value(), rfcUser, + checkinUser, false); + assertEquals("check resource object is returned", true, checkinResponse.isLeft()); + + // checkin (cancel rfc) + checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkinComponent(NodeTypeEnum.Resource, rfcResponse.left().value(), checkinUser, rfcUser, false); + assertEquals("check resource object is returned", true, checkinResponse.isLeft()); + resultResource = checkinResponse.left().value(); + + assertEquals(resultResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(resultResource.getVersion(), "0.1"); + assertEquals(resultResource.getCreatorUserId(), adminUser.getUserId()); + assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkinUser)); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(resultResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + } + + /*** SERVICE */ + @Test + public void checkinServiceDefaultTest() { + + Service resultService = createTestService(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + String origUniqueId = resultService.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkin + Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation + .checkinComponent(NodeTypeEnum.Service, resultService, checkinUser, resourceOwner, false); + assertEquals("check service object is returned", true, checkinResponse.isLeft()); + Service checkinResource = (Service) checkinResponse.left().value(); + + assertEquals(checkinResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(checkinResource.getVersion(), "0.1"); + assertEquals(checkinResource.getCreatorUserId(), adminUser.getUserId()); + assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Service, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkinUser)); + + } + + @Test + public void checkinServiceFromRfcTest() { + + Service resultResource = createTestService(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkin + Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation + .checkinComponent(NodeTypeEnum.Service, resultResource, checkinUser, resourceOwner, false); + assertEquals("check service object is returned", true, checkinResponse.isLeft()); + + // rfc + Either<? extends Component, StorageOperationStatus> rfcResponse = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, checkinResponse.left().value(), rfcUser, + checkinUser, false); + assertEquals("check service object is returned", true, checkinResponse.isLeft()); + + // checkin (cancel rfc) + checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, rfcResponse.left().value(), + checkinUser, rfcUser, false); + assertEquals("check resource object is returned", true, checkinResponse.isLeft()); + resultResource = (Service) checkinResponse.left().value(); + + assertEquals(resultResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(resultResource.getVersion(), "0.1"); + assertEquals(resultResource.getCreatorUserId(), adminUser.getUserId()); + assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Service, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(checkinUser)); + + // assert relations + ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); + metadata.setUniqueId(resultResource.getUniqueId()); + ServiceMetadataData resourceData = new ServiceMetadataData(metadata); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + } + + /**************************** + * UNDO CHECKOUT + ********************************************************************/ + + @Test + public void undoCheckoutNewResourceTest() { + + Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // + + // undo checkout + Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false); + assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); + + Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId); + assertTrue(origResourceResult.isRight()); + /* + * assertTrue(origResourceResult.isLeft()); + * assertTrue(origResourceResult.left().value().getIsDeleted() == true); + */ + } + + @Test + public void undoCheckoutNewFullResourceTest() { + + Resource resultResource = createFullTestResource(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // undo checkout + Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false); + assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); + + Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId); + /* + * assertTrue(origResourceResult.isLeft()); + * assertTrue(origResourceResult.left().value().getIsDeleted() == true); + */ assertTrue(origResourceResult.isRight()); + + String interfaceId = origUniqueId + "." + INTERFACE_NAME; + Either<InterfaceData, TitanOperationStatus> node = titanGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); + assertTrue(node.isRight()); + + String operationId = interfaceId + "." + INTERFACE_OPERATION_CREATE; + Either<OperationData, TitanOperationStatus> op = titanGenericDao.getNode( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), operationId, OperationData.class); + assertTrue(op.isRight()); + + String capabilityId = "capability." + origUniqueId + "." + CAPABILITY_NAME; + Either<CapabilityData, TitanOperationStatus> capability = titanGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityId, CapabilityData.class); + assertTrue(capability.isRight()); + + String requirementId = origUniqueId + "." + REQUIREMENT_NAME; + Either<RequirementData, TitanOperationStatus> req = titanGenericDao.getNode( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class); + assertTrue(req.isRight()); + + } + + @Test + public void undoCheckoutExistingResourceTest() { + + Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + String prevResourceId = resultResource.getUniqueId(); + Either<Resource, StorageOperationStatus> result2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource created", true, result2.isLeft()); + Resource resultResource2 = result2.left().value(); + + // get resource owner + getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, + false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + resourceOwner = getOwnerResponse.left().value(); + assertEquals(resourceOwner, checkoutUser); + + // undo checkout + Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .undoCheckout(NodeTypeEnum.Resource, resultResource2, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); + + // get previous resource + Either<Resource, StorageOperationStatus> resourceAfterUndo = resourceOperation.getResource(prevResourceId); + assertTrue(resourceAfterUndo.isLeft()); + Resource actualResource = resourceAfterUndo.left().value(); + assertTrue(actualResource.isHighestVersion()); + assertEquals(adminUser.getUserId(), actualResource.getCreatorUserId()); + assertEquals(adminUser.getUserId(), actualResource.getLastUpdaterUserId()); + assertEquals("0.1", actualResource.getVersion()); + assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState()); + + Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation + .getResource(resultResource2.getUniqueId()); + /* + * assertTrue(origResourceResult.isLeft()); + * assertTrue(origResourceResult.left().value().getIsDeleted() == true); + */ assertTrue(origResourceResult.isRight()); + + } + + /**** SERVICE ***/ + @Test + public void undoCheckoutNewServiceTest() { + + Service resultResource = createTestService(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // + + // undo checkout + Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation + .undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false); + assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); + + Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId); + /* + * assertTrue(origResourceResult.isLeft()); + * assertTrue(origResourceResult.left().value().getIsDeleted() == true); + */ assertTrue(origResourceResult.isRight()); + + } + + @Test + public void undoCheckoutNewFullServiceTest() { + + Service origService = createTestService(checkinUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + String origUniqueId = origService.getUniqueId(); + + // add artifacts + addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "install_apache"); + addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "start_apache"); + + // add resource instances + ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); + riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, + resourceOperation, propertyOperation, resourceInstanceOperation); + riTest.addResourceInstancesAndRelation(origService.getUniqueId()); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + Either<Service, StorageOperationStatus> service = serviceOperation.getService(origUniqueId); + assertTrue(service.isLeft()); + + Service resultResource = service.left().value(); + List<ComponentInstance> resourceInstances = resultResource.getComponentInstances(); + + // undo checkout + Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation + .undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false); + assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); + + Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId); + /* + * assertTrue(origResourceResult.isLeft()); + * assertTrue(origResourceResult.left().value().getIsDeleted() == true); + */ assertTrue(origResourceResult.isRight()); + + for (ComponentInstance ri : resourceInstances) { + Either<ComponentInstanceData, TitanOperationStatus> node = titanGenericDao.getNode( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(), + ComponentInstanceData.class); + assertTrue(node.isRight()); + } + + } + + @Test + public void undoCheckoutExistingServiceTest() { + + Service resultResource = createTestService(adminUser.getUserId(), "0.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + String prevResourceId = resultResource.getUniqueId(); + Either<? extends Component, StorageOperationStatus> result2 = lifecycleOperation + .checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false); + assertEquals("check resource created", true, result2.isLeft()); + Component resultResource2 = result2.left().value(); + String result2Uid = resultResource.getUniqueId(); + + // get resource owner + getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, + false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + resourceOwner = getOwnerResponse.left().value(); + assertEquals(resourceOwner, checkoutUser); + + // undo checkout + Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation + .undoCheckout(NodeTypeEnum.Service, resultResource2, checkoutUser, resourceOwner, false); + assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft()); + + // get previous resource + Either<Service, StorageOperationStatus> resourceAfterUndo = serviceOperation.getService(prevResourceId); + assertTrue(resourceAfterUndo.isLeft()); + Service actualResource = resourceAfterUndo.left().value(); + assertTrue(actualResource.isHighestVersion()); + assertEquals(adminUser.getUserId(), actualResource.getCreatorUserId()); + assertEquals(adminUser.getUserId(), actualResource.getLastUpdaterUserId()); + assertEquals("0.1", actualResource.getVersion()); + assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState()); + + Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(result2Uid); + /* + * assertTrue(origResourceResult.isLeft()); + * assertTrue(origResourceResult.left().value().getIsDeleted() == true); + */ assertTrue(origResourceResult.isRight()); + + } + + /**************************** + * CERTIFICATION REQUEST + ********************************************************************/ + + @Test + public void certReqDefaultTest() { + Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + } + + @Test + public void atomicCheckinCertReqTest() { + Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + private Resource testCertificationRequest(LifecycleStateEnum preState) { + + Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", preState, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkin + Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, resourceOwner, false); + assertEquals("check resource object is returned", true, certReqResponse.isLeft()); + Resource resourceAfterChange = certReqResponse.left().value(); + + assertEquals(resourceAfterChange.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(resourceAfterChange.getVersion(), "0.1"); + assertEquals(resourceAfterChange.getCreatorUserId(), adminUser.getUserId()); + assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Resource, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(rfcUser)); + + return resourceAfterChange; + } + + /** SERVICE **/ + @Test + public void certServiceReqDefaultTest() { + Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + + // assert relations + ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); + metadata.setUniqueId(actualResource.getUniqueId()); + ServiceMetadataData serviceData = new ServiceMetadataData(metadata); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + } + + @Test + public void atomicServiceCheckinCertReqTest() { + Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + // assert relations + ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); + metadata.setUniqueId(actualResource.getUniqueId()); + ServiceMetadataData serviceData = new ServiceMetadataData(metadata); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + private Service testServiceCertificationRequest(LifecycleStateEnum preState) { + + Service resultResource = createTestService(adminUser.getUserId(), "0.1", preState, null); + String origUniqueId = resultResource.getUniqueId(); + + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, + NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + + // checkin + Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, resourceOwner, false); + assertEquals("check resource object is returned", true, certReqResponse.isLeft()); + Service resourceAfterChange = (Service) certReqResponse.left().value(); + + assertEquals(resourceAfterChange.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(resourceAfterChange.getVersion(), "0.1"); + assertEquals(resourceAfterChange.getCreatorUserId(), adminUser.getUserId()); + assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId()); + + // assert owner changed + Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation + .getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Service, false); + assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft()); + resourceOwner = getOwnerCheckoutResponse.left().value(); + assertTrue(resourceOwner.equals(rfcUser)); + + return resourceAfterChange; + } + + /**************************** + * START CERTIFICATION + ********************************************************************/ + + @Test + public void startCertificationTest() { + + Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // certification request + Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false); + assertTrue(requestCertificationResult.isLeft()); + + // start certification + Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false); + + assertEquals(true, startCertificationResult.isLeft()); + Resource actualResource = startCertificationResult.left().value(); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); + + assertTrue(actualResource.isHighestVersion()); + assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); + assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); + assertEquals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, actualResource.getLifecycleState()); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + /** SERVICE */ + @Test + public void startServiceCertificationTest() { + + Service resultResource = createTestService(checkinUser.getUserId(), "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // certification request + Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, checkinUser, false); + assertTrue(requestCertificationResult.isLeft()); + + // start certification + Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultResource, testerUser, rfcUser, false); + + assertEquals(true, startCertificationResult.isLeft()); + Service actualResource = (Service) startCertificationResult.left().value(); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); + + assertTrue(actualResource.isHighestVersion()); + assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); + assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); + assertEquals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, actualResource.getLifecycleState()); + + // assert relations + ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition(); + metadata.setUniqueId(actualResource.getUniqueId()); + ServiceMetadataData serviceData = new ServiceMetadataData(metadata); + Map<String, Object> props = new HashMap<String, Object>(); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + /**************************** + * FAIL CERTIFICATION + ********************************************************************/ + + @Test + public void failCertificationTest() { + + Resource actualResource = certificationStatusChange(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + // old edges removed + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + // new state is checkin + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + /*** SERVICE **/ + + @Test + public void failCertificationServiceTest() { + + Service actualService = certificationStatusChangeService(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser); + + // assert relations + ServiceMetadataData resourceData = new ServiceMetadataData((ServiceMetadataDataDefinition) actualService + .getComponentMetadataDefinition().getMetadataDataDefinition()); + Map<String, Object> props = new HashMap<String, Object>(); + + // old edges removed + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + // new state is checkin + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + /**************************** + * CANCEL CERTIFICATION + ********************************************************************/ + + @Test + public void cancelCertificationTest() { + + Resource actualResource = certificationStatusChange(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + // old edges removed + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + // new state is rfc + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + /** SERVICE **/ + @Test + public void cancelCertificationServiceTest() { + + Service actualService = certificationStatusChangeService(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser); + + // assert relations + ServiceMetadataData ServiceNode = new ServiceMetadataData(); + ServiceNode.getMetadataDataDefinition().setUniqueId(actualService.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + // old edges removed + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + // new state is rfc + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + } + + /**************************** CERTIFY ********************************************************************/ + + @Test + public void certifyTest() { + + Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // certification request + Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false); + assertTrue(requestCertificationResult.isLeft()); + + // start certification + Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false); + assertEquals(true, startCertificationResult.isLeft()); + Resource actualResource = startCertificationResult.left().value(); + + // cancel certification + Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation + .certifyComponent(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, false); + + assertEquals(true, CertificationResult.isLeft()); + actualResource = (Resource) CertificationResult.left().value(); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); + + assertTrue(actualResource.isHighestVersion()); + assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); + assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); + assertEquals(LifecycleStateEnum.CERTIFIED, actualResource.getLifecycleState()); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + // old edges removed + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + // new state is certified + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + } + + /******** SERVICE **/ + + @Test + public void certifyServiceTest() { + + Service resultService = createTestService(checkinUser.getUserId(), "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // certification request + Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false); + assertTrue(requestCertificationResult.isLeft()); + + // start certification + Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false); + assertEquals(true, startCertificationResult.isLeft()); + Service actualService = (Service) startCertificationResult.left().value(); + + // cancel certification + Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation + .certifyComponent(NodeTypeEnum.Service, actualService, testerUser, testerUser, false); + + assertEquals(true, CertificationResult.isLeft()); + actualService = (Service) CertificationResult.left().value(); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Service, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals(testerUser.getUserId(), resourceOwner.getUserId()); + + assertTrue(actualService.isHighestVersion()); + assertEquals(checkinUser.getUserId(), actualService.getCreatorUserId()); + assertEquals(testerUser.getUserId(), actualService.getLastUpdaterUserId()); + assertEquals(LifecycleStateEnum.CERTIFIED, actualService.getLifecycleState()); + + // assert relations + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(actualService.getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + + // old edges removed + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao + .getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isRight()); + + // new state is certified + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, + props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, + GraphEdgeLabels.LAST_STATE, props); + assertTrue(incomingRelationByCriteria.isLeft()); + assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue()); + + } + + @Test + public void testDeleteOldVersionsResource() { + // simulate + createTestResource(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); + Resource resourceNewVersion = createTestResource(checkinUser.getUserId(), "1.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + createTestResource(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + resourceNewVersion.getUUID()); + createTestResource(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, + resourceNewVersion.getUUID()); + Resource certifiedResource = createTestResource(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, + resourceNewVersion.getUUID()); + + Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation + .deleteOldComponentVersions(NodeTypeEnum.Resource, certifiedResource.getName(), + certifiedResource.getUUID(), false); + + assertTrue(deleteOldComponentVersions.isLeft()); + + String resourceName = certifiedResource.getName(); + Either<List<Resource>, StorageOperationStatus> resource = resourceOperation + .getResourceByNameAndVersion(resourceName, "1.0", false); + assertTrue(resource.isLeft()); + + resource = resourceOperation.getResourceByNameAndVersion(resourceName, "2.0", false); + assertTrue(resource.isLeft()); + + resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.1", false); + assertTrue(resource.isLeft()); + assertTrue(resource.left().value().size() == 1); + Resource deleted = resource.left().value().get(0); + assertTrue(deleted.getIsDeleted()); + // assertEquals(StorageOperationStatus.NOT_FOUND, + // resource.right().value()); + + resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.2", false); + // assertTrue(resource.isRight()); + // assertEquals(StorageOperationStatus.NOT_FOUND, + // resource.right().value()); + assertTrue(resource.isLeft()); + assertTrue(resource.left().value().size() == 1); + deleted = resource.left().value().get(0); + assertTrue(deleted.getIsDeleted()); + + resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.3", false); + // assertTrue(resource.isRight()); + // assertEquals(StorageOperationStatus.NOT_FOUND, + // resource.right().value()); + assertTrue(resource.isLeft()); + assertTrue(resource.left().value().size() == 1); + deleted = resource.left().value().get(0); + assertTrue(deleted.getIsDeleted()); + } + + @Test + public void testDeleteOldVersionsService() { + // simulate + createTestService(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null); + Service serviceNewUUid = createTestService(checkinUser.getUserId(), "1.1", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + createTestService(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, + serviceNewUUid.getUUID()); + createTestService(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, + serviceNewUUid.getUUID()); + Service certifiedService = createTestService(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, + serviceNewUUid.getUUID()); + + Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation + .deleteOldComponentVersions(NodeTypeEnum.Service, certifiedService.getName(), + certifiedService.getUUID(), false); + + assertTrue(deleteOldComponentVersions.isLeft()); + + String resourceName = certifiedService.getName(); + Either<Service, StorageOperationStatus> service = serviceOperation.getServiceByNameAndVersion(resourceName, + "1.0", null, false); + assertTrue(service.isLeft()); + + service = serviceOperation.getServiceByNameAndVersion(resourceName, "2.0", null, false); + assertTrue(service.isLeft()); + + service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.1", null, false); + /* + * assertTrue(resource.isRight()); + * assertEquals(StorageOperationStatus.NOT_FOUND, + * resource.right().value()); + */ + assertTrue(service.isLeft()); + assertTrue(service.left().value().getIsDeleted()); + + service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.2", null, false); + + service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false); + /* + * assertTrue(service.isRight()); + * assertEquals(StorageOperationStatus.NOT_FOUND, + * service.right().value()); + */ + assertTrue(service.isLeft()); + assertTrue(service.left().value().getIsDeleted()); + + service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false); + /* + * assertTrue(service.isRight()); + * assertEquals(StorageOperationStatus.NOT_FOUND, + * service.right().value()); + */ + assertTrue(service.isLeft()); + assertTrue(service.left().value().getIsDeleted()); + + } + + private Resource certificationStatusChange(LifecycleStateEnum nextState, User expectedOwner) { + Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // certification request + Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false); + assertTrue(requestCertificationResult.isLeft()); + + // start certification + Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false); + assertEquals(true, startCertificationResult.isLeft()); + Resource actualResource = startCertificationResult.left().value(); + + // cancel certification + Either<Resource, StorageOperationStatus> failCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .cancelOrFailCertification(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, nextState, + false); + + assertEquals(true, failCertificationResult.isLeft()); + actualResource = failCertificationResult.left().value(); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals(expectedOwner, resourceOwner); + + assertTrue(actualResource.isHighestVersion()); + assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId()); + assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId()); + assertEquals(nextState, actualResource.getLifecycleState()); + return actualResource; + } + + private Service certificationStatusChangeService(LifecycleStateEnum nextState, User expectedOwner) { + Service resultService = createTestService(checkinUser.getUserId(), "0.2", + LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null); + + // certification request + Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false); + assertTrue(requestCertificationResult.isLeft()); + + // start certification + Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false); + assertEquals(true, startCertificationResult.isLeft()); + Service actualService = (Service) startCertificationResult.left().value(); + + // cancel certification + Either<? extends Component, StorageOperationStatus> failCertificationResult = lifecycleOperation + .cancelOrFailCertification(NodeTypeEnum.Service, actualService, testerUser, testerUser, nextState, + false); + + assertEquals(true, failCertificationResult.isLeft()); + actualService = (Service) failCertificationResult.left().value(); + + // get resource owner + Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation + .getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Resource, false); + + assertEquals("check user object is returned", true, getOwnerResponse.isLeft()); + User resourceOwner = getOwnerResponse.left().value(); + assertEquals(expectedOwner, resourceOwner); + + assertTrue(actualService.isHighestVersion()); + assertEquals(checkinUser.getUserId(), actualService.getCreatorUserId()); + assertEquals(testerUser.getUserId(), actualService.getLastUpdaterUserId()); + assertEquals(nextState, actualService.getLifecycleState()); + return actualService; + } + + private Resource createTestResource(String userId, String version, LifecycleStateEnum state, String uuid) { + // create resource in graph + + Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME); + resource2.setVersion(version); + ; + resource2.setLifecycleState(state); + resource2.setUUID(uuid); + + Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource2); + assertEquals("check resource created", true, result.isLeft()); + Resource resultResource = result.left().value(); + return resultResource; + } + + private Service createTestService(String userId, String version, LifecycleStateEnum state, String uuid) { + // create resource in graph + + Service service = new Service(); + service.setName(SERVICE_NAME); + service.setVersion(version); + service.setDescription("description 1"); + service.setCreatorUserId(userId); + service.setContactId("contactId@sdc.com"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(CATEGORY_NAME); + + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + service.setTags(tags); + service.setUUID(uuid); + + service.setLifecycleState(state); + + Either<Service, StorageOperationStatus> result = serviceOperation.createService(service); + assertEquals("check service created", true, result.isLeft()); + Service resultResource = result.left().value(); + return resultResource; + } + + private Resource createFullTestResource(String userId, String version, LifecycleStateEnum state) { + + Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME); + resource2.setVersion(version); + ; + resource2.setLifecycleState(state); + + InterfaceDefinition inter = new InterfaceDefinition(INTERFACE_NAME, "interface description", null); + + Operation operation = new Operation(); + operation.setDescription("op description"); + operation.setUniqueId(inter.getUniqueId() + "." + INTERFACE_OPERATION_CREATE); + + ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition(); + artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); + artifactDataDef.setArtifactName("create_myRoot.sh"); + artifactDataDef.setArtifactLabel("create_myRoot"); + artifactDataDef.setArtifactType("SHELL"); + artifactDataDef.setDescription("good description"); + artifactDataDef.setEsId("esId"); + artifactDataDef.setUniqueId(operation.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); + ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); + + operation.setImplementation(artifactDef); + operation.setCreationDate(System.currentTimeMillis()); + Map<String, Operation> ops = new HashMap<>(); + ops.put(INTERFACE_OPERATION_CREATE, operation); + inter.setOperations(ops); + + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + interfaces.put(INTERFACE_NAME, inter); + + resource2.setInterfaces(interfaces); + + String capabilityTypeName = CAPABILITY_HOSTED_ON; + createCapabilityOnGraph(capabilityTypeName); + + // create capability definition + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setDescription("my capability"); + capabilityDefinition.setType(capabilityTypeName); + capabilityDefinition.setName(CAPABILITY_NAME); + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + List<String> validSourceTypes = new ArrayList<String>(); + validSourceTypes.add("tosca.nodes.SC"); + capabilityDefinition.setValidSourceTypes(validSourceTypes); + List<CapabilityDefinition> caplist = new ArrayList<CapabilityDefinition>(); + caplist.add(capabilityDefinition); + capabilities.put(capabilityTypeName, caplist); + resource2.setCapabilities(capabilities); + + // add requirement definition + RequirementDefinition reqDefinition = new RequirementDefinition(); + // reqDefinition.setNode(reqNodeName); + // reqDefinition.setRelationship(reqRelationship); + + reqDefinition.setCapability(capabilityTypeName); + reqDefinition.setName(REQUIREMENT_NAME); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + List<RequirementDefinition> reqlist = new ArrayList<RequirementDefinition>(); + reqlist.add(reqDefinition); + requirements.put(capabilityTypeName, reqlist); + resource2.setRequirements(requirements); + + Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource2); + assertEquals("check resource created", true, result.isLeft()); + Resource resultResource = result.left().value(); + + // add artifacts to resource + // ArtifactDataDefinition artifactDataDef = new + // ArtifactDataDefinition(); + artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI="); + artifactDataDef.setArtifactName("create_myRoot.sh"); + artifactDataDef.setArtifactLabel("create_myRoot"); + artifactDataDef.setArtifactType("SHELL"); + artifactDataDef.setDescription("good description"); + artifactDataDef.setEsId("esId"); + artifactDataDef.setUniqueId(resultResource.getUniqueId() + "." + artifactDataDef.getArtifactLabel()); + artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz"); + // artifacts.put("myArtifact", artifactDef); + // resource2.setArtifacts(artifacts); + + Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = artifactOperation + .addArifactToComponent(artifactDef, resultResource.getUniqueId(), NodeTypeEnum.Resource, false, true); + assertTrue(addArifactToResource.isLeft()); + + Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(resultResource.getUniqueId()); + assertTrue(resource.isLeft()); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + String json = prettyGson.toJson(resource.left().value()); + log.debug(json); + return resource.left().value(); + } + + private void createCapabilityOnGraph(String capabilityTypeName) { + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setDescription("desc1"); + capabilityTypeDefinition.setType(capabilityTypeName); + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + String propName1 = "disk_size"; + PropertyDefinition property1 = buildProperty1(); + properties.put(propName1, property1); + capabilityTypeDefinition.setProperties(properties); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition); + assertTrue(addCapabilityType1.isLeft()); + } + + private User convertUserDataToUser(UserData modifierData) { + User modifier = new User(); + modifier.setUserId(modifierData.getUserId()); + modifier.setEmail(modifierData.getEmail()); + modifier.setFirstName(modifierData.getFirstName()); + modifier.setLastName(modifierData.getLastName()); + modifier.setRole(modifierData.getRole()); + return modifier; + } + + private Resource buildResourceMetadata(String userId, String category) { + // deleteAndCreateCategory(category); + + Resource resource = new Resource(); + resource.setName("my-resource"); + resource.setVersion("1.0"); + ; + resource.setDescription("description 1"); + resource.setAbstract(false); + resource.setCreatorUserId(userId); + resource.setContactId("contactId@sdc.com"); + resource.setVendorName("vendor 1"); + resource.setVendorRelease("1.0.0"); + String[] categoryArr = category.split("/"); + resource.addCategory(categoryArr[0], categoryArr[1]); + resource.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + resource.setTags(tags); + return resource; + } + + public UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + userData.setRole(role); + + titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanGenericDao.createNode(userData, UserData.class); + titanGenericDao.commit(); + + return userData; + } + + private PropertyDefinition buildProperty1() { + PropertyDefinition property1 = new PropertyDefinition(); + property1.setDefaultValue("10"); + property1.setDescription( + "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property1.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + constraints.add(propertyConstraint1); + + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + constraints.add(propertyConstraint2); + + property1.setConstraints(constraints); + return property1; + } + + private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".sh"); + artifactInfo.setArtifactType("SHELL"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setPayloadData("UEsDBAoAAAAIAAeLb0bDQz"); + + 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(artifactName); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); + + Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation + .addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); + assertTrue(artifact.isLeft()); + return artifactInfo; + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java new file mode 100644 index 0000000000..5bd6c831a5 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java @@ -0,0 +1,120 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Iterator; + +import javax.annotation.Resource; + +import org.apache.commons.lang.StringUtils; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") + +public class PolicyTypeOperationTest extends ModelTestBase { + + @Resource(name = "policy-type-operation") + private PolicyTypeOperation policyTypeOperation; + + @BeforeClass + public static void setupBeforeClass() { + ModelTestBase.init(); + + } + + @Before + public void cleanUp() { + TitanGenericDao titanGenericDao = policyTypeOperation.titanGenericDao; + Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + + } + titanGenericDao.commit(); + } + + @Test + public void testAddPolicyType() { + + PolicyTypeDefinition policyTypePreCreate = createPolicyTypeDef(); + assertTrue(StringUtils.isEmpty(policyTypePreCreate.getUniqueId())); + Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType = policyTypeOperation + .addPolicyType(policyTypePreCreate); + assertTrue(addPolicyType.isLeft()); + PolicyTypeDefinition policyTypePostCreate = addPolicyType.left().value(); + assertEquals(policyTypePostCreate.getType(), policyTypePreCreate.getType()); + assertEquals(policyTypePostCreate.getDescription(), policyTypePreCreate.getDescription()); + + assertTrue(!StringUtils.isEmpty(policyTypePostCreate.getUniqueId())); + } + + @Test + public void testGetLatestPolicyTypeByType() { + PolicyTypeDefinition policyTypeCreated = policyTypeOperation.addPolicyType(createPolicyTypeDef()).left() + .value(); + Either<PolicyTypeDefinition, StorageOperationStatus> eitherPolicyTypeFetched = policyTypeOperation + .getLatestPolicyTypeByType(policyTypeCreated.getType()); + assertTrue(eitherPolicyTypeFetched.isLeft()); + PolicyTypeDefinition policyTypeFetched = eitherPolicyTypeFetched.left().value(); + assertEquals(policyTypeFetched.toString(), policyTypeCreated.toString()); + + } + + private PolicyTypeDefinition createPolicyTypeDef() { + PolicyTypeDataDefinition policyTypeDataDefinition = new PolicyTypeDataDefinition(); + policyTypeDataDefinition + .setDescription("description: The TOSCA Policy Type all other TOSCA Policy Types derive from"); + policyTypeDataDefinition.setType("tosca.policies.Root"); + PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeDataDefinition); + policyTypeDefinition.setHighestVersion(true); + policyTypeDefinition.setVersion("1.0"); + return policyTypeDefinition; + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java new file mode 100644 index 0000000000..6caa3044ad --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java @@ -0,0 +1,548 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyRule; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.PropertyData; + +import fj.data.Either; + +public class PropertyOperationTest extends ModelTestBase { + + PropertyOperation propertyOperation = new PropertyOperation(); + + TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + + @Before + public void setup() { + propertyOperation.setTitanGenericDao(titanGenericDao); + + } + + /* + * @Test public void addPropertyToResourceTest() { + * + * String propName = "myProp"; PropertyDefinition property = + * buildPropertyDefinition(); List<PropertyConstraint> constraints = + * buildConstraints(); property.setConstraints(constraints); + * + * PropertyData propertyData = new PropertyData(property, + * propertyOperation.convertConstraintsToString(constraints)); + * + * Either<PropertyData, TitanOperationStatus> either = + * Either.left(propertyData); + * //when(propertyDao.create((GraphNeighbourTable)anyObject(), + * eq(PropertyData.class), eq(NodeTypeEnum.Property))).thenReturn(either); + * GraphRelation graphRelation = new GraphRelation(); Either<GraphRelation, + * TitanOperationStatus> relationResult = Either.left(graphRelation); + * + * when(titanGenericDao.createNode((PropertyData)anyObject(), + * eq(PropertyData.class))).thenReturn(either); + * when(titanGenericDao.createRelation((GraphNode)anyObject(), + * (GraphNode)anyObject(), eq(GraphEdgeLabels.PROPERTY), + * anyMap())).thenReturn(relationResult); + * + * Either<PropertyDefinition, StorageOperationStatus> result = + * propertyOperation.addPropertyToResource(propName, property, + * NodeTypeEnum.Resource, "my-resource.1.0"); + * + * assertTrue(result.isLeft()); System.out.println(result.left().value()); + * PropertyDefinition propertyDefinition = result.left().value(); + * + * List<PropertyConstraint> originalConstraints = property.getConstraints(); + * List<PropertyConstraint> propertyConstraintsResult = + * propertyDefinition.getConstraints(); + * assertEquals(propertyConstraintsResult.size(), + * originalConstraints.size()); + * + * } + */ + private PropertyDefinition buildPropertyDefinition() { + PropertyDefinition property = new PropertyDefinition(); + property.setDefaultValue("10"); + property.setDescription( + "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property.setType(ToscaType.INTEGER.name().toLowerCase()); + return property; + } + + @Test + public void addPropertiesToGraphTableTest() { + + // Map<String, PropertyDefinition> properties = new HashMap<String, + // PropertyDefinition>(); + // String propName = "myProp"; + // PropertyDefinition property = buildPropertyDefinition(); + // + // List<PropertyConstraint> constraints = buildConstraints(); + // property.setConstraints(constraints); + // + // properties.put(propName, property); + // + // GraphNeighbourTable graphNeighbourTable = new GraphNeighbourTable(); + // ResourceData resourceData = new ResourceData(); + // String resourceName = "my-resource"; + // String resourceVersion = "1.0"; + // String resourceId = resourceName + "." + resourceVersion; + // resourceData.setUniqueId(resourceId); + // int resourceIndex = graphNeighbourTable.addNode(resourceData); + // + // heatParametersOperation.addPropertiesToGraphTable(properties, + // graphNeighbourTable, resourceIndex, resourceId); + // + // assertEquals(2, graphNeighbourTable.getNodes().size()); + // assertEquals(1, graphNeighbourTable.getDirectedEdges().size()); + // List<GraphNode> nodes = graphNeighbourTable.getNodes(); + // boolean nodeFound = false; + // for (GraphNode neo4jNode : nodes) { + // if (neo4jNode instanceof PropertyData) { + // PropertyData propertyData = (PropertyData)neo4jNode; + // assertEquals("check property unique id", resourceId + "." + propName, + // propertyData.getUniqueId()); + // assertEquals(property.getDescription(), + // propertyData.getPropertyDataDefinition().getDescription()); + // nodeFound = true; + // } + // } + // assertEquals("looking for PropertyData object in table", true, + // nodeFound); + // + // NodeRelation nodeRelation = + // graphNeighbourTable.getDirectedEdges().get(0); + // assertEquals("check from index to index edge", 0, + // nodeRelation.getFromIndex()); + // assertEquals("check from index to index edge", 1, + // nodeRelation.getToIndex()); + // assertEquals("check edge type", + // GraphEdgePropertiesDictionary.PROPERTY, + // nodeRelation.getEdge().getEdgeType()); + // assertEquals("check propert name on edge", true, + // nodeRelation.getEdge().getProperties().values().contains(propName)); + } + + @Test + public void convertConstraintsTest() { + + List<PropertyConstraint> constraints = buildConstraints(); + List<String> convertedStringConstraints = propertyOperation.convertConstraintsToString(constraints); + assertEquals("constraints size", constraints.size(), convertedStringConstraints.size()); + + List<PropertyConstraint> convertedConstraints = propertyOperation + .convertConstraints(convertedStringConstraints); + assertEquals("check size of constraints", constraints.size(), convertedConstraints.size()); + + Set<String> constraintsClasses = new HashSet<String>(); + for (PropertyConstraint propertyConstraint : constraints) { + constraintsClasses.add(propertyConstraint.getClass().getName()); + } + + for (PropertyConstraint propertyConstraint : convertedConstraints) { + assertTrue("check all classes generated", + constraintsClasses.contains(propertyConstraint.getClass().getName())); + } + } + + @Test + public void testIsPropertyDefaultValueValid_NoDefault() { + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.BOOLEAN.getType()); + assertTrue(propertyOperation.isPropertyDefaultValueValid(property, null)); + } + + @Test + public void testIsPropertyDefaultValueValid_ValidDefault() { + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("50"); + assertTrue(propertyOperation.isPropertyDefaultValueValid(property, null)); + } + + @Test + public void testIsPropertyDefaultValueValid_InvalidDefault() { + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.BOOLEAN.getType()); + property.setDefaultValue("50"); + assertFalse(propertyOperation.isPropertyDefaultValueValid(property, null)); + } + + private List<PropertyConstraint> buildConstraints() { + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + List<String> range = new ArrayList<String>(); + range.add("0"); + range.add("100"); + InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); + constraints.add(propertyConstraint1); + constraints.add(propertyConstraint2); + constraints.add(propertyConstraint3); + return constraints; + } + + @Test + public void findPropertyValueBestMatch1() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", "v1node1", instanceProperty.getValue()); + assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatch2() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceProperty2.setValueUniqueUid("aaaa"); + instanceIdToValue.put("node2", instanceProperty2); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", "v1node2", instanceProperty.getValue()); + assertEquals("check default value", "vv1", instanceProperty.getDefaultValue()); + assertNull("check value unique id is null", instanceProperty.getValueUniqueUid()); + + } + + @Test + public void findPropertyValueBestMatch3() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + instanceProperty1.setValueUniqueUid("aaaa"); + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", "v1node1", instanceProperty.getValue()); + assertEquals("check default value", "v1node3", instanceProperty.getDefaultValue()); + assertEquals("check valid unique id", instanceProperty1.getValueUniqueUid(), + instanceProperty.getValueUniqueUid()); + + } + + @Test + public void findPropertyValueBestMatch1Rules() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule = new PropertyRule(); + String[] ruleArr = { "node1", ".+", "node3" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr)); + propertyRule.setRule(rule1); + propertyRule.setValue("88"); + rules.add(propertyRule); + instanceProperty1.setRules(rules); + + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", propertyRule.getValue(), instanceProperty.getValue()); + assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatch2Rules() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); + + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List<String> rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); + + rules.add(propertyRule2); + rules.add(propertyRule1); + + instanceProperty1.setRules(rules); + + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); + assertEquals("check default value", "v1node2", instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatch1RuleLowLevel() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); + + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List<String> rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); + + rules.add(propertyRule2); + rules.add(propertyRule1); + + instanceProperty1.setRules(rules); + + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + + List<PropertyRule> rules3 = new ArrayList<>(); + PropertyRule propertyRule3 = new PropertyRule(); + String[] ruleArr3 = { "node2", "node3" }; + List<String> rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); + propertyRule3.setRule(rule3); + propertyRule3.setValue("77"); + rules3.add(propertyRule3); + + instanceProperty2.setRules(rules3); + instanceIdToValue.put("node2", instanceProperty2); + + ComponentInstanceProperty instanceProperty3 = new ComponentInstanceProperty(); + instanceProperty3.setValue("v1node3"); + instanceIdToValue.put("node3", instanceProperty3); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); + assertEquals("check default value", propertyRule3.getValue(), instanceProperty.getDefaultValue()); + + } + + @Test + public void findPropertyValueBestMatchDefaultValueNotChanged() { + + String propertyUniqueId = "x1"; + ComponentInstanceProperty instanceProperty = new ComponentInstanceProperty(); + instanceProperty.setValue("v1"); + instanceProperty.setDefaultValue("vv1"); + List<String> path = new ArrayList<>(); + path.add("node1"); + path.add("node2"); + path.add("node3"); + instanceProperty.setPath(path); + + Map<String, ComponentInstanceProperty> instanceIdToValue = new HashMap<String, ComponentInstanceProperty>(); + ComponentInstanceProperty instanceProperty1 = new ComponentInstanceProperty(); + instanceProperty1.setValue("v1node1"); + + List<PropertyRule> rules = new ArrayList<>(); + PropertyRule propertyRule1 = new PropertyRule(); + String[] ruleArr1 = { "node1", "node2", ".+" }; + List<String> rule1 = new ArrayList<>(Arrays.asList(ruleArr1)); + propertyRule1.setRule(rule1); + propertyRule1.setValue("88"); + + PropertyRule propertyRule2 = new PropertyRule(); + String[] ruleArr2 = { "node1", "node2", "node3" }; + List<String> rule2 = new ArrayList<>(Arrays.asList(ruleArr2)); + propertyRule2.setRule(rule2); + propertyRule2.setValue("99"); + + rules.add(propertyRule2); + rules.add(propertyRule1); + + instanceProperty1.setRules(rules); + + instanceIdToValue.put("node1", instanceProperty1); + + ComponentInstanceProperty instanceProperty2 = new ComponentInstanceProperty(); + instanceProperty2.setValue("v1node2"); + + List<PropertyRule> rules3 = new ArrayList<>(); + PropertyRule propertyRule3 = new PropertyRule(); + String[] ruleArr3 = { "node2", "node333" }; + List<String> rule3 = new ArrayList<>(Arrays.asList(ruleArr3)); + propertyRule3.setRule(rule3); + propertyRule3.setValue("77"); + rules3.add(propertyRule3); + + instanceProperty2.setRules(rules3); + instanceIdToValue.put("node2", instanceProperty2); + + propertyOperation.updatePropertyByBestMatch(propertyUniqueId, instanceProperty, instanceIdToValue); + + assertEquals("check value", propertyRule2.getValue(), instanceProperty.getValue()); + assertEquals("check default value", "vv1", instanceProperty.getDefaultValue()); + + } + + // add all rule types + // add rule with size = 1(instance itself = ALL). relevant for VLi. equals + // to X.*.*.* in all paths size +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java new file mode 100644 index 0000000000..fe4b501148 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java @@ -0,0 +1,236 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +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.Map.Entry; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.CapabiltyInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.RequirementImplDef; +import org.openecomp.sdc.be.model.Resource; +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.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.RequirementOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.operations.impl.util.PrintGraph; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class RequirementOperationTest extends ModelTestBase { + private static Logger log = LoggerFactory.getLogger(RequirementOperationTest.class.getName()); + private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + private static String USER_ID = "muserId"; + private static String CATEGORY_NAME = "category/mycategory"; + + private static ConfigurationManager configurationManager; + + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "requirement-operation") + private RequirementOperation requirementOperation; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @javax.annotation.Resource(name = "capability-operation") + private CapabilityOperation capabilityOperation; + + @javax.annotation.Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + @BeforeClass + public static void setupBeforeClass() { + + // configurationManager = new ConfigurationManager( + // new ConfigurationSource() { + // + // @Override + // public <T> T getAndWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // return null; + // } + // + // @Override + // public <T> void addWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // + // } + // }); + // + // Configuration configuration = new Configuration(); + // configuration.setTitanInMemoryGraph(true); + // + // configurationManager.setConfiguration(configuration); + ModelTestBase.init(); + } + + @Test + public void testDummy() { + + assertTrue(requirementOperation != null); + + } + + @Test + public void testAddRequirementNotExistCapability() { + + String reqName = "host"; + RequirementDefinition reqDefinition = new RequirementDefinition(); + reqDefinition.setNode("tosca.nodes.Compute"); + reqDefinition.setRelationship("myrelationship"); + reqDefinition.setCapability("mycapability___2"); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "0.1", null, + true, true); + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation + .addRequirementToResource(reqName, reqDefinition, resource.getUniqueId()); + assertEquals("check error", StorageOperationStatus.INVALID_ID, addRequirementToResource.right().value()); + + } + + @Before + public void createUserAndCategory() { + String[] category = CATEGORY_NAME.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(category[0], category[1], titanDao); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + @Test + public void testAddRequirementWithCapability() { + + String capabilityTypeName = "tosca.nodes.Container"; + + String reqName = "host"; + RequirementDefinition reqDefinition = new RequirementDefinition(); + reqDefinition.setNode("tosca.nodes.Compute"); + reqDefinition.setRelationship("myrelationship"); + reqDefinition.setCapability(capabilityTypeName); + + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + + capabilityTypeOperationTest.createCapability(capabilityTypeName); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "2.0", null, + true, true); + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation + .addRequirementToResource(reqName, reqDefinition, resource.getUniqueId()); + + assertEquals("check requirement was added", true, addRequirementToResource.isLeft()); + + Either<Resource, StorageOperationStatus> resource2 = resourceOperation.getResource(resource.getUniqueId()); + String json = prettyGson.toJson(resource2); + log.debug(json); + } + + private void compareProperties(Map<String, PropertyDefinition> capabilityProperties, + CapabiltyInstance capabiltyInstance, Map<String, String> actual) { + + Map<String, String> properties = capabiltyInstance.getProperties(); + + for (Entry<String, PropertyDefinition> entry : capabilityProperties.entrySet()) { + String paramName = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + String defaultValue = propertyDefinition.getDefaultValue(); + + String value = properties.get(paramName); + + String actualValue = null; + if (actual != null) { + actualValue = actual.get(paramName); + } + if (actualValue != null) { + assertEquals("check property value of key " + paramName, value, actualValue); + } else { + assertEquals("check property value of key " + paramName, value, defaultValue); + } + } + + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java new file mode 100644 index 0000000000..bef51f415c --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java @@ -0,0 +1,2511 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +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.regex.Pattern; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; +import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.RequirementOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.operations.impl.util.PrintGraph; +import org.openecomp.sdc.be.resources.data.ArtifactData; +import org.openecomp.sdc.be.resources.data.HeatParameterData; +import org.openecomp.sdc.be.resources.data.HeatParameterValueData; +import org.openecomp.sdc.be.resources.data.RelationshipInstData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.UniqueIdData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ResourceInstanceOperationTest extends ModelTestBase { + private static Logger log = LoggerFactory.getLogger(ResourceInstanceOperationTest.class.getName()); + private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + private static String USER_ID = "muserId"; + private static String CATEGORY_NAME = "category/mycategory"; + + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "requirement-operation") + private RequirementOperation requirementOperation; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @javax.annotation.Resource(name = "capability-operation") + private CapabilityOperation capabilityOperation; + + @javax.annotation.Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + @javax.annotation.Resource(name = "component-instance-operation") + private ComponentInstanceOperation resourceInstanceOperation; + + @javax.annotation.Resource + private HeatParametersOperation heatParameterOperation; + + @javax.annotation.Resource + private ArtifactOperation artifactOperation; + + private String CAPABILITY_1 = "mycapability101"; + private String CAPABILITY_2 = "mycapability102"; + + private Integer TEST_CLASS_NUMBER = 1; + + public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); + + public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); + + @BeforeClass + public static void setupBeforeClass() { + + // configurationManager = new ConfigurationManager( + // new ConfigurationSource() { + // + // @Override + // public <T> T getAndWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // return null; + // } + // + // @Override + // public <T> void addWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // + // } + // }); + // + // Configuration configuration = new Configuration(); + // + // ////inmemory + // boolean useInMemory = true; + // if (useInMemory) { + // configuration.setTitanInMemoryGraph(true); + // } else { + // configuration.setTitanInMemoryGraph(false); + // configuration.setTitanCfgFile("C:\\Git_work\\D2-SDnC\\catalog-be\\src\\main\\resources\\config\\titan.properties"); + // } + // + // + // + // configurationManager.setConfiguration(configuration); + ModelTestBase.init(); + } + + public void setOperations(TitanGenericDao titanDao, CapabilityTypeOperation capabilityTypeOperation, + RequirementOperation requirementOperation, CapabilityOperation capabilityOperation, + ResourceOperation resourceOperation, PropertyOperation propertyOperation, + ComponentInstanceOperation resourceInstanceOperation2) { + this.titanDao = titanDao; + this.capabilityTypeOperation = capabilityTypeOperation; + this.capabilityOperation = capabilityOperation; + this.requirementOperation = requirementOperation; + this.resourceOperation = resourceOperation; + this.propertyOperation = propertyOperation; + this.resourceInstanceOperation = resourceInstanceOperation2; + } + + @Test + public void testDummy() { + + assertTrue(requirementOperation != null); + + } + + @Test + public void testAddResourceInstanceInvalidServiceId() { + + try { + ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache"); + + Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation + .addComponentInstanceToContainerComponent("service1", NodeTypeEnum.Service, "1", true, instance, + NodeTypeEnum.Resource, false); + assertEquals("check failed status - service is not in graph", true, status.isRight()); + assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, + status.right().value()); + } finally { + titanDao.rollback(); + } + + } + + @Test + public void testAddResourceInstanceValidServiceIdInvalidResourceId() { + try { + + ServiceMetadataData serviceData1 = createService("myservice1.1.0"); + + ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache"); + + Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation + .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, + "1", true, instance, NodeTypeEnum.Resource, false); + + assertEquals("check failed status - service is not in graph", true, status.isRight()); + assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, + status.right().value()); + + } finally { + titanDao.rollback(); + } + + } + + @Test + public void testAddResourceInstanceValidServiceId() { + try { + String serviceName = "myservice1.1.0"; + String resourceName = "tosca.nodes.Apache.2.0"; + ServiceMetadataData serviceData1 = createService(serviceName); + ResourceMetadataData resourceData = createResource(resourceName); + + ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), + "1", "tosca.nodes.Apache"); + + Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation + .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, + "1", true, instance, NodeTypeEnum.Resource, false); + + assertEquals("check success status - service is not in graph", true, status.isLeft()); + + ComponentInstance value = status.left().value(); + assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName()); + + ServiceMetadataData serviceData2 = deleteService(serviceName); + ResourceMetadataData resourceData2 = deleteResource(resourceName); + + } finally { + titanDao.rollback(); + } + } + + @Test + public void testUpdateResourceInstance() { + try { + String serviceName = "myservice1.1.0"; + String resourceName = "tosca.nodes.Apache.2.0"; + ServiceMetadataData serviceData1 = createService(serviceName); + ResourceMetadataData resourceData = createResource(resourceName); + + ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), + "1", "tosca.nodes.Apache"); + + Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation + .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, + "1", true, instance, NodeTypeEnum.Resource, false); + + ComponentInstance resourceInstance = status.left().value(); + Long creationTime = resourceInstance.getCreationTime(); + String name = resourceInstance.getName(); + assertEquals("check success status - service is not in graph", true, status.isLeft()); + + ComponentInstance value = status.left().value(); + assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName()); + + Either<ComponentInstance, StorageOperationStatus> u1Res = resourceInstanceOperation.updateResourceInstance( + (String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, + true); + assertTrue("check update succeed", u1Res.isLeft()); + + Long lastModificationTimeNC = value.getModificationTime(); + String desc = "AAAAA"; + String posX = "15"; + String posY = "12"; + String updatedName = "Shlokshlik"; + value.setDescription(desc); + value.setPosX(posX); + Either<ComponentInstance, StorageOperationStatus> u2Res = resourceInstanceOperation.updateResourceInstance( + (String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, + true); + assertTrue("check update succeed", u2Res.isLeft()); + assertEquals("check resource instance updated", desc, u2Res.left().value().getDescription()); + assertEquals("check resource instance updated", posX, u2Res.left().value().getPosX()); + assertEquals("check resource instance updated", resourceInstance.getPosY(), u2Res.left().value().getPosY()); + assertEquals("check modification time was not updated since it was supplied", + u2Res.left().value().getModificationTime(), lastModificationTimeNC); + + Long lastModificationTime = value.getModificationTime(); + value.setPosY(posY); + value.setModificationTime(null); + value.setName(updatedName); + Either<ComponentInstance, StorageOperationStatus> u3Res = resourceInstanceOperation.updateResourceInstance( + (String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, + true); + assertTrue("check update succeed", u3Res.isLeft()); + assertEquals("check resource instance updated", desc, u3Res.left().value().getDescription()); + assertEquals("check resource pos x updated", posX, u3Res.left().value().getPosX()); + assertEquals("check resource pos y updated", posY, u3Res.left().value().getPosY()); + assertTrue("check modification time was updated", + u3Res.left().value().getModificationTime() >= lastModificationTime); + assertEquals("check creation time was not updated", creationTime, u3Res.left().value().getCreationTime()); + assertEquals("check name was updated", updatedName, u3Res.left().value().getName()); + + ServiceMetadataData serviceData2 = deleteService(serviceName); + ResourceMetadataData resourceData2 = deleteResource(resourceName); + + } finally { + titanDao.rollback(); + } + } + + @Test + public void testRemoveResourceInstance() { + try { + String serviceName = "myservice1.1.0"; + String resourceName = "tosca.nodes.Apache.2.0"; + ServiceMetadataData serviceData1 = createService(serviceName); + ResourceMetadataData resourceData = createResource(resourceName); + + ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), + "1", "tosca.nodes.Apache"); + + Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation + .addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, + "1", true, instance, NodeTypeEnum.Resource, false); + + assertEquals("check success status - service is not in graph", true, status.isLeft()); + + ComponentInstance value = status.left().value(); + assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName()); + + Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation + .removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, value.getUniqueId()); + + assertTrue("check resource service was deleted.", status1.isLeft()); + assertEquals("check resource instance returned.", "tosca.nodes.Apache 1", status1.left().value().getName()); + + ServiceMetadataData serviceData2 = deleteService(serviceName); + ResourceMetadataData resourceData2 = deleteResource(resourceName); + + } finally { + titanDao.rollback(); + } + } + + @Test + public void testRemoveResourceInstanceNotFound() { + try { + String serviceName = "myservice1.1.0"; + ServiceMetadataData serviceData1 = createService(serviceName); + + Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation + .removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, "stam"); + + assertTrue("check resource service was not deleted.", status1.isRight()); + assertEquals("check NOT_FOUND returned.", TitanOperationStatus.NOT_FOUND, status1.right().value()); + + ServiceMetadataData serviceData2 = deleteService(serviceName); + + } finally { + titanDao.rollback(); + } + } + + public ServiceMetadataData createService(String serviceName) { + + ServiceMetadataData serviceData1 = new ServiceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(serviceName); + Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, + ServiceMetadataData.class); + + assertTrue("check service created", createNode.isLeft()); + return createNode.left().value(); + } + + public ServiceMetadataData deleteService(String serviceName) { + + ServiceMetadataData serviceData1 = new ServiceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(serviceName); + Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1, + ServiceMetadataData.class); + assertTrue("check service deleted", createNode.isLeft()); + return createNode.left().value(); + } + + public ResourceMetadataData createResource(String resourceName) { + + ResourceMetadataData serviceData1 = new ResourceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); + Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, + ResourceMetadataData.class); + + assertTrue("check service created", createNode.isLeft()); + return createNode.left().value(); + } + + public ResourceMetadataData deleteResource(String resourceName) { + + ResourceMetadataData serviceData1 = new ResourceMetadataData(); + serviceData1.getMetadataDataDefinition().setUniqueId(resourceName); + Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1, + ResourceMetadataData.class); + + assertTrue("check service created", createNode.isLeft()); + return createNode.left().value(); + } + + @Test + public void testAddResourceInstanceJson() { + addResourceInstanceJson(); + } + + public ComponentInstance addResourceInstanceJson() { + + ComponentInstance resourceInstance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache"); + + String json = prettyGson.toJson(resourceInstance); + log.debug(json); + + return resourceInstance; + + } + + private ComponentInstance buildResourceInstance(String respurceUid, String instanceNumber, String name) { + ComponentInstance resourceInstance = new ComponentInstance(); + // resourceInstance + // .setUniqueId("<SN>.tosca.nodes.Apache.2.0." + instanceNumber); + resourceInstance.setName(name); + resourceInstance.setDescription("desc1"); + resourceInstance.setPosX("20"); + resourceInstance.setPosY("40"); + resourceInstance.setComponentUid(respurceUid); + resourceInstance.setCreationTime(System.currentTimeMillis()); + resourceInstance.setModificationTime(System.currentTimeMillis()); + resourceInstance.setNormalizedName(normaliseComponentName(name)); + + // Map<String, RequirementInstance> requirements = new HashMap<String, + // RequirementInstance>(); + // + // RequirementInstance requirementInstance1 = new RequirementInstance(); + // requirementInstance1.setNode("NA"); + // RelationshipImpl relationshipImpl = new RelationshipImpl(); + // relationshipImpl.setType("tosca.relationships.HostedOn"); + // requirementInstance1.setRelationship(relationshipImpl); + // + // requirements.put("host", requirementInstance1); + // + // RequirementInstance requirementInstance2 = new RequirementInstance(); + // requirementInstance2.setNode("NA"); + // RelationshipImpl relationshipImpl2 = new RelationshipImpl(); + // relationshipImpl2.setType("tosca.relationships.LinkTo"); + // requirementInstance2.setRelationship(relationshipImpl2); + // + // requirements.put("link", requirementInstance2); + // + // resourceInstance.setRequirements(requirements); + return resourceInstance; + } + + @Test + public void testConenctResourceInstancesJson() { + RequirementCapabilityRelDef addRelationship = addRelationship("apache_1", "compute_100"); + String json = prettyGson.toJson(addRelationship); + log.debug(json); + + RequirementCapabilityRelDef capabilityRelDef = prettyGson.fromJson(json, RequirementCapabilityRelDef.class); + log.debug("{}", capabilityRelDef); + + } + + public RequirementCapabilityRelDef addRelationship(String from, String to) { + RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); + requirementCapabilityRelDef.setFromNode(from); + requirementCapabilityRelDef.setToNode(to); + List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>(); + + String req = "host"; + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType("tosca.nodes.HostedOn"); + RequirementAndRelationshipPair rels = new RequirementAndRelationshipPair(req, relationshipImpl); + relationships.add(rels); + + requirementCapabilityRelDef.setRelationships(relationships); + + return requirementCapabilityRelDef; + } + + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID); + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); + + /* + * CategoryData categoryData = new CategoryData(); + * categoryData.setName(category); + * + * titanDao.deleteNode(categoryData, CategoryData.class); + * Either<CategoryData, TitanOperationStatus> createNode = titanDao + * .createNode(categoryData, CategoryData.class); + * System.out.println("after creating caetgory " + createNode); + */ + } + + @Test + @Ignore + public void testConnectResourceInstances() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + try { + + String capabilityTypeName = CAPABILITY_2; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest + .createCapability(capabilityTypeName); + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + // rollbackAndPrint(); + + // Add capabilities to Compute Resource + CapabilityDefinition addCapability = addCapabilityToResource(capabilityTypeName, "host", computeComponent); + + // CapabilityDefinition capabilityDefinition = new + // CapabilityDefinition(); + // capabilityDefinition.setDescription("my capability"); + // capabilityDefinition.setType(capabilityTypeName); + // List<String> validSourceTypes = new ArrayList<String>(); + // validSourceTypes.add("tosca.nodes.SC"); + // capabilityDefinition.setValidSourceTypes(validSourceTypes); + // Either<CapabilityDefinition, StorageOperationStatus> + // addCapability = capabilityOperation + // .addCapability(computeComponent.getUniqueId(), "host", + // capabilityDefinition, true); + // //logger.debug("addCapability result " + addCapability); + // assertTrue("check capability created ", addCapability.isLeft()); + // + // ============================================= + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceName = "myservice.1.0"; + List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, + computeComponent, "host", false, addCapability.getUniqueId(), + addRequirementToResource.left().value().getUniqueId()); + + PrintGraph printGraph = new PrintGraph(); + String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); + log.debug(webGraph); + + Either<Resource, StorageOperationStatus> resourceFull = resourceOperation + .getResource(resource.getUniqueId()); + assertTrue(resourceFull.isLeft()); + List<RequirementCapabilityRelDef> componentInstancesRelations = resourceFull.left().value() + .getComponentInstancesRelations(); + + RequirementCapabilityRelDef capabilityRelDef = componentInstancesRelations.get(0); + capabilityRelDef.getRelationships().get(0).setRequirement("host"); + + // disconnectResourcesInService(serviceName, resInstances.get(0), + // "host"); + disconnectResourcesInService(serviceName, capabilityRelDef); + + } finally { + rollbackAndPrint(false); + compareGraphSize(numberOfVertices); + } + + } + + @Test + @Ignore + public void testConnectResourceInstances1Requirement2Capabilities() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + + try { + + String capabilityTypeName1 = CAPABILITY_1; + String capabilityTypeName2 = CAPABILITY_2; + String reqName1 = "host1"; + String reqName2 = "host2"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest + .createCapability(capabilityTypeName1); + CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest + .createCapability(capabilityTypeName2); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + // Add capabilities to Compute Resource + CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent); + CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent); + + // rollbackAndPrint(); + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent); + + String requirementId = addRequirementToResource.left().value().getUniqueId(); + String parentReqUniqId = requirementId; + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceName = "myservice.1.0"; + List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, + computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId); + + PrintGraph printGraph = new PrintGraph(); + String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); + log.debug(webGraph); + + RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); + relationPair.setRequirement(reqName2); + + relationPair.setCapabilityUid(capabilty1.getUniqueId()); + relationPair.setRequirementUid(requirementId); + + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation + .connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), + resInstances.get(1).getUniqueId(), relationPair); + assertEquals("check cannot associate resource instances", TitanOperationStatus.ILLEGAL_ARGUMENT, + connectResourcesInService1.right().value()); + relationPair.setRequirement(reqName1); + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation + .connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), + resInstances.get(1).getUniqueId(), relationPair); + assertEquals("check cannot associate resource instances", TitanOperationStatus.TITAN_SCHEMA_VIOLATION, + connectResourcesInService2.right().value()); + + relationPair.setRequirement(reqName1); + + RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef(); + capabilityRelDef.setFromNode(resInstances.get(0).getUniqueId()); + capabilityRelDef.setToNode(resInstances.get(1).getUniqueId()); + List<RequirementAndRelationshipPair> list = new ArrayList<>(); + list.add(relationPair); + + disconnectResourcesInService(serviceName, capabilityRelDef); + + } finally { + rollbackAndPrint(); + compareGraphSize(numberOfVertices); + } + + } + + private void rollbackAndPrint() { + rollbackAndPrint(false); + } + + private void rollbackAndPrint(boolean print) { + TitanOperationStatus rollback = titanDao.rollback(); + if (print) { + log.debug("rollback status={}", rollback); + PrintGraph printGraph = new PrintGraph(); + printGraph.printGraphVertices(titanDao.getGraph().left().value()); + } + } + + @Test + public void testConnectResourceInstances2Requirement2Capabilities() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + + try { + + String capabilityTypeName1 = CAPABILITY_1; + String capabilityTypeName2 = CAPABILITY_2; + String reqName1 = "host1"; + String reqName2 = "host2"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest + .createCapability(capabilityTypeName1); + CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest + .createCapability(capabilityTypeName2); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // rollbackAndPrint(); + // OKKKKKKK + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + // rollbackAndPrint(); + // OKKKKKKKKKK + + // Add capabilities to Compute Resource + CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent); + CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent); + + // rollbackAndPrint(); + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource1 = addRequirementToResource( + capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent); + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource2 = addRequirementToResource( + capabilityTypeName2, reqName2, reqNodeName, reqRelationship, softwareComponent); + + // create my resource derived from software component + String MY_RESOURCE = "my-resource"; + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, MY_RESOURCE, + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceName = "myservice.1.0"; + String requirementId1 = addRequirementToResource1.left().value().getUniqueId(); + String requirementId2 = addRequirementToResource2.left().value().getUniqueId(); + List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, + computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId1); + + RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); + relationPair.setRequirement(reqName2); + relationPair.setCapabilityUid(capabilty2.getUniqueId()); + relationPair.setRequirementUid(requirementId2); + relationPair.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); + relationPair.setRequirementOwnerId(resInstances.get(0).getUniqueId()); + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation + .connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), + resInstances.get(1).getUniqueId(), relationPair); + assertTrue("check associate resource instances succeed " + reqName2, connectResourcesInService1.isLeft()); + + // rollbackAndPrint(); + + PrintGraph printGraph = new PrintGraph(); + String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); + log.debug(webGraph); + + RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef(); + reqCapDef.setFromNode(resInstances.get(0).getUniqueId()); + reqCapDef.setToNode(resInstances.get(1).getUniqueId()); + + relationPair.setRequirement(reqName1); + relationPair.setCapabilityUid(capabilty1.getUniqueId()); + relationPair.setRequirementUid(requirementId1); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(reqName1); + relationPair.setRelationships(relationship); + + List<RequirementAndRelationshipPair> list = new ArrayList<>(); + list.add(relationPair); + reqCapDef.setRelationships(list); + + disconnectResourcesInService(serviceName, reqCapDef); + + reqCapDef.getRelationships().clear(); + + RequirementAndRelationshipPair relationPair1 = new RequirementAndRelationshipPair(); + relationPair1.setRequirement(reqName2); + relationPair1.setCapabilityUid(capabilty2.getUniqueId()); + relationPair1.setRequirementUid(requirementId2); + relationPair1.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); + relationPair1.setRequirementOwnerId(resInstances.get(0).getUniqueId()); + relationship.setType(reqName2); + relationPair1.setRelationships(relationship); + reqCapDef.getRelationships().add(relationPair1); + + disconnectResourcesInService(serviceName, reqCapDef); + + RequirementCapabilityRelDef relation = new RequirementCapabilityRelDef(); + String fromResUid = resInstances.get(0).getUniqueId(); + String toResUid = resInstances.get(1).getUniqueId(); + relation.setFromNode(fromResUid); + relation.setToNode(toResUid); + List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>(); + RequirementAndRelationshipPair immutablePair1 = new RequirementAndRelationshipPair(reqName1, null); + RequirementAndRelationshipPair immutablePair2 = new RequirementAndRelationshipPair(reqName2, null); + immutablePair1.setCapabilityUid(capabilty1.getUniqueId()); + immutablePair1.setRequirementUid(addRequirementToResource1.left().value().getUniqueId()); + immutablePair1.setRequirementOwnerId(resInstances.get(0).getUniqueId()); + immutablePair1.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); + + immutablePair2.setCapabilityUid(capabilty2.getUniqueId()); + immutablePair2.setRequirementUid(addRequirementToResource2.left().value().getUniqueId()); + immutablePair2.setRequirementOwnerId(resInstances.get(0).getUniqueId()); + immutablePair2.setCapabilityOwnerId(resInstances.get(1).getUniqueId()); + + relationships.add(immutablePair1); + relationships.add(immutablePair2); + relation.setRelationships(relationships); + + Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances = resourceInstanceOperation + .associateResourceInstances(serviceName, NodeTypeEnum.Service, relation, true); + assertTrue("check return code after associating 2 requirements in one request", + associateResourceInstances.isLeft()); + RequirementCapabilityRelDef capabilityRelDef = associateResourceInstances.left().value(); + String fromNode = capabilityRelDef.getFromNode(); + assertEquals("check from node", resInstances.get(0).getUniqueId(), fromNode); + String toNode = capabilityRelDef.getToNode(); + assertEquals("check to node", resInstances.get(1).getUniqueId(), toNode); + List<RequirementAndRelationshipPair> relationships2 = capabilityRelDef.getRelationships(); + assertEquals("check number of relations", 2, relationships2.size()); + + for (RequirementAndRelationshipPair pair : relationships2) { + String key = pair.getRequirement(); + RelationshipImpl relationshipImpl = pair.getRelationship(); + if (key.equals(reqName1)) { + String type = relationshipImpl.getType(); + assertEquals("Check relationship type name", reqRelationship, type); + } else if (key.equals(reqName2)) { + String type = relationshipImpl.getType(); + assertEquals("Check relationship type name", reqRelationship, type); + } else { + assertTrue("requirement " + key + " was not found in the original request", false); + } + } + + verifyGetAllResourceInstanceFromService(reqName1, reqName2, serviceName, fromResUid, toResUid); + + List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>(); + TitanOperationStatus findResourcesPathRecursively = resourceOperation + .findResourcesPathRecursively(resource.getUniqueId(), resourcesPathList); + assertEquals("check returned status", TitanOperationStatus.OK, findResourcesPathRecursively); + assertEquals("check list size", 3, resourcesPathList.size()); + + TitanOperationStatus validateTheTargetResourceInstance = resourceInstanceOperation + .validateTheTargetResourceInstance(MY_RESOURCE, resource.getUniqueId()); + assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance); + validateTheTargetResourceInstance = resourceInstanceOperation + .validateTheTargetResourceInstance(softwareCompName, resource.getUniqueId()); + assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance); + + validateTheTargetResourceInstance = resourceInstanceOperation + .validateTheTargetResourceInstance(softwareCompName + "STAM", resource.getUniqueId()); + assertEquals("check resource name not in the path", TitanOperationStatus.MATCH_NOT_FOUND, + validateTheTargetResourceInstance); + + Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation + .deleteComponentInstance(NodeTypeEnum.Service, serviceName, toResUid, true); + assertTrue("check resource instance was deleted.", deleteResourceInstance.isLeft()); + + } finally { + rollbackAndPrint(false); + compareGraphSize(numberOfVertices); + } + + } + + private void verifyGetAllResourceInstanceFromService(String reqName1, String reqName2, String serviceName, + String fromResUid, String toResUid) { + + Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation + .getAllComponentInstances(serviceName, NodeTypeEnum.Service, NodeTypeEnum.Resource, true); + // assertTrue("check return code after get all resource instances", + // associateResourceInstances.isLeft()); + ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances + .left().value(); + List<ComponentInstance> nodes = immutablePair.getKey(); + List<RequirementCapabilityRelDef> edges = immutablePair.getValue(); + assertEquals("check 2 nodes returned", 2, nodes.size()); + assertEquals("check one relation returned", 1, edges.size()); + RequirementCapabilityRelDef requirementCapabilityRelDef = edges.get(0); + assertEquals("check from node", requirementCapabilityRelDef.getFromNode(), fromResUid); + requirementCapabilityRelDef.getToNode(); + assertEquals("check to node", requirementCapabilityRelDef.getToNode(), toResUid); + int size = requirementCapabilityRelDef.getRelationships().size(); + assertEquals("check number of relations", 2, size); + String req1 = requirementCapabilityRelDef.getRelationships().get(0).getRequirement(); + String req2 = requirementCapabilityRelDef.getRelationships().get(1).getRequirement(); + + List<String> requirements = new ArrayList<String>(); + requirements.add(req1); + requirements.add(req2); + + assertTrue("check requirement returned " + reqName1, requirements.contains(reqName1)); + assertTrue("check requirement returned " + reqName2, requirements.contains(reqName2)); + + String nodesStr = prettyGson.toJson(nodes); + String edgesStr = prettyGson.toJson(edges); + + log.debug(nodesStr); + log.debug(edgesStr); + } + + private Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String capabilityTypeName1, + String reqName1, String reqNodeName, String reqRelationship, Resource softwareComponent) { + RequirementDefinition reqDefinition1 = new RequirementDefinition(); + reqDefinition1.setNode(reqNodeName); + reqDefinition1.setRelationship(reqRelationship); + reqDefinition1.setCapability(capabilityTypeName1); + // add requirement to software component + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation + .addRequirementToResource(reqName1, reqDefinition1, softwareComponent.getUniqueId(), true); + assertEquals("check requirement was added", true, addRequirementToResource.isLeft()); + return addRequirementToResource; + } + + private CapabilityDefinition addCapabilityToResource(String capabilityTypeName1, String reqName1, + Resource computeComponent) { + CapabilityDefinition capabilityDefinition1 = new CapabilityDefinition(); + capabilityDefinition1.setDescription("my capability"); + capabilityDefinition1.setType(capabilityTypeName1); + List<String> validSourceTypes = new ArrayList<String>(); + validSourceTypes.add("tosca.nodes.SC"); + capabilityDefinition1.setValidSourceTypes(validSourceTypes); + Either<CapabilityDefinition, StorageOperationStatus> addCapability = capabilityOperation + .addCapability(computeComponent.getUniqueId(), reqName1, capabilityDefinition1, true); + assertTrue("check capability created ", addCapability.isLeft()); + return addCapability.left().value(); + } + + @Test + public void testConnectResourceInstancesCapabilityNameDiffFromReqName() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + + try { + + String capabilityTypeName = CAPABILITY_2; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + String DIFFERENT_CAPABILITY = "hostDiffernet"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest + .createCapability(capabilityTypeName); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + CapabilityDefinition capabilty = addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, + computeComponent); + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceName = "myservice.1.0"; + List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, + computeComponent, "host", false, capabilty.getUniqueId(), parentReqUniqId); + + PrintGraph printGraph = new PrintGraph(); + String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); + // log.debug(webGraph); + + } finally { + rollbackAndPrint(); + + compareGraphSize(numberOfVertices); + } + + } + + @Test + public void testConnectResourceInstancesInvalidCapability() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + + try { + + String capabilityTypeName = CAPABILITY_2; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + String capabilityTypeNameOther = CAPABILITY_2 + "othertype"; + + String DIFFERENT_CAPABILITY = "hostDiffernet"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest + .createCapability(capabilityTypeName); + + CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest + .createCapability(capabilityTypeNameOther); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent); + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeNameOther, reqName, reqNodeName, reqRelationship, softwareComponent); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceName = "myservice.1.0"; + List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, + resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT); + + PrintGraph printGraph = new PrintGraph(); + String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); + log.debug(webGraph); + + } finally { + rollbackAndPrint(); + + compareGraphSize(numberOfVertices); + } + + } + + private void compareGraphSize(int numberOfVertices, Set<String> toRemoveFromSet) { + PrintGraph printGraph2 = new PrintGraph(); + int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value()); + + Set<String> set = printGraph2.getVerticesSet(titanDao.getGraph().left().value()); + if (toRemoveFromSet != null) { + set.removeAll(toRemoveFromSet); + } + + assertEquals("check all data deleted from graph " + set, numberOfVertices, numberOfVerticesCurr); + } + + private void compareGraphSize(int numberOfVertices) { + PrintGraph printGraph2 = new PrintGraph(); + int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value()); + + assertEquals( + "check all data deleted from graph " + printGraph2.getVerticesSet(titanDao.getGraph().left().value()), + numberOfVertices, numberOfVerticesCurr); + } + + @Test + public void testConnectResourceInstancesRequirementNotFound() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + try { + + String capabilityTypeName = CAPABILITY_2; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + String DIFFERENT_CAPABILITY = "hostDiffernet"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest + .createCapability(capabilityTypeName); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + addCapabilityToResource(capabilityTypeName, reqName, computeComponent); + + // create requirement definition + + RequirementDefinition reqDefinition = new RequirementDefinition(); + reqDefinition.setNode(reqNodeName); + reqDefinition.setRelationship(reqRelationship); + reqDefinition.setCapability(capabilityTypeName); + // add requirement to software component + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation + .addRequirementToResource(reqName + "ssssssss", reqDefinition, softwareComponent.getUniqueId(), + true); + assertEquals("check requirement was added", true, addRequirementToResource.isLeft()); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceName = "myservice.1.0"; + List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, + resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT); + + PrintGraph printGraph = new PrintGraph(); + String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value()); + log.debug(webGraph); + + } finally { + titanDao.rollback(); + + compareGraphSize(numberOfVertices); + } + + } + + private void disconnectResourcesInService(String serviceName, RequirementCapabilityRelDef reqCapDef) { + + Either<List<RelationshipInstData>, TitanOperationStatus> disconnectResourcesInService = resourceInstanceOperation + .disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef); + assertTrue("check relatioship instance was deleted", disconnectResourcesInService.isLeft()); + + disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, + NodeTypeEnum.Service, reqCapDef); + assertTrue("check relatioship instance already was deleted", disconnectResourcesInService.isRight()); + assertEquals("check relatioship instance already was deleted. status NOT_FOUND", TitanOperationStatus.NOT_FOUND, + disconnectResourcesInService.right().value()); + } + + private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstancesWithError(String serviceName, + Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService, + TitanOperationStatus titanOperationStatus) { + + String serviceId = "myservice.1.0"; + + if (false == ignoreCreatingService) { + ServiceMetadataData createService = createService(serviceId); + } + ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName()); + + ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", + computeComponent.getName()); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", myinstanceRes.isLeft()); + ComponentInstance value1 = myinstanceRes.left().value(); + Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, + NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", computeInstTes.isLeft()); + ComponentInstance value2 = computeInstTes.left().value(); + + RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); + relationPair.setRequirement(requirement); + + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation + .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), + relationPair); + + assertTrue("check relation was not created", connectResourcesInService.isRight()); + assertEquals("check error code after connect resource instances failed", titanOperationStatus, + connectResourcesInService.right().value()); + + List<ComponentInstance> resInstances = new ArrayList<ComponentInstance>(); + resInstances.add(value1); + + return resInstances; + + } + + private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstances(String serviceName, + Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService, + String capabilityId, String requirementId) { + + String serviceId = "myservice.1.0"; + + if (false == ignoreCreatingService) { + ServiceMetadataData createService = createService(serviceId); + } + ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName()); + + ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", + computeComponent.getName()); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", myinstanceRes.isLeft()); + ComponentInstance value1 = myinstanceRes.left().value(); + Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, + NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", computeInstTes.isLeft()); + ComponentInstance value2 = computeInstTes.left().value(); + RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); + relationPair.setRequirement(requirement); + + relationPair.setCapabilityUid(capabilityId); + relationPair.setRequirementUid(requirementId); + relationPair.setRequirementOwnerId(value1.getUniqueId()); + relationPair.setCapabilityOwnerId(value2.getUniqueId()); + + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation + .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), + relationPair); + + assertTrue("check relation created", connectResourcesInService.isLeft()); + + List<ComponentInstance> resInstances = new ArrayList<ComponentInstance>(); + resInstances.add(value1); + resInstances.add(value2); + + return resInstances; + + } + + @Test + public void getAllResourceInstancesThree() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + try { + + Set<String> vertexSetBeforeMethod = printGraph1.getVerticesSet(titanDao.getGraph().left().value()); + + String capabilityTypeName = CAPABILITY_2; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest + .createCapability(capabilityTypeName); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + // rollbackAndPrint(); + + // Add capabilities to Compute Resource + CapabilityDefinition capability = addCapabilityToResource(capabilityTypeName, "host", computeComponent); + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceId = "myservice.1.0"; + + ServiceMetadataData createService = createService(serviceId); + + Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation + .getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true); + assertTrue("check NOT_FOUND is returned", allResourceInstances.isRight()); + assertEquals("check NOT_FOUND is returned", allResourceInstances.right().value(), + StorageOperationStatus.NOT_FOUND); + + ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource"); + myresourceInstance.setName("my-resource"); + + ComponentInstance computeInstance1 = buildResourceInstance(computeComponent.getUniqueId(), "2", + "tosca.nodes.Compute2"); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", myinstanceRes.isLeft()); + ComponentInstance value1 = myinstanceRes.left().value(); + + allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, + NodeTypeEnum.Resource, true); + assertTrue("check resource instances found", allResourceInstances.isLeft()); + ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances + .left().value(); + List<ComponentInstance> nodes = immutablePair.getKey(); + List<RequirementCapabilityRelDef> edges = immutablePair.getValue(); + + assertEquals("check resource instances size", 1, nodes.size()); + assertEquals("check resource instances size", 0, edges.size()); + + Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, + computeInstance1, NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", computeInstTes.isLeft()); + ComponentInstance value2 = computeInstTes.left().value(); + + allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, + NodeTypeEnum.Resource, true); + assertTrue("check resource instances found", allResourceInstances.isLeft()); + immutablePair = allResourceInstances.left().value(); + nodes = immutablePair.getKey(); + edges = immutablePair.getValue(); + + assertEquals("check resource instances size", 2, nodes.size()); + assertEquals("check resource instances size", 0, edges.size()); + + String requirement = "host"; + RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); + relationPair.setRequirement(requirement); + relationPair.setCapabilityUid(capability.getUniqueId()); + relationPair.setRequirementUid(addRequirementToResource.left().value().getUniqueId()); + relationPair.setRequirementOwnerId(value1.getUniqueId()); + relationPair.setCapabilityOwnerId(value2.getUniqueId()); + + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation + .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), + value2.getUniqueId(), relationPair); + + assertTrue("check relation created", connectResourcesInService.isLeft()); + + allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, + NodeTypeEnum.Resource, true); + assertTrue("check resource instances found", allResourceInstances.isLeft()); + immutablePair = allResourceInstances.left().value(); + nodes = immutablePair.getKey(); + edges = immutablePair.getValue(); + + assertEquals("check resource instances size", 2, nodes.size()); + assertEquals("check resource instances size", 1, edges.size()); + + List<ComponentInstance> resInstances2 = new ArrayList<ComponentInstance>(); + resInstances2.add(value1); + resInstances2.add(value2); + + ComponentInstance myresourceInstance2 = buildResourceInstance(resource.getUniqueId(), "1", "myresource2"); + + Either<ComponentInstance, TitanOperationStatus> newResource = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "3", true, + myresourceInstance2, NodeTypeEnum.Resource, false); + + assertTrue("added resource instance successfully", newResource.isLeft()); + + relationPair.setRequirement(requirement); + relationPair.setRequirementOwnerId(newResource.left().value().getUniqueId()); + + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation + .connectResourcesInService(serviceId, NodeTypeEnum.Service, + newResource.left().value().getUniqueId(), value2.getUniqueId(), relationPair); + assertTrue("check resource instance was added to service", connectResourcesInService2.isLeft()); + + allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, + NodeTypeEnum.Resource, true); + assertTrue("check resource instances found", allResourceInstances.isLeft()); + immutablePair = allResourceInstances.left().value(); + nodes = immutablePair.getKey(); + edges = immutablePair.getValue(); + + assertEquals("check resource instances size", 3, nodes.size()); + assertEquals("check resource instances size", 2, edges.size()); + + Either<List<ComponentInstance>, TitanOperationStatus> deleteAllResourceInstancesOfService = resourceInstanceOperation + .deleteAllComponentInstancesInternal(serviceId, NodeTypeEnum.Service); + assertTrue("check resource instances was deleted.", deleteAllResourceInstancesOfService.isLeft()); + assertEquals("check number of deleted resource instances.", 3, + deleteAllResourceInstancesOfService.left().value().size()); + + Either<List<RelationshipInstData>, TitanOperationStatus> allRelatinshipInst = titanDao + .getAll(NodeTypeEnum.RelationshipInst, RelationshipInstData.class); + assertTrue("allRelatinshipInst is empty", allRelatinshipInst.isRight()); + assertEquals("allRelatinshipInst result is NOT_FOUND", TitanOperationStatus.NOT_FOUND, + allRelatinshipInst.right().value()); + + Either<Resource, StorageOperationStatus> deleteComputeResource = resourceOperation + .deleteResource(computeComponent.getUniqueId(), true); + assertTrue("delete compute resource succeed", deleteComputeResource.isLeft()); + + Either<Resource, StorageOperationStatus> deleteSCResource = resourceOperation + .deleteResource(softwareComponent.getUniqueId(), true); + assertTrue("delete software component resource succeed", deleteSCResource.isLeft()); + + Either<Resource, StorageOperationStatus> deleteMyResource = resourceOperation + .deleteResource(resource.getUniqueId(), true); + assertTrue("delete my resource succeed", deleteMyResource.isLeft()); + + Either<Resource, StorageOperationStatus> rootResourceDeleted = resourceOperation + .deleteResource(rootResource.getUniqueId(), true); + assertTrue("delete root resource succeed", rootResourceDeleted.isLeft()); + + Set<String> vertexSetAfterDelete = printGraph1.getVerticesSet(titanDao.getGraph().left().value()); + + vertexSetAfterDelete.removeAll(vertexSetBeforeMethod); + + log.debug("vertexSetAfterDelete={}", vertexSetAfterDelete); + log.debug("vertexSetAfterDelete size={}", vertexSetAfterDelete.size()); + + // int numberOfVerticesAfterOperation = + // printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + // System.out.println(numberOfVerticesAfterOperation); + // 6 - service, 2 tags, capability + 2 parameters + // compareGraphSize(numberOfVertices + 6, vertexSetBeforeMethod); + + } finally { + rollbackAndPrint(false); + compareGraphSize(numberOfVertices); + // printGraph1.printGraphVertices(titanDao.getGraph().left().value()); + } + + } + + public void testCreateRootResource() { + + String name = "tosca.nodes.Root"; + + String state = LifecycleStateEnum.CERTIFIED.name(); + + ResourceMetadataData resourceData1 = new ResourceMetadataData(); + resourceData1.getMetadataDataDefinition().setUniqueId(UniqueIdBuilder.buildResourceUniqueId()); + resourceData1.getMetadataDataDefinition().setName(name); + resourceData1.getMetadataDataDefinition().setState(state); + resourceData1.getMetadataDataDefinition().setHighestVersion(true); + resourceData1.getMetadataDataDefinition().setContactId("contactId"); + Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1, + ResourceMetadataData.class); + + log.debug("{}", createNode1); + + titanDao.commit(); + } + + public void testMultiResourceCertified() { + boolean create = true; + String name = "myresource7"; + if (create) { + + String state = LifecycleStateEnum.CERTIFIED.name(); + boolean isHighestVersion = true; + + ResourceMetadataData resourceData1 = new ResourceMetadataData(); + resourceData1.getMetadataDataDefinition().setUniqueId(name + "." + "1.0"); + resourceData1.getMetadataDataDefinition().setName(name); + resourceData1.getMetadataDataDefinition().setState(state); + resourceData1.getMetadataDataDefinition().setHighestVersion(true); + resourceData1.getMetadataDataDefinition().setContactId("contactId"); + Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1, + ResourceMetadataData.class); + + log.debug("{}", createNode1); + + titanDao.commit(); + + // resourceData1.setHighestVersion(false); + resourceData1.getMetadataDataDefinition().setContactId("222contactId222"); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData1, + ResourceMetadataData.class); + + titanDao.commit(); + + // TitanGraph titanGraph = titanDao.getGraph().left().value(); + // Iterable<Result<Vertex>> vertices = + // titanGraph.indexQuery("highestVersion", + // "v.highestVersion:true").vertices(); + // for (Result<Vertex> vertex : vertices) { + // Vertex element = vertex.getElement(); + // System.out.println( ElementHelper.getProperties(element)); + // } + + } + + Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = searchForResource(name); + + log.debug("{}", byCriteria.left().value().size()); + + byCriteria = searchForResource(name); + + log.debug("{}", byCriteria.left().value().size()); + + } + + private Either<List<ResourceMetadataData>, TitanOperationStatus> searchForResource(String name) { + Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); + propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); + // propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), + // true); + propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), name); + propertiesToMatch.put(GraphPropertiesDictionary.CONTACT_ID.getProperty(), "contactId"); + // propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), + // true); + Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao + .getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); + return byCriteria; + } + + @Test + public void testCreateResourceInstanceTwice() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + try { + + String capabilityTypeName = CAPABILITY_2; + String reqName = "host"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + ComponentInstance myresourceInstance = buildResourceInstance(softwareComponent.getUniqueId(), "1", + softwareCompName); + + String serviceName = "myservice.1.0"; + ServiceMetadataData createService = createService(serviceName); + Either<ComponentInstance, StorageOperationStatus> myinstanceRes1 = resourceInstanceOperation + .createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, + NodeTypeEnum.Resource, true); + assertTrue("check resource instance was created", myinstanceRes1.isLeft()); + + Either<ComponentInstance, StorageOperationStatus> myinstanceRes2 = resourceInstanceOperation + .createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, + NodeTypeEnum.Resource, true); + assertTrue("check resource instance was not created", myinstanceRes2.isRight()); + assertEquals("check error code", StorageOperationStatus.SCHEMA_VIOLATION, myinstanceRes2.right().value()); + + Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation + .deleteComponentInstance(NodeTypeEnum.Service, serviceName, + myinstanceRes1.left().value().getUniqueId(), true); + assertTrue("check resource instance was deleted", deleteResourceInstance.isLeft()); + + deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, + serviceName, myinstanceRes1.left().value().getUniqueId(), true); + assertTrue("check resource instance was not deleted", deleteResourceInstance.isRight()); + assertEquals("check resource instance was not deleted", StorageOperationStatus.NOT_FOUND, + deleteResourceInstance.right().value()); + + } finally { + rollbackAndPrint(false); + compareGraphSize(numberOfVertices); + } + + } + + @Test + public void testConnectResourceInstancesTwice() { + + PrintGraph printGraph1 = new PrintGraph(); + int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value()); + + try { + + String capabilityTypeName1 = CAPABILITY_1; + String capabilityTypeName2 = CAPABILITY_2; + String reqName1 = "host1"; + String reqName2 = "host2"; + String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER; + String rootName = "Root2" + TEST_CLASS_NUMBER; + String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER; + String computeNodeName = reqNodeName; + String myResourceVersion = "4.0" + TEST_CLASS_NUMBER; + String reqRelationship = "myrelationship"; + + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest + .createCapability(capabilityTypeName1); + CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest + .createCapability(capabilityTypeName2); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + // create root resource + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, + true, true); + + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + + // create software component + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + // create compute component + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, + "1.0", rootResource.getName(), true, true); + + // Add capabilities to Compute Resource + CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent); + CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent); + + // rollbackAndPrint(); + + // create requirement definition + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + // create my resource derived from software component + Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", + myResourceVersion, softwareComponent.getName(), true, true); + + String serviceId = "myservice.1.0"; + + ServiceMetadataData createService = createService(serviceId); + ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource"); + + ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", + computeNodeName); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", myinstanceRes.isLeft()); + ComponentInstance value1 = myinstanceRes.left().value(); + Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, + computeInstance, NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", computeInstTes.isLeft()); + ComponentInstance value2 = computeInstTes.left().value(); + + RequirementCapabilityRelDef relation = new RequirementCapabilityRelDef(); + String fromResUid = value1.getUniqueId(); + String toResUid = value2.getUniqueId(); + relation.setFromNode(fromResUid); + relation.setToNode(toResUid); + List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>(); + RequirementAndRelationshipPair immutablePair1 = new RequirementAndRelationshipPair(reqName1, null); + immutablePair1.setCapabilityUid(capabilty1.getUniqueId()); + immutablePair1.setRequirementUid(parentReqUniqId); + immutablePair1.setRequirementOwnerId(fromResUid); + immutablePair1.setCapabilityOwnerId(toResUid); + relationships.add(immutablePair1); + + relation.setRelationships(relationships); + + Either<RequirementCapabilityRelDef, StorageOperationStatus> connectResourcesInService = resourceInstanceOperation + .associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true); + assertTrue("check association succeed", connectResourcesInService.isLeft()); + + relationships.clear(); + RequirementAndRelationshipPair immutablePair2 = new RequirementAndRelationshipPair(reqName2, null); + immutablePair2.setCapabilityUid(capabilty2.getUniqueId()); + immutablePair2.setRequirementUid(parentReqUniqId); + relationships.add(immutablePair2); + + RequirementCapabilityRelDef firstRelation = connectResourcesInService.left().value(); + connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, + NodeTypeEnum.Service, relation, true); + assertTrue("check association succeed", connectResourcesInService.isRight()); + assertEquals("check association failed", StorageOperationStatus.MATCH_NOT_FOUND, + connectResourcesInService.right().value()); + + Either<RequirementCapabilityRelDef, StorageOperationStatus> disconnectResourcesInService = resourceInstanceOperation + .dissociateResourceInstances(serviceId, NodeTypeEnum.Service, firstRelation, true); + + assertTrue("check dissociation succeed", disconnectResourcesInService.isLeft()); + + disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, + NodeTypeEnum.Service, relation, true); + + assertTrue("check dissociation failed", disconnectResourcesInService.isRight()); + assertEquals("check association failed", StorageOperationStatus.NOT_FOUND, + disconnectResourcesInService.right().value()); + } finally { + rollbackAndPrint(); + compareGraphSize(numberOfVertices); + } + + } + + private Resource createComputeWithCapability(String capabilityTypeName, String computeNodeName, + ResourceOperationTest resourceOperationTest, Resource rootResource) { + // create compute component + // String id = UniqueIdBuilder.buildResourceUniqueId(computeNodeName, + // "1.0"); + // if (resourceOperation.getResource(id).isLeft()){ + // resourceOperation.deleteResource(id); + // } + Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation + .getResourceByNameAndVersion(computeNodeName, "1.0", false); + if (oldResource.isLeft()) { + for (Resource old : oldResource.left().value()) { + if (old.getResourceType().equals(ResourceTypeEnum.VFC)) { + resourceOperation.deleteResource(old.getUniqueId()); + } + } + + } + + Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", + rootResource.getName(), true, true); + + // rollbackAndPrint(); + + // Add capabilities to Compute Resource + addCapabilityToResource(capabilityTypeName, "host", computeComponent); + return resourceOperation.getResource(computeComponent.getUniqueId()).left().value(); + } + + private Resource createSoftwareComponentWithReq(String softwareCompName, + ResourceOperationTest resourceOperationTest, Resource rootResource, String capabilityTypeName, + String reqName, String reqRelationship, String reqNodeName) { + Either<ResourceMetadataData, TitanOperationStatus> updateNode; + ResourceMetadataData resourceData = new ResourceMetadataData(); + // create software component + // String id = UniqueIdBuilder.buildResourceUniqueId(softwareCompName, + // "1.0"); + // if (resourceOperation.getResource(id).isLeft()){ + // resourceOperation.deleteResource(id); + // } + Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation + .getResourceByNameAndVersion(softwareCompName, "1.0", false); + if (oldResource.isLeft()) { + if (oldResource.isLeft()) { + for (Resource old : oldResource.left().value()) { + if (old.getResourceType().equals(ResourceTypeEnum.VFC)) { + resourceOperation.deleteResource(old.getUniqueId()); + } + } + + } + } + + Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, + "1.0", rootResource.getName(), true, true); + + resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource( + capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent); + + String parentReqUniqId = addRequirementToResource.left().value().getUniqueId(); + + return resourceOperation.getResource(softwareComponent.getUniqueId()).left().value(); + } + + private Resource createRootResource(String rootName, ResourceOperationTest resourceOperationTest) { + // create root resource + // String rootId = UniqueIdBuilder.buildResourceUniqueId(rootName, + // "1.0"); + Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation + .getResourceByNameAndVersion(rootName, "1.0", false); + if (oldResource.isLeft()) { + for (Resource old : oldResource.left().value()) { + if (old.getResourceType().equals(ResourceTypeEnum.VFC)) { + resourceOperation.deleteResource(old.getUniqueId()); + } + } + + } + Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, + true); + ResourceMetadataData rootResourceData = new ResourceMetadataData(); + rootResourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId()); + rootResourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(rootResourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation + .getResource(rootResource.getUniqueId(), true); + + String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value()); + log.debug(rootResourceJson); + return rootResource; + } + + public void addResourceInstancesAndRelation(String serviceId) { + + String rootName = "tosca.nodes.test.root"; + String softwareCompName = "tosca.nodes.test.softwarecomponent"; + String capabilityTypeName = "myCapability"; + String reqName = "host"; + String computeNodeName = "tosca.nodes.test.compute"; + String reqRelationship = "myRelationship"; + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = createRootResource(rootName, resourceOperationTest); + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName); + + Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, + rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName); + Resource compute = createComputeWithCapability(capabilityTypeName, computeNodeName, resourceOperationTest, + rootResource); + + // resource1 + ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", + "tosca.nodes.test.root"); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + + assertTrue("check instance added to service", myinstanceRes.isLeft()); + + // resource2 + ComponentInstance computeInstance = buildResourceInstance(compute.getUniqueId(), "2", + "tosca.nodes.test.compute"); + ComponentInstance value1 = myinstanceRes.left().value(); + + Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, + NodeTypeEnum.Resource, false); + assertTrue("check instance added to service", computeInstTes.isLeft()); + ComponentInstance value2 = computeInstTes.left().value(); + + RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair(); + relationPair.setRequirement(reqName); + relationPair.setCapability(capabilityTypeName); + + String capId = ""; + Map<String, List<CapabilityDefinition>> capabilities = compute.getCapabilities(); + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + capId = entry.getValue().get(0).getUniqueId(); + } + relationPair.setCapabilityUid(capId); + Map<String, List<RequirementDefinition>> requirements = softwareComponentResource.getRequirements(); + String reqId = ""; + for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { + reqId = entry.getValue().get(0).getUniqueId(); + } + relationPair.setRequirementUid(reqId); + relationPair.setRequirementOwnerId(value1.getUniqueId()); + relationPair.setCapabilityOwnerId(value2.getUniqueId()); + relationPair.setCapabilityUid(capId); + + Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation + .connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), + relationPair); + + assertTrue("check relation created", connectResourcesInService.isLeft()); + + } + + @Test + public void addResourceInstancesResourceDeleted() { + + String rootName = "tosca.nodes.test.root"; + String softwareCompName = "tosca.nodes.test.softwarecomponent"; + String capabilityTypeName = "myCapability"; + String reqName = "host"; + String computeNodeName = "tosca.nodes.test.compute"; + String reqRelationship = "myRelationship"; + + ServiceMetadataData origService = createService("myService"); + String serviceId = (String) origService.getUniqueId(); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = createRootResource(rootName, resourceOperationTest); + // Create Capability type + CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest(); + capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation); + capabilityTypeOperationTest.createCapability(capabilityTypeName); + + Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, + rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName); + + deleteResource(softwareComponentResource.getUniqueId()); + + // resource1 + ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", + "tosca.nodes.test.root"); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + + assertTrue("check instance not added to service", myinstanceRes.isRight()); + + } + + @Test + public void testDeploymentArtifactsOnRI() { + + String rootName = "tosca.nodes.test.root"; + + ServiceMetadataData origService = createService("testDeploymentArtifactsOnRI"); + String serviceId = (String) origService.getUniqueId(); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = createRootResource(rootName, resourceOperationTest); + ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), + "myArtifact"); + + // resource1 + ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + + assertTrue("check instance added to service", myinstanceRes.isLeft()); + + Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation + .getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource); + assertTrue(resourceInstancesOfService.isLeft()); + List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left; + assertTrue(resourceInstanceList.size() == 1); + ComponentInstance resourceInstance = resourceInstanceList.get(0); + assertTrue(resourceInstance.getDeploymentArtifacts().size() == 1); + Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel())); + + ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource); + heatEnvArtifact.setArtifactType("HEAT_ENV"); + heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env"); + heatEnvArtifact.setUniqueId(null); + + Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact( + heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, + false); + assertTrue(either.isLeft()); + + resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, + NodeTypeEnum.Service, NodeTypeEnum.Resource); + assertTrue(resourceInstancesOfService.isLeft()); + resourceInstanceList = resourceInstancesOfService.left().value().left; + assertTrue(resourceInstanceList.size() == 1); + resourceInstance = resourceInstanceList.get(0); + assertTrue(resourceInstance.getDeploymentArtifacts().size() == 2); + artifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel())); + assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env")); + ArtifactDefinition heatEnvFromRI = artifacts.get(addArtifactToResource.getArtifactLabel() + "env"); + assertEquals(addArtifactToResource.getUniqueId(), heatEnvFromRI.getGeneratedFromId()); + + List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()) + .getHeatParameters(); + assertNotNull(heatParameters); + assertTrue(heatParameters.size() == 1); + + List<HeatParameterDefinition> heatEnvParameters = heatEnvFromRI.getHeatParameters(); + assertNotNull(heatEnvParameters); + assertTrue(heatEnvParameters.size() == 1); + + resourceOperation.deleteResource(rootResource.getUniqueId()); + + } + + @Test + public void deleteResourceInstanceWithArtifacts() { + String rootName = "tosca.nodes.test.root"; + + ServiceMetadataData origService = createService("deleteResourceInstanceWithArtifacts"); + String serviceId = (String) origService.getUniqueId(); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = createRootResource(rootName, resourceOperationTest); + ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), + "myArtifact"); + + // resource1 + ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + + ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource); + heatEnvArtifact.setArtifactType("HEAT_ENV"); + heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env"); + heatEnvArtifact.setUniqueId(null); + + assertTrue("check instance added to service", myinstanceRes.isLeft()); + + Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation + .getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource); + assertTrue(resourceInstancesOfService.isLeft()); + List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left; + assertTrue(resourceInstanceList.size() == 1); + ComponentInstance resourceInstance = resourceInstanceList.get(0); + + Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact( + heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, + false); + assertTrue(either.isLeft()); + ArtifactDefinition heatEnvDefinition = either.left().value(); + + // delete resource instance + Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation + .deleteComponentInstance(NodeTypeEnum.Service, serviceId, resourceInstance.getUniqueId()); + assertTrue(deleteResourceInstance.isLeft()); + + // check heat env deleted + ArtifactData artifactData = new ArtifactData(); + Either<ArtifactData, TitanOperationStatus> getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), + heatEnvDefinition.getUniqueId(), ArtifactData.class); + assertTrue(getDeletedArtifact.isRight()); + + // check heat is not deleted + getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), addArtifactToResource.getUniqueId(), + ArtifactData.class); + assertTrue(getDeletedArtifact.isLeft()); + + HeatParameterData heatParamData = new HeatParameterData(); + Either<HeatParameterData, TitanOperationStatus> heatParamNode = titanDao.getNode(heatParamData.getUniqueIdKey(), + addArtifactToResource.getHeatParameters().get(0).getUniqueId(), HeatParameterData.class); + assertTrue(heatParamNode.isLeft()); + + resourceOperation.deleteResource(rootResource.getUniqueId()); + + } + + @Test + public void getHeatEnvParams() { + String rootName = "tosca.nodes.test.root"; + + ServiceMetadataData origService = createService("getHeatEnvParams"); + String serviceId = (String) origService.getUniqueId(); + + ResourceOperationTest resourceOperationTest = new ResourceOperationTest(); + resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation); + + Resource rootResource = createRootResource(rootName, resourceOperationTest); + ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), + "myArtifact"); + + // resource1 + ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName); + + Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation + .addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, + myresourceInstance, NodeTypeEnum.Resource, false); + + ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource); + heatEnvArtifact.setArtifactType("HEAT_ENV"); + heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env"); + heatEnvArtifact.setUniqueId(null); + + assertTrue("check instance added to service", myinstanceRes.isLeft()); + + Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation + .getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource); + assertTrue(resourceInstancesOfService.isLeft()); + List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left; + assertTrue(resourceInstanceList.size() == 1); + ComponentInstance resourceInstance = resourceInstanceList.get(0); + + Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact( + heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, + false); + assertTrue(either.isLeft()); + ArtifactDefinition heatEnvDefinition = either.left().value(); + + // update value + String newHeatValue = "123"; + addHeatValueToEnv(heatEnvDefinition.getUniqueId(), addArtifactToResource.getHeatParameters().get(0), + newHeatValue); + + // check values received + + resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, + NodeTypeEnum.Service, NodeTypeEnum.Resource); + assertTrue(resourceInstancesOfService.isLeft()); + resourceInstanceList = resourceInstancesOfService.left().value().left; + assertTrue(resourceInstanceList.size() == 1); + resourceInstance = resourceInstanceList.get(0); + assertTrue(resourceInstance.getDeploymentArtifacts().size() == 2); + Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel())); + assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env")); + + List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()) + .getHeatParameters(); + assertNotNull(heatParameters); + assertTrue(heatParameters.size() == 1); + HeatParameterDefinition heatParameterTemplate = heatParameters.get(0); + + List<HeatParameterDefinition> heatEnvParameters = artifacts + .get(addArtifactToResource.getArtifactLabel() + "env").getHeatParameters(); + assertNotNull(heatEnvParameters); + assertTrue(heatEnvParameters.size() == 1); + HeatParameterDefinition heatParameterEnv = heatEnvParameters.get(0); + + assertEquals(heatParameterEnv.getDefaultValue(), heatParameterTemplate.getCurrentValue()); + assertEquals(newHeatValue, heatParameterEnv.getCurrentValue()); + assertFalse(newHeatValue.equals(heatParameterTemplate.getCurrentValue())); + + resourceOperation.deleteResource(rootResource.getUniqueId()); + + } + + public void addHeatValueToEnv(String artifactId, HeatParameterDefinition heatDefinition, String value) { + HeatParameterValueData heatValueData = new HeatParameterValueData(); + heatValueData.setValue(value); + heatValueData.setUniqueId(artifactId + "." + heatDefinition.getName()); + Either<HeatParameterValueData, TitanOperationStatus> createValue = titanDao.createNode(heatValueData, + HeatParameterValueData.class); + assertTrue(createValue.isLeft()); + HeatParameterValueData value2 = createValue.left().value(); + HeatParameterData heatParamData = new HeatParameterData(heatDefinition); + Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(value2, heatParamData, + GraphEdgeLabels.PROPERTY_IMPL, null); + assertTrue(createRelation.isLeft()); + Map<String, Object> props = new HashMap<String, Object>(); + props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), heatDefinition.getName()); + Either<GraphRelation, TitanOperationStatus> createRelation2 = titanDao.createRelation( + new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId), value2, GraphEdgeLabels.PARAMETER_VALUE, props); + assertTrue(createRelation2.isLeft()); + titanDao.commit(); + + } + + public static String normaliseComponentName(String name) { + String[] split = splitComponentName(name); + StringBuffer sb = new StringBuffer(); + for (String splitElement : split) { + sb.append(splitElement); + } + return sb.toString(); + + } + + private static String[] splitComponentName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + String[] split = normalizedName.split(" "); + return split; + } + + public static String normaliseComponentInstanceName(String name) { + String[] split = splitComponentInstanceName(name); + StringBuffer sb = new StringBuffer(); + for (String splitElement : split) { + sb.append(splitElement); + } + return sb.toString(); + + } + + private static String[] splitComponentInstanceName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + String[] split = normalizedName.split(" "); + return split; + } + + private ArtifactDefinition addArtifactToResource(String userId, String resourceId, String artifactName) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".yml"); + artifactInfo.setArtifactType("HEAT"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + 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(artifactName); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); + artifactInfo.setEsId(artifactInfo.getUniqueId()); + + List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); + 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); + + Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation + .addArifactToComponent(artifactInfo, resourceId, NodeTypeEnum.Resource, true, true); + assertTrue(artifact.isLeft()); + return artifact.left().value(); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java new file mode 100644 index 0000000000..f977509f6b --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java @@ -0,0 +1,734 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +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.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; +import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; +import org.openecomp.sdc.be.resources.data.PropertyData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ResourceOperationTest extends ModelTestBase { + + private static Logger log = LoggerFactory.getLogger(ResourceOperationTest.class.getName()); + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @javax.annotation.Resource(name = "lifecycle-operation") + private LifecycleOperation lifecycleOperation; + + @javax.annotation.Resource(name = "capability-operation") + private CapabilityOperation capabilityOperation; + + @javax.annotation.Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + private static String CATEGORY_NAME = "category/mycategory"; + private static String CATEGORY_NAME_UPDATED = "category1/updatedcategory"; + + @BeforeClass + public static void setupBeforeClass() { + + ModelTestBase.init(); + } + + public void setOperations(TitanGenericDao titanGenericDao, ResourceOperation resourceOperation, + PropertyOperation propertyOperation) { + this.titanDao = titanGenericDao; + this.resourceOperation = resourceOperation; + this.propertyOperation = propertyOperation; + } + + @Test + public void dummyTest() { + + } + + private Resource buildResourceMetadata(String userId, String category, String resourceName, + String resourceVersion) { + + Resource resource = new Resource(); + resource.setName(resourceName); + resource.setVersion(resourceVersion); + ; + resource.setDescription("description 1"); + resource.setAbstract(false); + resource.setCreatorUserId(userId); + resource.setContactId("contactId@sdc.com"); + resource.setVendorName("vendor 1"); + resource.setVendorRelease("1.0.0"); + resource.setToscaResourceName(resourceName); + String[] categoryArr = category.split("/"); + resource.addCategory(categoryArr[0], categoryArr[1]); + resource.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + resource.setTags(tags); + return resource; + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + } + + public Resource createResource(String userId, String category, String resourceName, String resourceVersion, + String parentResourceName, boolean isAbstract, boolean isHighestVersion) { + + String propName1 = "disk_size"; + String propName2 = "num_cpus"; + + List<String> derivedFrom = new ArrayList<String>(); + if (parentResourceName != null) { + derivedFrom.add(parentResourceName); + } + Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion); + + resource.setAbstract(isAbstract); + resource.setHighestVersion(isHighestVersion); + + Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>(); + + PropertyDefinition property1 = new PropertyDefinition(); + property1.setDefaultValue("10"); + property1.setDescription( + "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node."); + property1.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>(); + GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0"); + log.debug("{}", propertyConstraint1); + + constraints.add(propertyConstraint1); + + LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10"); + constraints.add(propertyConstraint2); + + property1.setConstraints(constraints); + + properties.put(propName1, property1); + + PropertyDefinition property2 = new PropertyDefinition(); + property2.setDefaultValue("2"); + property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node."); + property2.setType(ToscaType.INTEGER.name().toLowerCase()); + List<PropertyConstraint> constraints3 = new ArrayList<PropertyConstraint>(); + List<String> range = new ArrayList<String>(); + range.add("1"); + range.add("4"); + + InRangeConstraint propertyConstraint3 = new InRangeConstraint(range); + constraints3.add(propertyConstraint3); + // property2.setConstraints(constraints3); + property2.setConstraints(constraints3); + properties.put(propName2, property2); + + resource.setDerivedFrom(derivedFrom); + + resource.setProperties(convertMapToList(properties)); + + Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true); + + assertTrue(result.isLeft()); + Resource resultResource = result.left().value(); + + // assertEquals("check resource unique id", + // UniqueIdBuilder.buildResourceUniqueId(resourceName, + // resourceVersion), resultResource.getUniqueId()); + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + resultResource.getLifecycleState()); + + // retrieve property from graph + String resourceId = resultResource.getUniqueId(); + // String resourceId = UniqueIdBuilder.buildResourceUniqueId( + // resource.getResourceName(), resource.getResourceVersion()); + + Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, + resourceId); + + assertTrue(either.isLeft()); + PropertyDefinition propertyDefinition = either.left().value(); + assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue()); + assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription()); + assertEquals("check property type", property1.getType(), propertyDefinition.getType()); + assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId()); + assertEquals("check property consitraints size", property1.getConstraints().size(), + propertyDefinition.getConstraints().size()); + + return resultResource; + + } + + public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) { + if (properties == null) { + return null; + } + + List<PropertyDefinition> definitions = new ArrayList<>(); + for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { + String name = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + propertyDefinition.setName(name); + definitions.add(propertyDefinition); + } + + return definitions; + } + + @Test + public void testFollowed() { + String rootName = "Root123"; + + String userId = "jh0003"; + String category = CATEGORY_NAME; + deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); + deleteAndCreateCategory(category); + + Resource rootResource = createResource(userId, category, rootName, "1.0", null, false, true); + log.debug(" *** create **"); + log.debug("{}", rootResource); + String resourceId = rootResource.getUniqueId(); + + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); + lastStateStates.add(LifecycleStateEnum.CERTIFIED); + + Either<List<Resource>, StorageOperationStatus> followed = resourceOperation.getFollowed(userId, lifecycleStates, + lastStateStates, false); + assertTrue(followed.isLeft()); + List<Resource> list = followed.left().value(); + + assertEquals(1, list.size()); + resourceOperation.deleteResource(resourceId); + + followed = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false); + assertTrue(followed.isLeft()); + list = followed.left().value(); + assertTrue(list.isEmpty()); + + } + + @Ignore + @Test + public void testGetLatestVersion() { + String rootName = "Root123"; + + String userId = "jh0003"; + String category = "category/mycategory"; + deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); + deleteAndCreateCategory(category); + + Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(rootName, true); + assertTrue(latestByName.isRight()); + assertEquals(StorageOperationStatus.NOT_FOUND, latestByName.right().value()); + + Resource rootResource = createResource(userId, category, rootName, "1.0", null, false, true); + + latestByName = resourceOperation.getLatestByName(rootName, true); + assertTrue(latestByName.isLeft()); + + Resource rootResourceHighest = createResource(userId, category, rootName, "1.3", null, false, true); + + latestByName = resourceOperation.getLatestByName(rootName, false); + assertTrue(latestByName.isLeft()); + assertEquals(rootResourceHighest.getUniqueId(), latestByName.left().value().getUniqueId()); + + resourceOperation.deleteResource(rootResource.getUniqueId()); + resourceOperation.deleteResource(rootResourceHighest.getUniqueId()); + } + + @Test + public void testOverrideResource() { + String rootName = "Root123"; + + String userId = "jh0003"; + String category = CATEGORY_NAME; + String updatedCategory = CATEGORY_NAME_UPDATED; + deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); + deleteAndCreateCategory(category); + deleteAndCreateCategory(updatedCategory); + + Resource rootResource = createResource(userId, category, rootName, "1.1", null, false, true); + + rootResource.setCategories(null); + String[] updateArr = updatedCategory.split("/"); + rootResource.addCategory(updateArr[0], updateArr[1]); + List<PropertyDefinition> properties = rootResource.getProperties(); + PropertyDefinition propertyDefinition = findProperty(properties, "disk_size"); + + rootResource.setProperties(new ArrayList<PropertyDefinition>()); + propertyDefinition.setName("myProperty"); + rootResource.getProperties().add(propertyDefinition); + + Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource, + rootResource, false); + + assertTrue(overrideResource.isLeft()); + Resource resourceAfter = overrideResource.left().value(); + assertEquals(1, resourceAfter.getProperties().size()); + + assertNotNull(findProperty(resourceAfter.getProperties(), "myProperty")); + assertEquals(1, resourceAfter.getCategories().size()); + assertEquals(1, resourceAfter.getCategories().get(0).getSubcategories().size()); + + assertEquals(updateArr[0], resourceAfter.getCategories().get(0).getName()); + assertEquals(updateArr[1], resourceAfter.getCategories().get(0).getSubcategories().get(0).getName()); + + resourceOperation.deleteResource(rootResource.getUniqueId()); + } + + @Test + public void testResourceWithCapabilities() { + String rootName = "Root123"; + + String userId = "jh0003"; + String category = CATEGORY_NAME; + String updatedCategory = CATEGORY_NAME_UPDATED; + deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); + deleteAndCreateCategory(category); + deleteAndCreateCategory(updatedCategory); + + Resource rootResource = createResource(userId, category, rootName, "1.1", null, false, true); + + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(); + capabilityTypeDefinition.setType("tosca.capabilities.Container"); + PropertyDefinition delaultProperty1 = new PropertyDefinition(); + delaultProperty1.setName("def"); + delaultProperty1.setType("string"); + delaultProperty1.setDefaultValue("def"); + + PropertyDefinition delaultProperty2 = new PropertyDefinition(); + delaultProperty2.setName("host"); + delaultProperty2.setType("string"); + delaultProperty2.setDefaultValue("true"); + + HashMap<String, PropertyDefinition> props = new HashMap<String, PropertyDefinition>(); + props.put(delaultProperty1.getName(), delaultProperty1); + props.put(delaultProperty2.getName(), delaultProperty2); + capabilityTypeDefinition.setProperties(props); + + Either<CapabilityTypeDefinition, StorageOperationStatus> addTypeRes = capabilityTypeOperation + .addCapabilityType(capabilityTypeDefinition); + assertTrue(addTypeRes.isLeft()); + + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setDescription("firstCap"); + capabilityDefinition.setName("firstCap"); + capabilityDefinition.setType("tosca.capabilities.Container"); + + List<ComponentInstanceProperty> properties = new ArrayList<ComponentInstanceProperty>(); + ComponentInstanceProperty propertyDefinition1 = new ComponentInstanceProperty(); + propertyDefinition1.setName("version"); + propertyDefinition1.setType("string"); + propertyDefinition1.setDefaultValue("007"); + properties.add(propertyDefinition1); + + ComponentInstanceProperty propertyDefinition2 = new ComponentInstanceProperty(); + propertyDefinition2.setName("host"); + propertyDefinition2.setType("string"); + propertyDefinition2.setDefaultValue("localhost"); + properties.add(propertyDefinition2); + + capabilityDefinition.setProperties(properties); + + Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation + .addCapability(rootResource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition); + assertTrue(addCapabilityRes.isLeft()); + + List<PropertyDefinition> newProperties = new ArrayList<PropertyDefinition>(); + propertyDefinition1 = new ComponentInstanceProperty(); + propertyDefinition1.setName("num_cpu"); + propertyDefinition1.setType("string"); + propertyDefinition1.setDefaultValue("4"); + newProperties.add(propertyDefinition1); + + propertyDefinition2 = new ComponentInstanceProperty(); + propertyDefinition2.setName("port"); + propertyDefinition2.setType("string"); + propertyDefinition2.setDefaultValue("4444"); + newProperties.add(propertyDefinition2); + + CapabilityDefinition addedCap = addCapabilityRes.left().value(); + + Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesRes = capabilityOperation + .updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties); + assertTrue(updatePropertiesRes.isLeft()); + + PropertyDefinition invalidProperty = new PropertyDefinition(); + invalidProperty.setName("port"); + invalidProperty.setType("rrr"); + invalidProperty.setDefaultValue("666"); + newProperties.add(invalidProperty); + + Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesInvalidRes = capabilityOperation + .updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties); + assertTrue(updatePropertiesInvalidRes.isRight()); + + Either<CapabilityDefinition, StorageOperationStatus> getCapabilityRes = capabilityOperation + .getCapability(addedCap.getUniqueId()); + assertTrue(getCapabilityRes.isLeft()); + + Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapabilityRes = capabilityOperation + .deletePropertiesOfCapability(addedCap.getUniqueId()); + assertTrue(deletePropertiesOfCapabilityRes.isLeft()); + + StorageOperationStatus deleteCapabilityRes = capabilityOperation + .deleteCapabilityFromGraph(addedCap.getUniqueId()); + assertTrue(deleteCapabilityRes.equals(StorageOperationStatus.OK)); + + getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId()); + assertTrue(getCapabilityRes.isRight() + && getCapabilityRes.right().value().equals(StorageOperationStatus.NOT_FOUND)); + + resourceOperation.deleteResource(rootResource.getUniqueId()); + } + + private PropertyDefinition findProperty(List<PropertyDefinition> properties, String propName) { + + if (properties == null) { + return null; + } + + for (PropertyDefinition propertyDefinition : properties) { + String name = propertyDefinition.getName(); + if (name.equals(propName)) { + return propertyDefinition; + } + } + + return null; + } + + @Test + public void testOverrideResourceNotExist() { + String rootName = "Root123"; + + String userId = "jh0003"; + String category = CATEGORY_NAME; + deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); + deleteAndCreateCategory(category); + + Resource rootResource = buildResourceMetadata(userId, category, rootName, "1.1"); + rootResource.setUniqueId(UniqueIdBuilder.buildResourceUniqueId()); + + Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource, + rootResource, false); + + assertTrue(overrideResource.isRight()); + + } + + @Ignore + @Test + public void testCatalogResource() { + String resName = "myResource"; + String userId = "jh0003"; + String category = CATEGORY_NAME; + deleteAndCreateCategory(category); + // resourceOperation.deleteResource(UniqueIdBuilder.buildResourceUniqueId(resName,"0.1")); + Resource newResource = createResource(userId, category, resName, "0.1", null, false, true); + String resourceId = newResource.getUniqueId(); + + Map<String, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); + + Either<Set<Resource>, StorageOperationStatus> catalog = resourceOperation.getCatalogData(propertiesToMatch, + false); + assertTrue(catalog.isLeft()); + Set<Resource> catalogSet = catalog.left().value(); + Set<String> idSet = new HashSet<>(); + for (Resource resource : catalogSet) { + idSet.add(resource.getUniqueId()); + } + assertTrue(idSet.contains(resourceId)); + resourceOperation.deleteResource(resourceId); + } + + @Ignore + @Test + public void testTesterFollowed() { + String rootName = "Test1"; + String rootName2 = "Test2"; + String rootName3 = "Test3"; + String userId = "jh0003"; + String testerUserId = "tt0004"; + String category = CATEGORY_NAME; + deleteAndCreateUser(testerUserId, "tester", "last"); + deleteAndCreateCategory(category); + + String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); + Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class); + User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); + Either<UserData, TitanOperationStatus> findTesterUser = titanDao.getNode(key, testerUserId, UserData.class); + User testerUser = OperationTestsUtil.convertUserDataToUser(findTesterUser.left().value()); + + // Create 3 new resources + Resource resultResource = createResource(userId, category, rootName, "1.0", null, false, true); + log.debug("{}", resultResource); + String resourceId = resultResource.getUniqueId(); + Resource resultResource2 = createResource(userId, category, rootName2, "1.0", null, false, true); + log.debug("{}", resultResource2); + String resourceId2 = resultResource2.getUniqueId(); + Resource resultResource3 = createResource(userId, category, rootName3, "1.0", null, false, true); + log.debug("{}", resultResource3); + String resourceId3 = resultResource3.getUniqueId(); + + // update 1 resource to READY_FOR_CERTIFICATION + Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Resource, resultResource, adminUser, adminUser, false); + Resource RFCResource = certReqResponse.left().value(); + assertEquals(RFCResource.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + + // update 1 resource to CERTIFICATION_IN_PROGRESS + Either<Resource, StorageOperationStatus> startCertificationResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .startComponentCertification(NodeTypeEnum.Resource, resultResource2, testerUser, adminUser, false); + Resource IPResource = startCertificationResponse.left().value(); + assertEquals(IPResource.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(testerUserId, + lifecycleStates, false); + + assertTrue(resources.isLeft()); + List<Resource> result = resources.left().value(); + + List<String> idSet = new ArrayList(); + for (Resource resource : result) { + idSet.add(resource.getUniqueId()); + } + assertTrue(idSet.contains(resourceId)); + assertTrue(idSet.contains(resourceId2)); + assertFalse(idSet.contains(resourceId3)); + resourceOperation.deleteResource(resourceId); + resourceOperation.deleteResource(resourceId2); + resourceOperation.deleteResource(resourceId3); + + } + + @Test + public void getVersionListNotDeleted() { + String resName = "myResource"; + String userId = "jh0003"; + String category = CATEGORY_NAME; + deleteAndCreateCategory(category); + + Resource newResource = createResource(userId, category, resName, "0.1", null, false, true); + String resourceId1 = newResource.getUniqueId(); + + User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis()); + Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false); + assertTrue(checkoutResource.isLeft()); + Resource newResource2 = checkoutResource.left().value(); + String resourceId2 = newResource2.getUniqueId(); + + Resource newResource3 = createResource(userId, category, resName, "0.1", null, false, true); + String resourceId3 = newResource3.getUniqueId(); + + Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList( + NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), + ResourceMetadataData.class); + assertTrue(versionList.isLeft()); + Map<String, String> versionMap = versionList.left().value(); + + assertTrue(versionMap.size() == 2); + assertTrue(versionMap.containsValue(resourceId1)); + assertTrue(versionMap.containsValue(resourceId2)); + assertFalse(versionMap.containsValue(resourceId3)); + + Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId1); + assertTrue(deleteResource.isLeft()); + deleteResource = resourceOperation.deleteResource(resourceId2); + assertTrue(deleteResource.isLeft()); + deleteResource = resourceOperation.deleteResource(resourceId3); + assertTrue(deleteResource.isLeft()); + + } + + @Test + public void getVersionListWithDeleted() { + String resName = "myResource"; + String userId = "jh0003"; + String category = CATEGORY_NAME; + deleteAndCreateCategory(category); + + Resource newResource = createResource(userId, category, resName, "0.1", null, false, true); + String resourceId1 = newResource.getUniqueId(); + + User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis()); + Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation + .checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false); + assertTrue(checkoutResource.isLeft()); + Resource newResource2 = checkoutResource.left().value(); + String resourceId2 = newResource2.getUniqueId(); + + Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(resourceId1, false); + assertTrue(resource.isLeft()); + Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation + .markComponentToDelete(resource.left().value(), false); + assertTrue(markResourceToDelete.isLeft()); + + Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList( + NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), + ResourceMetadataData.class); + + assertTrue(versionList.isLeft()); + Map<String, String> versionMap = versionList.left().value(); + + assertTrue(versionMap.size() == 1); + assertFalse(versionMap.containsValue(resourceId1)); + assertTrue(versionMap.containsValue(resourceId2)); + + Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId1); + assertTrue(deleteResource.isLeft()); + deleteResource = resourceOperation.deleteResource(resourceId2); + assertTrue(deleteResource.isLeft()); + } + + @Test + public void testDerviedPropertiesInResource() { + + try { + String userId = "jh0003"; + String category = CATEGORY_NAME; + + deleteAndCreateUser(userId, "first_" + userId, "last_" + userId); + deleteAndCreateCategory(category); + + Resource createResource1 = createResource(userId, category, "myResource1", "0.1", null, true, false); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(createResource1.getUniqueId()); + resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name()); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, + ResourceMetadataData.class); + assertTrue(updateNode.isLeft()); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + String json = gson.toJson(createResource1); + log.debug(json); + + Resource createResource2 = createResource(userId, category, "myResource2", "0.1", createResource1.getName(), + true, false); + + json = gson.toJson(createResource2); + log.debug(json); + + List<PropertyDefinition> propList1 = new ArrayList<>(); + TitanOperationStatus findAllResourcePropertiesRecursively1 = propertyOperation + .findAllResourcePropertiesRecursively(createResource1.getUniqueId(), propList1); + assertEquals("check search properties succeed", findAllResourcePropertiesRecursively1, + TitanOperationStatus.OK); + + List<PropertyDefinition> propList2 = new ArrayList<>(); + TitanOperationStatus findAllResourcePropertiesRecursively2 = propertyOperation + .findAllResourcePropertiesRecursively(createResource2.getUniqueId(), propList2); + assertEquals("check search properties succeed", findAllResourcePropertiesRecursively2, + TitanOperationStatus.OK); + + assertEquals("check number of properties", propList1.size() * 2, propList2.size()); + + resourceOperation.deleteResource(createResource1.getUniqueId()); + resourceOperation.deleteResource(createResource2.getUniqueId()); + + } finally { + + } + + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java new file mode 100644 index 0000000000..81a5a5ed1d --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java @@ -0,0 +1,964 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +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.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil; +import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; +import org.openecomp.sdc.be.resources.data.ArtifactData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.thinkaurelius.titan.core.TitanGraph; +//import com.tinkerpop.blueprints.Vertex; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class ServiceOperationTest extends ModelTestBase { + + @javax.annotation.Resource(name = "titan-generic-dao") + private TitanGenericDao titanDao; + + @javax.annotation.Resource(name = "service-operation") + private ServiceOperation serviceOperation; + + @javax.annotation.Resource + private IGraphLockOperation graphLockOperation; + + @javax.annotation.Resource + private ArtifactOperation artifactOperation; + + @javax.annotation.Resource(name = "requirement-operation") + private RequirementOperation requirementOperation; + + @javax.annotation.Resource(name = "resource-operation") + private ResourceOperation resourceOperation; + + @javax.annotation.Resource(name = "property-operation") + private PropertyOperation propertyOperation; + + @javax.annotation.Resource(name = "capability-operation") + private CapabilityOperation capabilityOperation; + + @javax.annotation.Resource(name = "capability-type-operation") + private CapabilityTypeOperation capabilityTypeOperation; + + @javax.annotation.Resource(name = "component-instance-operation") + private ComponentInstanceOperation resourceInstanceOperation; + + @javax.annotation.Resource(name = "lifecycle-operation") + private LifecycleOperation lifecycleOperation; + + private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName()); + private static String USER_ID = "muserId"; + private static String CATEGORY_NAME = "category/mycategory"; + + @BeforeClass + public static void setupBeforeClass() { + // ExternalConfiguration.setAppName("catalog-model"); + // String appConfigDir = "src/test/resources/config/catalog-model"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); + + // configurationManager = new ConfigurationManager(new + // ConfigurationSource() { + // + // @Override + // public <T> T getAndWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // return null; + // } + // + // @Override + // public <T> void addWatchConfiguration(Class<T> className, + // ConfigurationListener configurationListener) { + // // TODO Auto-generated method stub + // + // } + // }); + + // String appConfigDir = "src/test/resources/config"; + // ConfigurationSource configurationSource = new + // FSConfigurationSource(ExternalConfiguration.getChangeListener(), + // appConfigDir); + // configurationManager = new ConfigurationManager(configurationSource); + // + // Configuration configuration = new Configuration(); + // configuration.setTitanInMemoryGraph(true); + //// configuration.setTitanInMemoryGraph(false); + //// configuration.setTitanCfgFile("C:\\Dev\\d2\\D2-SDnC\\catalog-be\\src\\main\\resources\\config\\titan.properties"); + // + // configurationManager.setConfiguration(configuration); + + ModelTestBase.init(); + } + + @Before + public void createUserAndCategory() { + deleteAndCreateCategory(CATEGORY_NAME); + deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null); + } + + @Test + public void dummyTest() { + + } + + @Test + public void testCreateService() { + String category = CATEGORY_NAME; + String serviceName = "servceTest"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug(" *** create **"); + log.debug("{}", serviceAfterSave); + String uniqueId = serviceAfterSave.getUniqueId(); + + Either<Service, StorageOperationStatus> serviceGet = serviceOperation.getService(uniqueId); + assertTrue(serviceGet.isLeft()); + log.debug(" *** get **"); + log.debug("{}", serviceGet.left().value()); + + Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(uniqueId); + + assertTrue(serviceDelete.isLeft()); + log.debug(" *** delete **"); + log.debug("{}", serviceDelete.left().value()); + + Either<List<ArtifactData>, TitanOperationStatus> artifacts = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, + null, ArtifactData.class); + assertTrue(artifacts.isRight()); + assertEquals(TitanOperationStatus.NOT_FOUND, artifacts.right().value()); + + serviceOperation.deleteService(serviceAfterSave.getUniqueId()); + } + + @Test + public void testUtilsService() { + String category = CATEGORY_NAME; + String serviceName = "servceTest2"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug(" *** create **"); + log.debug("{}", serviceAfterSave); + String uniqueId = serviceAfterSave.getUniqueId(); + + boolean canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(uniqueId, serviceOperation, userId); + assertTrue(canWorkOnComponent); + + canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(serviceAfterSave, userId); + assertTrue(canWorkOnComponent); + + StorageOperationStatus lockComponent = graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service); + assertEquals(StorageOperationStatus.OK, lockComponent); + + lockComponent = graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service); + assertEquals(StorageOperationStatus.OK, lockComponent); + + Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(uniqueId); + } + + @Test + public void testInstanceCounter() { + String category = CATEGORY_NAME; + String serviceName = "servceTest2"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug(" *** create **"); + log.debug("{}", serviceAfterSave); + + Either<Integer, StorageOperationStatus> counter = serviceOperation + .increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false); + assertTrue(counter.isLeft()); + assertEquals(new Integer(1), (Integer) counter.left().value()); + + counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), + NodeTypeEnum.Service, false); + assertTrue(counter.isLeft()); + assertEquals(new Integer(2), (Integer) counter.left().value()); + Either<Service, StorageOperationStatus> serviceDelete = serviceOperation + .deleteService(serviceAfterSave.getUniqueId()); + } + + @Test + public void testAddArtifactToService() { + String category = CATEGORY_NAME; + String serviceName = "servceTest2"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug("{}", serviceAfterSave); + String serviceId = serviceAfterSave.getUniqueId(); + + ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache"); + + Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts(); + assertEquals(1, artifacts.size()); + + for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { + String artifactId = entry.getValue().getUniqueId(); + String description = entry.getValue().getDescription(); + assertEquals("hdkfhskdfgh", description); + + artifactInfo.setDescription("jghlsk new desfnjdh"); + + artifactOperation.updateArifactOnResource(artifactInfo, serviceId, artifactId, NodeTypeEnum.Service, false); + } + + service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + artifacts = service.left().value().getArtifacts(); + for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { + String artifactId = entry.getValue().getUniqueId(); + String description = entry.getValue().getDescription(); + assertEquals("jghlsk new desfnjdh", description); + + artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false); + } + service = serviceOperation.getService(serviceId); + assertTrue(service.isLeft()); + + artifacts = service.left().value().getArtifacts(); + assertEquals(0, artifacts.size()); + + Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId); + + Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, + null, ArtifactData.class); + assertTrue(byCriteria.isRight()); + assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value()); + + serviceOperation.deleteService(serviceAfterSave.getUniqueId()); + + } + + private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".sh"); + artifactInfo.setArtifactType("SHELL"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setPayloadData("UEsDBAoAAAAIAAeLb0bDQz"); + + 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(artifactName); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel())); + + Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation + .addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true); + assertTrue(artifact.isLeft()); + return artifactInfo; + } + + @Test + public void testFollowed() { + String category = CATEGORY_NAME; + String serviceName = "servceTest2"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug("{}", serviceAfterSave); + String serviceId = serviceAfterSave.getUniqueId(); + + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>(); + lastStateStates.add(LifecycleStateEnum.CERTIFIED); + + Either<List<Service>, StorageOperationStatus> followed = serviceOperation.getFollowed(userId, lifecycleStates, + lastStateStates, false); + assertTrue(followed.isLeft()); + List<Service> list = followed.left().value(); + assertEquals(1, list.size()); + serviceOperation.deleteService(serviceId); + } + + @Test + public void testUpdateService() { + String category = CATEGORY_NAME; + String serviceName = "12"; + String serviceVersion = "0.1"; + String userId = USER_ID; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug("{}", serviceAfterSave); + String serviceId = serviceAfterSave.getUniqueId(); + serviceAfterSave.setDescription("new description"); + Either<Service, StorageOperationStatus> updateService = serviceOperation.updateService(serviceAfterSave, false); + assertTrue(updateService.isLeft()); + + titanDao.commit(); + + Either<Service, StorageOperationStatus> serviceAfterUpdate = serviceOperation.getService(serviceId, false); + assertTrue(serviceAfterUpdate.isLeft()); + + serviceOperation.deleteService(serviceId); + assertEquals("new description", serviceAfterUpdate.left().value().getDescription()); + + } + + public Service createService(String userId, String category, String serviceName, String serviceVersion, + boolean isHighestVersion) { + + Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion); + + service.setHighestVersion(isHighestVersion); + + Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true); + + log.info(result.toString()); + assertTrue(result.isLeft()); + Service resultService = result.left().value(); + + // assertEquals("check resource unique id", + // UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion), + // resultService.getUniqueId()); + assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, + resultService.getLifecycleState()); + + return resultService; + } + + // @Test + public void testCloneFullService() { + // try{ + String userId = USER_ID; + // Either<Service, StorageOperationStatus> deleteService = + // serviceOperation.deleteService(UniqueIdBuilder.buildServiceUniqueId("my-service", + // "1.0"), false); + // log.info("testCloneFullService - after delete service. result + // is="+deleteService); + Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true); + + // add artifacts + addArtifactToService(userId, origService.getUniqueId(), "install_apache"); + addArtifactToService(userId, origService.getUniqueId(), "start_apache"); + + // add resource instances + ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); + riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, + resourceOperation, propertyOperation, resourceInstanceOperation); + riTest.addResourceInstancesAndRelation(origService.getUniqueId()); + + Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), + false); + assertTrue(service2.isLeft()); + origService = service2.left().value(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + String json = prettyGson.toJson(origService); + log.debug(json); + + Service fullService = origService; + + Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", + false); + assertTrue(createService.isLeft()); + Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation + .getServiceByNameAndVersion("my-service", "2.0", null, false); + assertTrue(serviceAfterCreate.isLeft()); + fullService = serviceAfterCreate.left().value(); + + Either<Service, StorageOperationStatus> getOrigService = serviceOperation + .getServiceByNameAndVersion("my-service", "1.0", null, false); + assertTrue(getOrigService.isLeft()); + origService = getOrigService.left().value(); + + // assertEquals(origService.getComponentMetadataDefinition(), + // fullService.getComponentMetadataDefinition()); + assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size()); + assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size()); + assertEquals(origService.getComponentInstancesRelations().size(), + fullService.getComponentInstancesRelations().size()); + + origService.setUniqueId(fullService.getUniqueId()); + origService.setVersion(fullService.getVersion()); + + assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); + assertEquals(origService.getCategories(), fullService.getCategories()); + + serviceOperation.deleteService(origService.getUniqueId()); + serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); + + // } finally { + // titanDao.rollback(); + // Either<Service, StorageOperationStatus> serviceAfterCreate = + // serviceOperation.getService(UniqueIdBuilder.buildServiceUniqueId("my-service", + // "2.0"), true); + // assertTrue(serviceAfterCreate.isRight()); + // + // Either<Service, StorageOperationStatus> getOrigService = + // serviceOperation.getService(UniqueIdBuilder.buildServiceUniqueId("my-service", + // "1.0"), true); + // assertTrue(getOrigService.isRight()); + // titanDao.rollback(); + // } + } + + // @Test + public void testCloneServiceWithoutResourceInstances() { + // try{ + String userId = USER_ID; + // Either<Service, StorageOperationStatus> deleteService = + // serviceOperation.deleteService(UniqueIdBuilder.buildServiceUniqueId("my-service", + // "1.0"), false); + // log.info("testCloneServiceWithoutResourceInstances - after delete + // service. result is="+deleteService); + Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true); + + // add artifacts + addArtifactToService(userId, origService.getUniqueId(), "install_apache"); + addArtifactToService(userId, origService.getUniqueId(), "start_apache"); + + Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), + false); + assertTrue(service2.isLeft()); + origService = service2.left().value(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + String json = prettyGson.toJson(origService); + log.debug(json); + + Service fullService = origService; + + Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", + false); + assertTrue(createService.isLeft()); + Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation + .getServiceByNameAndVersion("my-service", "2.0", null, false); + assertTrue(serviceAfterCreate.isLeft()); + fullService = serviceAfterCreate.left().value(); + + Either<Service, StorageOperationStatus> getOrigService = serviceOperation + .getServiceByNameAndVersion("my-service", "1.0", null, false); + assertTrue(getOrigService.isLeft()); + origService = getOrigService.left().value(); + + // assertEquals(origService.getComponentMetadataDefinition(), + // fullService.getComponentMetadataDefinition()); + assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size()); + assertEquals(origService.getComponentInstances(), fullService.getComponentInstances()); + assertEquals(origService.getComponentInstancesRelations(), fullService.getComponentInstancesRelations()); + + origService.setUniqueId(fullService.getUniqueId()); + origService.setVersion(fullService.getVersion()); + + assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); + assertEquals(origService.getCategories(), fullService.getCategories()); + + serviceOperation.deleteService(getOrigService.left().value().getUniqueId()); + serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); + + // } finally { + // titanDao.rollback(); + // } + } + + // @Test + public void testCloneServiceWithoutArtifacts() { + // try{ + + String userId = USER_ID; + + Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true); + + // add resource instances + ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest(); + riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, + resourceOperation, propertyOperation, resourceInstanceOperation); + riTest.addResourceInstancesAndRelation(origService.getUniqueId()); + + Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), + false); + assertTrue(service2.isLeft()); + origService = service2.left().value(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + String json = prettyGson.toJson(origService); + log.debug(json); + + Service fullService = origService; + + Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", + false); + assertTrue(createService.isLeft()); + Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation + .getServiceByNameAndVersion("my-service", "2.0", null, false); + assertTrue(serviceAfterCreate.isLeft()); + fullService = serviceAfterCreate.left().value(); + + Either<Service, StorageOperationStatus> getOrigService = serviceOperation + .getServiceByNameAndVersion("my-service", "1.0", null, false); + assertTrue(getOrigService.isLeft()); + origService = getOrigService.left().value(); + + assertEquals(origService.getArtifacts(), fullService.getArtifacts()); + assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size()); + assertEquals(origService.getComponentInstancesRelations().size(), + fullService.getComponentInstancesRelations().size()); + + origService.setUniqueId(fullService.getUniqueId()); + origService.setVersion(fullService.getVersion()); + + assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); + assertEquals(origService.getCategories(), fullService.getCategories()); + + serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); + serviceOperation.deleteService(getOrigService.left().value().getUniqueId()); + + // } finally { + // titanDao.rollback(); + // } + } + + // @Test + public void testCloneServiceSimple() { + // try{ + String userId = USER_ID; + String serviceName = "serviceToClone"; + // + // Either<Service, StorageOperationStatus> deleteService = + // serviceOperation.deleteService(UniqueIdBuilder.buildServiceUniqueId(serviceName, + // "1.0")); + // log.info("testCloneServiceSimple - after delete service. result + // is="+deleteService); + + Service origService = createService(userId, CATEGORY_NAME, serviceName, "1.0", true); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + String json = prettyGson.toJson(origService); + log.debug(json); + + Service fullService = origService; + + Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", + false); + assertTrue(createService.isLeft()); + Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation + .getServiceByNameAndVersion(serviceName, "2.0", null, false); + assertTrue(serviceAfterCreate.isLeft()); + fullService = serviceAfterCreate.left().value(); + + Either<Service, StorageOperationStatus> getOrigService = serviceOperation + .getServiceByNameAndVersion(serviceName, "1.0", null, false); + assertTrue(getOrigService.isLeft()); + origService = getOrigService.left().value(); + + // assertEquals(origService.getComponentMetadataDefinition(), + // fullService.getComponentMetadataDefinition()); + assertEquals(origService.getArtifacts(), fullService.getArtifacts()); + assertEquals(origService.getComponentInstances(), fullService.getComponentInstances()); + assertEquals(origService.getComponentInstancesRelations(), fullService.getComponentInstancesRelations()); + origService.setUniqueId(fullService.getUniqueId()); + origService.setVersion(fullService.getVersion()); + + assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition()); + assertEquals(origService.getCategories(), fullService.getCategories()); + + serviceOperation.deleteService(getOrigService.left().value().getUniqueId()); + serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId()); + + // } finally { + // titanDao.rollback(); + // } + } + + private Service buildServiceMetadata(String userId, String category, String serviceName, String serviceVersion) { + + Service service = new Service(); + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setDescription("description 1"); + + service.setCreatorUserId(userId); + service.setContactId("contactId@sdc.com"); + CategoryDefinition categoryDef = new CategoryDefinition(); + categoryDef.setName(category); + + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(categoryDef); + service.setCategories(categories); + + service.setIcon("images/my.png"); + List<String> tags = new ArrayList<String>(); + tags.add("TAG1"); + tags.add("TAG2"); + service.setTags(tags); + return service; + } + + private void deleteAndCreateCategory(String category) { + String[] names = category.split("/"); + OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao); + OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao); + + /* + * CategoryData categoryData = new CategoryData(); + * categoryData.setName(category); + * + * titanDao.deleteNode(categoryData, CategoryData.class); + * Either<CategoryData, TitanOperationStatus> createNode = + * titanDao.createNode(categoryData, CategoryData.class); + * System.out.println("after creating caetgory " + createNode); + */ + + } + + private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setFirstName(firstName); + userData.setLastName(lastName); + if (role != null && !role.isEmpty()) { + userData.setRole(role); + } else { + userData.setRole("ADMIN"); + } + + titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class); + titanDao.createNode(userData, UserData.class); + titanDao.commit(); + + return userData; + } + + @Test + public void testCatalogService() { + String userId = USER_ID; + String category = CATEGORY_NAME; + String serviceName = "MyService"; + String serviceVersion = "0.1"; + Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true); + log.debug("{}", serviceAfterSave); + String serviceId = serviceAfterSave.getUniqueId(); + + Map<String, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); + + Either<Set<Service>, StorageOperationStatus> catalog = serviceOperation.getCatalogData(propertiesToMatch, + false); + assertTrue(catalog.isLeft()); + Set<Service> catalogSet = catalog.left().value(); + Set<String> idSet = new HashSet<>(); + for (Service service : catalogSet) { + idSet.add(service.getUniqueId()); + } + assertTrue(idSet.contains(serviceId)); + serviceOperation.deleteService(serviceId); + } + + @After + public void teardown() { + clearGraph(); + } + + private void clearGraph() { + Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable<TitanVertex> vertices = graph.query().vertices(); + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + // graph.removeVertex(vertex); + vertex.remove(); + } + + } + titanDao.commit(); + } + + @Test + public void testTesterFollowed() { + String serviceName = "Test1"; + String serviceName2 = "Test2"; + String serviceName3 = "Test3"; + String userId = USER_ID; + String testerUserId = "tt0004"; + String category = CATEGORY_NAME; + deleteAndCreateUser(testerUserId, "tester", "last", "TESTER"); + // deleteAndCreateCategory(category); + + String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); + Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class); + User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); + Either<UserData, TitanOperationStatus> findTesterUser = titanDao.getNode(key, testerUserId, UserData.class); + User testerUser = OperationTestsUtil.convertUserDataToUser(findTesterUser.left().value()); + + // Create 3 new services + Service resultService = createService(userId, category, serviceName, "0.1", false); + log.debug("{}", resultService); + String serviceId = resultService.getUniqueId(); + Service resultService2 = createService(userId, category, serviceName2, "0.1", false); + log.debug("{}", resultService2); + String serviceId2 = resultService2.getUniqueId(); + Service resultService3 = createService(userId, category, serviceName3, "0.1", false); + log.debug("{}", resultService3); + String serviceId3 = resultService3.getUniqueId(); + + // update 1 service to READY_FOR_CERTIFICATION + Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); + Service RFCService = (Service) certReqResponse.left().value(); + assertEquals(RFCService.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION); + + // update 1 service to CERTIFICATION_IN_PROGRESS + Either<? extends Component, StorageOperationStatus> startCertificationResponse = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService2, testerUser, adminUser, false); + Service IPService = (Service) startCertificationResponse.left().value(); + assertEquals(IPService.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>(); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + Either<List<Service>, StorageOperationStatus> services = serviceOperation.getTesterFollowed(testerUserId, + lifecycleStates, false); + + assertTrue(services.isLeft()); + List<Service> result = services.left().value(); + + List<String> ids = new ArrayList<>(); + for (Service service : result) { + ids.add(service.getUniqueId()); + } + assertTrue(ids.contains(serviceId)); + assertTrue(ids.contains(serviceId2)); + assertFalse(ids.contains(serviceId3)); + serviceOperation.deleteService(serviceId); + serviceOperation.deleteService(serviceId2); + serviceOperation.deleteService(serviceId3); + + } + + @Test + public void testOpsFollowed() { + String serviceName = "Test1"; + String serviceName2 = "Test2"; + String serviceName3 = "Test3"; + String serviceName4 = "Test4"; + String userId = USER_ID; + String category = CATEGORY_NAME; + String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); + Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class); + User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); + + // Create 4 new services + Service resultService = createService(userId, category, serviceName, "0.1", false); + log.debug("{}", resultService); + String serviceId = resultService.getUniqueId(); + Service resultService2 = createService(userId, category, serviceName2, "0.1", false); + log.debug("{}", resultService2); + String serviceId2 = resultService2.getUniqueId(); + Service resultService3 = createService(userId, category, serviceName3, "0.1", false); + log.debug("{}", resultService3); + String serviceId3 = resultService3.getUniqueId(); + Service resultService4 = createService(userId, category, serviceName4, "0.1", false); + log.debug("{}", resultService3); + String serviceId4 = resultService4.getUniqueId(); + + // update 1 service to CERTIFIED dist status DISTRIBUTED + Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); + Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); + Service actualService = (Service) startCertificationResult.left().value(); + + Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation + .certifyComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); + Service certifiedService = (Service) certResponse.left().value(); + serviceOperation.updateDestributionStatus(resultService, adminUser, DistributionStatusEnum.DISTRIBUTED); + + // update 1 service to CERTIFIED dist status DISTRIBUTION_APPROVED + Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); + Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); + Service actualService2 = (Service) startCertificationResult2.left().value(); + + Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation + .certifyComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); + Service certifiedService2 = (Service) certResponse2.left().value(); + serviceOperation.updateDestributionStatus(resultService2, adminUser, + DistributionStatusEnum.DISTRIBUTION_APPROVED); + + // update 1 service to CERTIFIED dist status DISTRIBUTION_REJECTED + Either<? extends Component, StorageOperationStatus> reqCertificationResult3 = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false); + Either<? extends Component, StorageOperationStatus> startCertificationResult3 = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false); + Service actualService3 = (Service) startCertificationResult3.left().value(); + + Either<? extends Component, StorageOperationStatus> certResponse3 = lifecycleOperation + .certifyComponent(NodeTypeEnum.Service, actualService3, adminUser, adminUser, false); + Service certifiedService3 = (Service) certResponse3.left().value(); + serviceOperation.updateDestributionStatus(certifiedService3, adminUser, + DistributionStatusEnum.DISTRIBUTION_REJECTED); + + Map<String, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); + + Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>(); + distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); + distStatus.add(DistributionStatusEnum.DISTRIBUTED); + + Either<Set<Service>, StorageOperationStatus> services = serviceOperation + .getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false); + + assertTrue(services.isLeft()); + Set<Service> result = services.left().value(); + + List<String> ids = new ArrayList<>(); + for (Service service : result) { + ids.add(service.getUniqueId()); + } + assertTrue(ids.contains(certifiedService.getUniqueId())); + assertTrue(ids.contains(certifiedService2.getUniqueId())); + assertFalse(ids.contains(certifiedService3.getUniqueId())); + assertFalse(ids.contains(resultService4.getUniqueId())); + serviceOperation.deleteService(serviceId); + serviceOperation.deleteService(serviceId2); + serviceOperation.deleteService(serviceId3); + serviceOperation.deleteService(serviceId4); + } + + @Test + public void testGovernorFollowed() { + String serviceName = "Test1"; + String serviceName2 = "Test2"; + String serviceName3 = "Test3"; + String userId = USER_ID; + String category = CATEGORY_NAME; + String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); + Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class); + User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value()); + + // Create 3 new services + Service resultService = createService(userId, category, serviceName, "0.1", false); + log.debug("{}", resultService); + String serviceId = resultService.getUniqueId(); + Service resultService2 = createService(userId, category, serviceName2, "0.1", false); + log.debug("{}", resultService2); + String serviceId2 = resultService2.getUniqueId(); + Service resultService3 = createService(userId, category, serviceName3, "0.1", false); + log.debug("{}", resultService3); + String serviceId3 = resultService3.getUniqueId(); + + // update 1 service to CERTIFIED + DISTRIBUTED + Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); + Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false); + Service actualService = (Service) startCertificationResult.left().value(); + + Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation + .certifyComponent(NodeTypeEnum.Service, actualService, adminUser, adminUser, false); + Service certifiedService = (Service) certResponse.left().value(); + serviceOperation.updateDestributionStatus(certifiedService, adminUser, DistributionStatusEnum.DISTRIBUTED); + + // update 1 service to CERTIFIED dist status + DISTRIBUTION_REJECTED + Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation + .requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); + Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation + .startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false); + Service actualService2 = (Service) startCertificationResult2.left().value(); + + Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation + .certifyComponent(NodeTypeEnum.Service, actualService2, adminUser, adminUser, false); + Service certifiedService2 = (Service) certResponse2.left().value(); + serviceOperation.updateDestributionStatus(certifiedService2, adminUser, DistributionStatusEnum.DISTRIBUTED); + + Map<String, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); + + Either<Set<Service>, StorageOperationStatus> services = serviceOperation + .getCertifiedServicesWithDistStatus(propertiesToMatch, null, false); + + assertTrue(services.isLeft()); + Set<Service> result = services.left().value(); + + List<String> ids = new ArrayList<>(); + for (Service service : result) { + ids.add(service.getUniqueId()); + } + assertTrue(ids.contains(certifiedService.getUniqueId())); + assertTrue(ids.contains(certifiedService2.getUniqueId())); + assertFalse(ids.contains(serviceId3)); + serviceOperation.deleteService(serviceId); + serviceOperation.deleteService(serviceId2); + serviceOperation.deleteService(serviceId3); + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java new file mode 100644 index 0000000000..f77e477ed7 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java @@ -0,0 +1,239 @@ +/*- + * ============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.model.operations.impl; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Property; +import org.apache.tinkerpop.gremlin.structure.Vertex; +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.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ModelTestBase; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.api.UserRoleEnum; + +import fj.data.Either; + +public class UserAdminOperationTest extends ModelTestBase { + @InjectMocks + private static final UserAdminOperation userAdminOperation = new UserAdminOperation(); + private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class); + + private static final String ADMIN = "admin"; + + @BeforeClass + public static void setup() { + ModelTestBase.init(); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Mockito.reset(titanGenericDao); + mockTitanUpdate(); + mockTitanDelete(); + + } + + @Test + public void testDeActivateUserDataSuccess() { + UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + + Either<User, StorageOperationStatus> eitherUser = userAdminOperation + .deActivateUser(userAdminOperation.convertToUser(userData)); + + verify(titanGenericDao, times(1)).updateNode(Mockito.eq(userData), Mockito.eq(UserData.class)); + verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); + assertTrue(eitherUser.isLeft()); + User user = eitherUser.left().value(); + assertTrue(user.getStatus() == UserStatusEnum.INACTIVE); + + } + + /* + * @Test public void testDeActivateUserDataFail(){ UserData userData = + * mockTitanGet(ADMIN, UserRoleEnum.ADMIN, false); + * + * Either<User, StorageOperationStatus> eitherUser = + * userAdminOperation.deActivateUser(userAdminOperation.convertToUser( + * userData)); + * + * verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), + * Mockito.eq(UserData.class)); verify(titanGenericDao, + * times(0)).deleteNode(Mockito.any(UserData.class), + * Mockito.eq(UserData.class)); assertTrue(eitherUser.isRight()); + * assertTrue(eitherUser.right().value() == + * StorageOperationStatus.USER_INACTIVE); + * + * } + */ + + @Test + public void testDeleteUserWithoutResources() { + UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + + List<Edge> edgesList = new ArrayList<Edge>(); + + Either<List<Edge>, TitanOperationStatus> eitherResult = Either.left(edgesList); + when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + + Either<User, ActionStatus> eitherUser = userAdminOperation.deleteUserData(ADMIN); + verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); + verify(titanGenericDao, times(1)).deleteNode(userData, UserData.class); + assertTrue(eitherUser.isLeft()); + + } + + @Test + public void testDeleteUserWithResources() { + UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, true); + + List<Edge> edgesList = new ArrayList<Edge>(); + edgesList.add(getEmptyEdgeImpl()); + + Either<List<Edge>, TitanOperationStatus> eitherResult = Either.left(edgesList); + when(titanGenericDao.getEdgesForNode(userData, Direction.BOTH)).thenReturn(eitherResult); + + Either<User, ActionStatus> eitherUser = userAdminOperation.deleteUserData(ADMIN); + verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); + verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); + assertTrue(eitherUser.isRight()); + assertTrue(eitherUser.right().value() == ActionStatus.USER_HAS_ACTIVE_ELEMENTS); + + } + + private Edge getEmptyEdgeImpl() { + return new Edge() { + + @Override + public Object id() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String label() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Graph graph() { + // TODO Auto-generated method stub + return null; + } + + @Override + public <V> Property<V> property(String key, V value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void remove() { + // TODO Auto-generated method stub + + } + + @Override + public Iterator<Vertex> vertices(Direction direction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <V> Iterator<Property<V>> properties(String... propertyKeys) { + // TODO Auto-generated method stub + return null; + } + + }; + } + + private UserData mockTitanGet(String userId, UserRoleEnum role, boolean isActive) { + UserData userData = buildUserData(userId, role, isActive); + Either<UserData, TitanOperationStatus> eitherUserData = Either.left(userData); + when(titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class)) + .thenReturn(eitherUserData); + return userData; + } + + private static void mockTitanUpdate() { + doAnswer(new Answer<Either<UserData, TitanOperationStatus>>() { + public Either<UserData, TitanOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + UserData retValue = (UserData) args[0]; + Either<UserData, TitanOperationStatus> result = Either.left(retValue); + return result; + } + + }).when(titanGenericDao).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); + } + + private static void mockTitanDelete() { + doAnswer(new Answer<Either<UserData, TitanOperationStatus>>() { + public Either<UserData, TitanOperationStatus> answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + UserData retValue = (UserData) args[0]; + Either<UserData, TitanOperationStatus> result = Either.left(retValue); + return result; + } + + }).when(titanGenericDao).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); + } + + private static UserData buildUserData(String userId, UserRoleEnum role, boolean isActive) { + UserData userData = new UserData(); + userData.setUserId(userId); + userData.setRole(role.getName()); + userData.setStatus(isActive ? UserStatusEnum.ACTIVE.name() : UserStatusEnum.INACTIVE.name()); + return userData; + + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java new file mode 100644 index 0000000000..2b9c296eb5 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/DataTypeValidatorTest.java @@ -0,0 +1,1004 @@ +/*- + * ============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.model.operations.impl.util; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertNotNull; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.model.tosca.converters.ListConverter; +import org.openecomp.sdc.be.model.tosca.converters.MapConverter; +import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; +import org.openecomp.sdc.be.model.tosca.validators.ListValidator; +import org.openecomp.sdc.be.model.tosca.validators.MapValidator; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +import fj.data.Either; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DataTypeValidatorTest { + private static Logger log = LoggerFactory.getLogger(DataTypeValidatorTest.class.getName()); + private static Gson gson = new Gson(); + + DataTypeValidatorConverter dataTypeValidator = DataTypeValidatorConverter.getInstance(); + + @Test + public void testDerivedFromPrimitiveEmptyValue() { + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + allDataTypes.put("integer", getPrimitiveDataType("integer")); + + DataTypeDefinition fromIntegerType = buildDerivedFromIntegerType(); + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate("", fromIntegerType, + allDataTypes); + + assertTrue("check result is valid", validate.right.booleanValue()); + assertEquals("check value is the same as sent", null, validate.left); + + validate = dataTypeValidator.validateAndUpdate(null, fromIntegerType, allDataTypes); + + assertTrue("check result is valid", validate.right.booleanValue()); + assertEquals("check value is the same as sent", null, validate.left); + + validate = dataTypeValidator.validateAndUpdate("88", fromIntegerType, allDataTypes); + + assertTrue("check result is valid", validate.right.booleanValue()); + assertEquals("check value is the same as sent", "88", validate.left.toString()); + + } + + @Test + public void testCompositeWithParameterDerivedFromPrimitiveEmptyValue() { + + DataTypeDefinition derivedFromIntegerType = buildDerivedFromIntegerType(); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + allDataTypes.put("myinteger", derivedFromIntegerType); + + DataTypeDefinition personDataType = buildPersonDataType(); + + Person person = new Person("my address", 32); + String json = gson.toJson(person); + log.debug(json); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, personDataType, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + person = new Person("my address", 32); + json = gson.toJson(person); + json = json.replace("32", "32a"); + log.debug(json); + + validate = dataTypeValidator.validateAndUpdate(json, personDataType, allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); + + } + + @Test + public void testCompositeWithEmptyListValue() { + + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + String[] strArr = {}; + List<String> strList = Arrays.asList(strArr); + + // Check empty list + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, strList); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + log.debug(json); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertEquals("check empty list", 0, credentialRes.getMylist().size()); + + log.debug("Result is = {}", validate.left.toString()); + + } + + @Test + public void testCompositeWithListNullValue() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check list is NULL + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNull("check list is null", credentialRes.getMylist()); + log.debug("Result is = {}", validate.left.toString()); + + } + + @Test + public void testCompositeWithUserNullValue() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check user is null + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNull("check list is null", credentialRes.getUser()); + log.debug("Result is = {}", validate.left.toString()); + } + + @Test + public void testCompositeWithEmptyUserValue() { + + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + // Check user is empty + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "", true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + log.debug(json); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNotNull("check list is not null", credentialRes.getUser()); + assertEquals("check user is empty", "", credentialRes.getUser()); + log.debug("Result is = {}", validate.left.toString()); + + } + + @Test + public void testCompositeWithSumNullValue() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + Credential credentialRes = gson.fromJson(validate.left.toString(), Credential.class); + assertNull("check list is null", credentialRes.getSum()); + log.debug("Result is = {}", validate.left.toString()); + } + + @Test + public void testInvalidJson() { + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + json += "fdfd"; + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); + + } + + @Test + public void testInvalidInnerValue() { + + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + json = json.replace("55", "a55b"); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); + + } + + @Test + public void testInvalidInnerJson() { + + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("", null); + + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + json = json.replace("{\"address\":\"\"}", "scalar"); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); + + } + + @Test + public void testInvalidPropertyJson() { + + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + // Check user is null + Credential credential = new Credential("protcol<br>>", null, "token_type", "token", null, null, true, null); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + json = json.replace("55", "a55b"); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertFalse("check valid value", validate.right.booleanValue()); + + } + + @Test + public void testCompositeDataTypeWithInternalComposite() { + + DataTypeDefinition dataTypeDefinition = buildCredentialDataType(); + + String[] strArr = { "aaa", "bbb", "c<br>dcc" }; + List<String> strList = Arrays.asList(strArr); + + Credential credential = new Credential("protcol<br>>", 5, "token_type", "token", null, "user", true, strList); + City mycity = new City("myadd<br><<br>", 55); + credential.setMycity(mycity); + + String json = gson.toJson(credential); + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + ImmutablePair<JsonElement, Boolean> validate = dataTypeValidator.validateAndUpdate(json, dataTypeDefinition, + allDataTypes); + assertTrue("check valid value", validate.right.booleanValue()); + + log.debug("Result is = {}", validate.left.toString()); + + } + + @Test + public void testMapValidator() { + + MapValidator validator = new MapValidator(); + Gson gson = new Gson(); + // Happy Scenarios + // 1 - Map<String,Integer> check OK + Map<String, Integer> map_1 = new HashMap<>(); + map_1.put("key1", 2); + map_1.put("key2", 3); + String value = gson.toJson(map_1); + String innerType = "integer"; + assertTrue("Test Map validation with inner integer type", validator.isValid(value, innerType, null)); + + // 2 - Map<String,Boolean> check OK + Map<String, Boolean> map_2 = new HashMap<>(); + map_2.put("key1", true); + map_2.put("key2", false); + value = gson.toJson(map_2); + innerType = "boolean"; + assertTrue("Test Map validation with inner boolean type", validator.isValid(value, innerType, null)); + + // 3 - give integer with quotes + innerType = "integer"; + value = "{\"key1\":\"5\",\"key2\":\"7\"}"; + assertTrue("Test Map validation with inner integer type, but qouted values", + validator.isValid(value, innerType, null)); + + // 4 - empty default value + innerType = "float"; + value = ""; + assertTrue("Test Map validation with inner float type", validator.isValid(value, innerType, null)); + + // Faulty Scenarios + // 5 - mismatch in data type + value = gson.toJson(map_1); + innerType = "boolean"; + assertFalse("Test Map faulty validation with inner boolean type", validator.isValid(value, innerType, null)); + // 6 - mismatch in data type + value = gson.toJson(map_2); + innerType = "integer"; + assertFalse("Test Map faulty validation with inner integer type", validator.isValid(value, innerType, null)); + + } + + @Test + public void testMapConverter() { + + MapConverter converter = new MapConverter(); + Gson gson = new Gson(); + // Happy Scenarios + Map<String, String> map_1 = new HashMap<>(); + Map<String, String> resMap_1 = new HashMap<>(); + + // 1 - check Spaces eliminated + html square brackets eliminated + map_1.put("key1", "<b>test</b>"); + map_1.put("key2", " test"); + resMap_1.put("key1", "test"); + resMap_1.put("key2", " test"); + String value = gson.toJson(map_1); + String expectedVal = gson.toJson(resMap_1); + String innerType = "string"; + assertEquals("Test Map validation with inner string type", expectedVal, + converter.convert(value, innerType, null)); + + // 2 - float converter + innerType = "float"; + value = "{\"key1\":0.4545,\"key2\":0.2f}"; + expectedVal = "{\"key1\":0.4545,\"key2\":0.2}"; + assertEquals("Test Map validation with inner float type", expectedVal, + converter.convert(value, innerType, null)); + + // 3 - check default empty value converter + innerType = "float"; + value = ""; + expectedVal = ""; + assertEquals("Test Map validation with inner float type", expectedVal, + converter.convert(value, innerType, null)); + + // 4 - invalid json + // 3 - check default empty value converter + innerType = "float"; + value = "{1345234556@#("; + expectedVal = null; + assertEquals("Test Map validation with inner float type", expectedVal, + converter.convert(value, innerType, null)); + + } + + @Test + public void testCompositeDataTypeWithMapComposite() { + + DataTypeDefinition fileDataTypeDefinition = buildFileDataType(); + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + + MyFile myFile = new MyFile(); + myFile.setAge(88); + Map<String, City> attributes = new HashMap<>(); + attributes.put("key1", new City("address1<br>", 11)); + attributes.put("key2", new City("address2<br>", 22)); + myFile.setAttributes(attributes); + + String str = gson.toJson(myFile); + log.debug(str); + + ImmutablePair<JsonElement, Boolean> convert = dataTypeValidator.validateAndUpdate(str, fileDataTypeDefinition, + allDataTypes); + + assertTrue("check map converter succeed", convert.right); + + JsonElement convertedValue = convert.left; + + log.debug("{}", convertedValue); + MyFile fromJson = gson.fromJson(convertedValue, MyFile.class); + + assertEquals("check age", 88, fromJson.getAge().intValue()); + assertEquals("check address 1", "address1", fromJson.getAttributes().get("key1").getAddress()); + assertEquals("check address 2", "address2", fromJson.getAttributes().get("key2").getAddress()); + + } + + @Test + public void testMapConverterWithComplexInnerType() { + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); + + Gson gson = new Gson(); + // Happy Scenarios + Map<String, Object> map_1 = new HashMap<>(); + + // 1 - check Spaces eliminated + html square brackets eliminated + + String[] strArr = { "aaa", "bbb", "c<br>dcc" }; + List<String> strList = Arrays.asList(strArr); + Credential credential1 = new Credential("protocol;:,.\"<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity1 = new City("myadd<br><<br>", 55); + credential1.setMycity(mycity1); + + Credential credential2 = new Credential("protocol;:,.\"<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity2 = new City("myadd<br><<br>", 66); + credential2.setMycity(mycity2); + + map_1.put("key1", credential1); + map_1.put("key2", credential2); + + String str = gson.toJson(map_1); + log.debug(str); + + MapConverter mapConverter = new MapConverter(); + Either<String, Boolean> convert = mapConverter.convertWithErrorResult(str, "credential", allDataTypes); + + assertTrue("check map converter succeed", convert.isLeft()); + + String convertedValue = convert.left().value(); + + Type type = new TypeToken<Map<String, Credential>>() { + }.getType(); + + Map<String, Credential> fromJson = gson.fromJson(convertedValue, type); + + Credential actualCredential1 = fromJson.get("key1"); + assertEquals("check sum", 5, actualCredential1.getSum().intValue()); + assertEquals("check protocol", "protocol;:,.\">", actualCredential1.getProtocol()); + String[] convertedStrArr = { "aaa", "bbb", "cdcc" }; + List<String> convertedStrList = Arrays.asList(convertedStrArr); + assertEquals("check list", convertedStrList, actualCredential1.getMylist()); + + assertEquals("check city address", "myadd<", actualCredential1.getMycity().getAddress()); + assertEquals("check city address", 55, actualCredential1.getMycity().getAge().intValue()); + + Credential actualCredential2 = fromJson.get("key2"); + assertEquals("check city address", 66, actualCredential2.getMycity().getAge().intValue()); + + } + + @Test + public void testListConverterWithComplexInnerType() { + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); + + Gson gson = new Gson(); + + List<Object> list = buildListOf2CredentialObjects(); + + String str = gson.toJson(list); + log.debug(str); + + ListConverter listConverter = new ListConverter(); + + Either<String, Boolean> convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); + + assertTrue("check map converter succeed", convert.isLeft()); + + String convertedValue = convert.left().value(); + + validateListOfCredential(gson, convertedValue); + + list.add(null); + + str = gson.toJson(list); + log.debug(str); + + convert = listConverter.convertWithErrorResult(str, "credential", allDataTypes); + + assertTrue("check map converter succeed", convert.isLeft()); + + validateListOfCredential(gson, convertedValue); + } + + @Test + public void testListValidatorWithComplexInnerType() { + + Map<String, DataTypeDefinition> allDataTypes = new HashMap<String, DataTypeDefinition>(); + DataTypeDefinition credentialDataTypeDefinition = buildCredentialDataType(); + DataTypeDefinition cityDataType = buildCityDataType(); + allDataTypes.put("city", cityDataType); + allDataTypes.put("credential", credentialDataTypeDefinition); + + Gson gson = new Gson(); + // Happy Scenarios + List<Object> list = buildListOf2CredentialObjects(); + + String str = gson.toJson(list); + log.debug(str); + + ListValidator listValidator = new ListValidator(); + + boolean isValid = listValidator.isValid(str, "credential", allDataTypes); + + assertTrue("check valid value", isValid); + + String badStr = str.replace("protocol", "protocol1"); + + isValid = listValidator.isValid(badStr, "credential", allDataTypes); + + assertFalse("check valid value", isValid); + + badStr = str.replace("55", "\"aa\""); + + isValid = listValidator.isValid(badStr, "credential", allDataTypes); + + assertFalse("check valid value", isValid); + + } + + private List<Object> buildListOf2CredentialObjects() { + List<Object> list = new ArrayList<>(); + + String[] strArr = { "aaa", "bbb", "c<br>dcc" }; + List<String> strList = Arrays.asList(strArr); + Credential credential1 = new Credential("protocol.,\":;<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity1 = new City("myadd<br><<br>", 55); + credential1.setMycity(mycity1); + + Credential credential2 = new Credential("protocol.,\":;<br>>", 5, "token_type", "token", null, "user", true, + strList); + City mycity2 = new City("myadd<br><<br>", 66); + credential2.setMycity(mycity2); + + list.add(credential1); + list.add(credential2); + return list; + } + + private void validateListOfCredential(Gson gson, String convertedValue) { + + log.debug(convertedValue); + Type type = new TypeToken<List<Credential>>() { + }.getType(); + + List<Credential> fromJson = gson.fromJson(convertedValue, type); + + assertEquals("check list size", 2, fromJson.size()); + + // Credential actualCredential1 = gson.fromJson(list.get(0).toString(), + // Credential.class); + Credential actualCredential1 = fromJson.get(0); + assertEquals("check sum", 5, actualCredential1.getSum().intValue()); + assertEquals("check protocol", "protocol.,\":;>", actualCredential1.getProtocol()); + String[] convertedStrArr = { "aaa", "bbb", "cdcc" }; + List<String> convertedStrList = Arrays.asList(convertedStrArr); + assertEquals("check list", convertedStrList, actualCredential1.getMylist()); + + assertEquals("check city address", "myadd<", actualCredential1.getMycity().getAddress()); + assertEquals("check city address", 55, actualCredential1.getMycity().getAge().intValue()); + + // Credential actualCredential2 = gson.fromJson(list.get(1).toString(), + // Credential.class); + Credential actualCredential2 = fromJson.get(1); + assertEquals("check city address", 66, actualCredential2.getMycity().getAge().intValue()); + } + + private DataTypeDefinition buildCredentialDataType() { + DataTypeDefinition dataTypeDefinition = new DataTypeDefinition(); + dataTypeDefinition.setName("datatype.1"); + List<PropertyDefinition> properties = new ArrayList<>(); + PropertyDefinition propertyDefinition1 = new PropertyDefinition(); + propertyDefinition1.setName("sum"); + propertyDefinition1.setType(ToscaPropertyType.INTEGER.getType()); + PropertyDefinition propertyDefinition2 = new PropertyDefinition(); + propertyDefinition2.setName("protocol"); + propertyDefinition2.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition3 = new PropertyDefinition(); + propertyDefinition3.setName("token_type"); + propertyDefinition3.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition4 = new PropertyDefinition(); + propertyDefinition4.setName("token"); + propertyDefinition4.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition5 = new PropertyDefinition(); + propertyDefinition5.setName("keys"); + propertyDefinition5.setType(ToscaPropertyType.MAP.getType()); + PropertyDefinition propertyDefinition6 = new PropertyDefinition(); + propertyDefinition6.setName("mylist"); + propertyDefinition6.setType(ToscaPropertyType.LIST.getType()); + SchemaDefinition entrySchema = new SchemaDefinition(); + PropertyDataDefinition property = new PropertyDataDefinition(); + property.setType("string"); + entrySchema.setProperty(property); + propertyDefinition6.setSchema(entrySchema); + PropertyDefinition propertyDefinition7 = new PropertyDefinition(); + propertyDefinition7.setName("user"); + propertyDefinition7.setType(ToscaPropertyType.STRING.getType()); + PropertyDefinition propertyDefinition8 = new PropertyDefinition(); + propertyDefinition8.setName("isMandatory"); + propertyDefinition8.setType(ToscaPropertyType.BOOLEAN.getType()); + + PropertyDefinition propertyDefinition9 = new PropertyDefinition(); + propertyDefinition9.setName("mycity"); + propertyDefinition9.setType("city"); + + properties.add(propertyDefinition1); + properties.add(propertyDefinition2); + properties.add(propertyDefinition3); + properties.add(propertyDefinition4); + properties.add(propertyDefinition5); + properties.add(propertyDefinition6); + properties.add(propertyDefinition7); + properties.add(propertyDefinition8); + properties.add(propertyDefinition9); + + dataTypeDefinition.setProperties(properties); + return dataTypeDefinition; + } + + private static DataTypeDefinition buildCityDataType() { + DataTypeDefinition cityDataType = new DataTypeDefinition(); + cityDataType.setName("city"); + List<PropertyDefinition> cityProperties = new ArrayList<>(); + PropertyDefinition cityPropertyDefinition1 = new PropertyDefinition(); + cityPropertyDefinition1.setName("age"); + cityPropertyDefinition1.setType(ToscaPropertyType.INTEGER.getType()); + PropertyDefinition cityPropertyDefinition2 = new PropertyDefinition(); + cityPropertyDefinition2.setName("address"); + cityPropertyDefinition2.setType(ToscaPropertyType.STRING.getType()); + + cityProperties.add(cityPropertyDefinition1); + cityProperties.add(cityPropertyDefinition2); + + cityDataType.setProperties(cityProperties); + return cityDataType; + } + + private static DataTypeDefinition buildPersonDataType() { + DataTypeDefinition personDataType = new DataTypeDefinition(); + personDataType.setName("person"); + List<PropertyDefinition> personProperties = new ArrayList<>(); + PropertyDefinition personPropertyDefinition1 = new PropertyDefinition(); + personPropertyDefinition1.setName("age"); + personPropertyDefinition1.setType("myinteger"); + PropertyDefinition personPropertyDefinition2 = new PropertyDefinition(); + personPropertyDefinition2.setName("address"); + personPropertyDefinition2.setType(ToscaPropertyType.STRING.getType()); + + personProperties.add(personPropertyDefinition1); + personProperties.add(personPropertyDefinition2); + + personDataType.setProperties(personProperties); + return personDataType; + } + + private static DataTypeDefinition buildFileDataType() { + DataTypeDefinition fileDataType = new DataTypeDefinition(); + fileDataType.setName("file"); + List<PropertyDefinition> fileProperties = new ArrayList<>(); + PropertyDefinition filePropertyDefinition1 = new PropertyDefinition(); + filePropertyDefinition1.setName("age"); + filePropertyDefinition1.setType("integer"); + + PropertyDefinition filePropertyDefinition2 = new PropertyDefinition(); + filePropertyDefinition2.setName("attributes"); + filePropertyDefinition2.setType(ToscaPropertyType.MAP.getType()); + + fileProperties.add(filePropertyDefinition1); + fileProperties.add(filePropertyDefinition2); + + SchemaDefinition entrySchema = new SchemaDefinition(); + PropertyDataDefinition property = new PropertyDataDefinition(); + property.setType("city"); + entrySchema.setProperty(property); + filePropertyDefinition2.setSchema(entrySchema); + + fileDataType.setProperties(fileProperties); + return fileDataType; + } + + private static DataTypeDefinition getPrimitiveDataType(String type) { + + DataTypeDefinition derivedFrom = new DataTypeDefinition(); + derivedFrom.setName(type); + + return derivedFrom; + + } + + private static DataTypeDefinition buildDerivedFromIntegerType() { + + DataTypeDefinition derivedFrom = getPrimitiveDataType("integer"); + + DataTypeDefinition myIntegerDataType = new DataTypeDefinition(); + myIntegerDataType.setDerivedFrom(derivedFrom); + + myIntegerDataType.setName("myinteger"); + + return myIntegerDataType; + } + + public static class MyFile { + + Integer age; + + Map<String, City> attributes; + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Map<String, City> getAttributes() { + return attributes; + } + + public void setAttributes(Map<String, City> attributes) { + this.attributes = attributes; + } + + } + + public static class City { + + String address; + Integer age; + + public City(String address, Integer age) { + super(); + this.address = address; + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + } + + public static class Person { + + String address; + Integer age; + + public Person(String address, Integer age) { + super(); + this.address = address; + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "Person [address=" + address + ", age=" + age + "]"; + } + + } + + public static class Credential { + + String protocol; + Integer sum; + String token_type; + String token; + Map<String, String> keys; + String user; + Boolean isMandatory; + List<String> mylist; + City mycity; + + public Credential(String protocol, Integer sum, String token_type, String token, Map<String, String> keys, + String user, Boolean isMandatory, List<String> mylist) { + super(); + this.protocol = protocol; + this.sum = sum; + this.token_type = token_type; + this.token = token; + this.keys = keys; + this.user = user; + this.isMandatory = isMandatory; + this.mylist = mylist; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getToken_type() { + return token_type; + } + + public void setToken_type(String token_type) { + this.token_type = token_type; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public Map<String, String> getKeys() { + return keys; + } + + public void setKeys(Map<String, String> keys) { + this.keys = keys; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Boolean getIsMandatory() { + return isMandatory; + } + + public void setIsMandatory(Boolean isMandatory) { + this.isMandatory = isMandatory; + } + + public Integer getSum() { + return sum; + } + + public void setSum(Integer sum) { + this.sum = sum; + } + + public List<String> getMylist() { + return mylist; + } + + public void setMylist(List<String> mylist) { + this.mylist = mylist; + } + + public City getMycity() { + return mycity; + } + + public void setMycity(City mycity) { + this.mycity = mycity; + } + + @Override + public String toString() { + return "Credential [protocol=" + protocol + ", token_type=" + token_type + ", token=" + token + ", keys=" + + keys + ", user=" + user + ", isMandatory=" + isMandatory + "]"; + } + + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java new file mode 100644 index 0000000000..e356b49a10 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/OperationTestsUtil.java @@ -0,0 +1,95 @@ +/*- + * ============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.model.operations.impl.util; + +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ResourceCategoryData; +import org.openecomp.sdc.be.resources.data.ServiceCategoryData; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.be.resources.data.category.CategoryData; +import org.openecomp.sdc.be.resources.data.category.SubCategoryData; +import org.openecomp.sdc.common.util.ValidationUtils; + +import fj.data.Either; + +public class OperationTestsUtil { + + public static String deleteAndCreateServiceCategory(String category, TitanGenericDao titanDao) { + CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); + categoryData.getCategoryDataDefinition().setName(category); + categoryData.getCategoryDataDefinition() + .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); + categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( + ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ServiceNewCategory)); + titanDao.deleteNode(categoryData, CategoryData.class); + Either<CategoryData, TitanOperationStatus> createNode = titanDao.createNode(categoryData, CategoryData.class); + return (String) createNode.left().value().getUniqueId(); + } + + public static String deleteAndCreateResourceCategory(String category, String subcategory, + TitanGenericDao titanDao) { + + CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory); + categoryData.getCategoryDataDefinition().setName(category); + categoryData.getCategoryDataDefinition() + .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(category)); + categoryData.getCategoryDataDefinition().setUniqueId(UniqueIdBuilder.buildCategoryUid( + ValidationUtils.normalizeCategoryName4Uniqueness(category), NodeTypeEnum.ResourceNewCategory)); + + SubCategoryData subcategoryData = new SubCategoryData(NodeTypeEnum.ResourceSubcategory); + subcategoryData.getSubCategoryDataDefinition().setName(subcategory); + subcategoryData.getSubCategoryDataDefinition() + .setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); + subcategoryData.getSubCategoryDataDefinition().setUniqueId(UniqueIdBuilder + .buildSubCategoryUid(categoryData.getCategoryDataDefinition().getUniqueId(), subcategory)); + titanDao.deleteNode(categoryData, CategoryData.class); + titanDao.deleteNode(subcategoryData, SubCategoryData.class); + Either<CategoryData, TitanOperationStatus> createNode = titanDao.createNode(categoryData, CategoryData.class); + titanDao.createNode(subcategoryData, SubCategoryData.class); + titanDao.createRelation(categoryData, subcategoryData, GraphEdgeLabels.SUB_CATEGORY, null); + return (String) createNode.left().value().getUniqueId(); + } + + public static void deleteServiceCategory(String category, TitanGenericDao titanDao) { + ServiceCategoryData categoryData = new ServiceCategoryData(category); + titanDao.deleteNode(categoryData, ServiceCategoryData.class); + } + + public static void deleteResourceCategory(String category, String subcategory, TitanGenericDao titanDao) { + ResourceCategoryData categoryData = new ResourceCategoryData(category, subcategory); + titanDao.deleteNode(categoryData, ResourceCategoryData.class); + } + + public static User convertUserDataToUser(UserData modifierData) { + User modifier = new User(); + modifier.setUserId(modifierData.getUserId()); + modifier.setEmail(modifierData.getEmail()); + modifier.setFirstName(modifierData.getFirstName()); + modifier.setLastName(modifierData.getLastName()); + modifier.setRole(modifierData.getRole()); + return modifier; + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java new file mode 100644 index 0000000000..b58ce5598d --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/PrintGraph.java @@ -0,0 +1,461 @@ +/*- + * ============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.model.operations.impl.util; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Property; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.util.ElementHelper; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +import com.thinkaurelius.titan.core.TitanEdge; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +//import com.tinkerpop.blueprints.Direction; +//import com.tinkerpop.blueprints.Edge; +//import com.tinkerpop.blueprints.Vertex; +//import com.tinkerpop.blueprints.util.ElementHelper; + +public class PrintGraph { + + public void printGraphVertices(TitanGraph graph) { + + Iterable<TitanVertex> vertices = graph.query().vertices(); + + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + // System.out.println(vertex); + // System.out.println(ElementHelper.getProperties(vertex)); + // System.out.println("======================================="); + } + + } + // graph.commit(); + graph.tx().commit(); + } + + public void printGraphEdges(TitanGraph graph) { + + Iterable<TitanEdge> vertices = graph.query().edges(); + + if (vertices != null) { + Iterator<TitanEdge> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Edge edge = iterator.next(); + + // System.out.println(edge); + // System.out.println("edge=" + edge.getLabel() + ", + // properties="+ ElementHelper.getProperties(edge)); + // System.out.println("edge=" + edge.label() + ", properties="+ + // getProperties(edge)); + // System.out.println("======================================="); + } + + } + // graph.commit(); + graph.tx().commit(); + } + + public String buildGraphForWebgraphWiz(TitanGraph graph) { + + StringBuilder builder = new StringBuilder(); + builder.append("digraph finite_state_machine {\n"); + builder.append("rankdir=LR;\n"); + builder.append("size=\"15,10\" \n"); + // node [shape = doublecircle]; LR_0 LR_3 LR_4 LR_8; + // node [shape = circle]; + + Iterable<TitanVertex> vertices = graph.query().vertices(); + + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + // System.out.println(vertex); + // System.out.println(ElementHelper.getProperties(vertex)); + // System.out.println(getProperties(vertex)); + // System.out.println("======================================="); + + Map<String, Object> properties = getProperties(vertex); + + String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); + + String color = getColorByNodeType(nodeLabel); + + String uid = getNodeIdByLabel(nodeLabel, properties); + + // System.out.println("uid=" + uid); + + String nodeRecord = buildNodeRecord(uid, color, properties); + + // System.out.println(nodeRecord); + + builder.append(nodeRecord); + + // if (nodeLabel.equals(NodeTypeEnum.Category)) { + // + // String + // + // } else (nodeLabel.equals(NodeTypeEnum.User)) { + // + // } + + } + + } + + Iterable<TitanEdge> edges = graph.query().edges(); + + if (edges != null) { + Iterator<TitanEdge> iterator = edges.iterator(); + while (iterator.hasNext()) { + Edge edge = iterator.next(); + + // Vertex vertexFrom = edge.getVertex(Direction.OUT); + // Vertex vertexTo = edge.getVertex(Direction.IN); + Vertex vertexFrom = edge.outVertex(); + Vertex vertexTo = edge.inVertex(); + + // String fromUid = + // getNodeIdByLabel((String)vertexFrom.getProperty(GraphPropertiesDictionary.LABEL.getProperty()), + // ElementHelper.getProperties(vertexFrom)); + // String toUid = + // getNodeIdByLabel((String)vertexTo.getProperty(GraphPropertiesDictionary.LABEL.getProperty()), + // ElementHelper.getProperties(vertexTo)); + String fromUid = getNodeIdByLabel(vertexFrom.value(GraphPropertiesDictionary.LABEL.getProperty()), + getProperties(vertexFrom)); + String toUid = getNodeIdByLabel(vertexTo.value(GraphPropertiesDictionary.LABEL.getProperty()), + getProperties(vertexTo)); + + // String edgeLabel = edge.getLabel(); + String edgeLabel = edge.label(); + + // String edgeRecord = buildEdgeRecord(fromUid, toUid, + // edgeLabel, ElementHelper.getProperties(edge)); + String edgeRecord = buildEdgeRecord(fromUid, toUid, edgeLabel, getProperties(edge)); + + builder.append(edgeRecord); + + // System.out.println(edge); + // System.out.println("edge=" + edge.getLabel() + ", + // properties=" + // + ElementHelper.getProperties(edge)); + // System.out.println("edge=" + edge.label() + ", properties=" + // + getProperties(edge)); + // System.out.println("======================================="); + } + + } + + builder.append(" } "); + + return builder.toString(); + + } + + // LR_0 [ style = "bold" color = "red" shape = "Mrecord" label = + // "hello\nworld | { name | apache } | { version | 1.0 } | { uid | + // apache.1.0 } | { state| CERTIFIED } |{ b |{c|<here> d|e}| f}| g | h" + // ] + + // LR_0 -> LR_2 [ label = "SS(B)" ]; + // LR_0 -> LR_1 [ label = "SS(S)" ]; + // LR_1 -> LR_3 [ label = "S($end)" ]; + // LR_2 -> LR_6 [ label = "SS(b)" ]; + // LR_2 -> LR_5 [ label = "SS(a)" ]; + // LR_2 -> LR_4 [ label = "S(A)" ]; + // LR_5 -> LR_7 [ label = "S(b)" ]; + // LR_5 -> LR_5 [ label = "S(a)" ]; + // LR_6 -> LR_6 [ label = "S(b)" ]; + // LR_6 -> LR_5 [ label = "S(a)" ]; + // LR_7 -> LR_8 [ label = "S(b)" ]; + // LR_7 -> LR_5 [ label = "S(a)" ]; + // LR_8 -> LR_6 [ label = "S(b)" ]; + // LR_8 -> LR_5 [ label = "S(a)" ]; + + private String buildEdgeRecord(String fromUid, String toUid, String edgeLabel, Map<String, Object> properties) { + + StringBuilder builder = new StringBuilder(); + // LR_0 -> LR_2 [ label = "SS(B)" ]; + + String generatedProps = generateStringFromProperties(properties); + + String color = getEdgeColorByLabel(edgeLabel); + + builder.append("\"" + fromUid + "\"" + " -> " + "\"" + toUid + "\"" + " [ color = " + color + " label = \"" + + edgeLabel + "(" + generatedProps + ")\"" + " ] " + "\n"); + + return builder.toString(); + } + + private String getEdgeColorByLabel(String edgeLabel) { + + GraphEdgeLabels edgeLabelEnum = GraphEdgeLabels.getByName(edgeLabel); + + String color = "black"; + + switch (edgeLabelEnum) { + case PROPERTY: + color = "orange"; + break; + case CAPABILITY: + break; + case DERIVED_FROM: + color = "red"; + default: + break; + } + + return color; + } + + private String generateStringFromProperties(Map<String, Object> properties) { + + StringBuilder builder = new StringBuilder(); + + if (properties != null) { + for (Entry<String, Object> entry : properties.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue().toString(); + builder.append(key + "=" + value + "__"); + } + } + return builder.toString(); + + } + + private String buildNodeRecord(String uid, String color, Map<String, Object> properties) { + + StringBuilder builder = new StringBuilder(); + + builder.append("\"" + uid + "\"" + " [ "); + builder.append("style = \"bold\" "); + builder.append(" color = \"" + color + "\""); + builder.append("shape = \"Mrecord\" "); + + String label = ""; + int maxKeyLength = 0; + for (Entry<String, Object> entry1 : properties.entrySet()) { + String key = entry1.getKey(); + int keyLength = key.length(); + if (keyLength > maxKeyLength) { + maxKeyLength = keyLength; + } + } + + boolean first = true; + for (Entry<String, Object> entry : properties.entrySet()) { + + String key = entry.getKey(); + String value = entry.getValue().toString(); + + if (key.equals(GraphPropertiesDictionary.CONSTRAINTS.getProperty())) { + value = value.replaceAll("[^\\w\\s]", "_"); + } + + key = padKey(key, maxKeyLength); + + if (first) { + first = false; + } else { + label += " | "; + } + label += " { " + key + " | " + value + " } "; + } + + builder.append("label = \"" + label + "\" "); + builder.append(" ] "); + + // LR_0 [ style = "bold" color = "red" shape = "Mrecord" label = + // "hello\nworld | { name | apache } | { version | 1.0 } | { uid | + // apache.1.0 } | { state| CERTIFIED } |{ b |{c|<here> d|e}| f}| g | h" + // ] + + builder.append(" \n "); + return builder.toString(); + } + + private String getNodeIdByLabel(String nodeLabel, Map<String, Object> properties) { + + NodeTypeEnum typeEnum = NodeTypeEnum.getByName(nodeLabel); + + String uid = null; + switch (typeEnum) { + + case User: + uid = (String) properties.get(GraphPropertiesDictionary.USER_ID.getProperty()); + break; + case ServiceCategory: + case ResourceCategory: + case Tag: + uid = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty()); + break; + + default: + uid = (String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + break; + } + + return uid; + } + + private String getColorByNodeType(String nodeLabel) { + + NodeTypeEnum typeEnum = NodeTypeEnum.getByName(nodeLabel); + + String color = "red"; + switch (typeEnum) { + case ServiceCategory: + color = "blue"; + break; + case ResourceCategory: + color = "blue"; + break; + case Resource: + color = "forestgreen"; + break; + case User: + color = "green"; + break; + case Capability: + color = "lightgreen"; + break; + case CapabilityType: + color = "gray"; + break; + case Property: + color = "cyan"; + break; + case RelationshipType: + color = "darkorchid"; + break; + case Requirement: + color = "gold"; + break; + case RequirementImpl: + // color = "forestgreen"; + color = "gold"; + break; + case Service: + color = "cyan4"; + break; + case Tag: + color = "dimgrey"; + break; + default: + break; + + } + + return color; + } + + private String padKey(String key, int maxKeyLength) { + + int len = key.length(); + for (int i = len; i < maxKeyLength; i++) { + key += " "; + } + + return key; + } + + public int getNumberOfVertices(TitanGraph graph) { + int counter = 0; + Iterable<TitanVertex> vertices = graph.query().vertices(); + + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + counter++; + } + } + return counter; + } + + public Set<String> getVerticesSet(TitanGraph titanGraph) { + + Set<String> set = new HashSet<String>(); + + Iterable<TitanVertex> vertices = titanGraph.query().vertices(); + + if (vertices != null) { + Iterator<TitanVertex> iterator = vertices.iterator(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + + // System.out.println(vertex); + // System.out.println(ElementHelper.getProperties(vertex)); + // System.out.println(getProperties(vertex)); + // System.out.println("======================================="); + + // Map<String, Object> properties = + // ElementHelper.getProperties(vertex); + Map<String, Object> properties = getProperties(vertex); + + String nodeLabel = (String) properties.get(GraphPropertiesDictionary.LABEL.getProperty()); + + String uid = getNodeIdByLabel(nodeLabel, properties); + + set.add(uid); + } + } + + return set; + + } + + public Map<String, Object> getProperties(Element element) { + + Map<String, Object> result = null; + + if (element.keys() != null && element.keys().size() > 0) { + Map<String, Property> propertyMap = ElementHelper.propertyMap(element, + element.keys().toArray(new String[element.keys().size()])); + result = new HashMap<String, Object>(); + + for (Entry<String, Property> entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + result.put(key, value); + } + } + return result; + } + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java new file mode 100644 index 0000000000..b6b951bdc4 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/util/ResourceCreationUtils.java @@ -0,0 +1,36 @@ +/*- + * ============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.model.operations.impl.util; + +public class ResourceCreationUtils { + + public static String ATT_UID = "jm007a"; + public static String FIRST_NAME = "Julia"; + public static String LAST_NAME = "Hendrix"; + public static String DEFAULT_RESOURCE_NAME = "my-resource"; + public static String DEFAULT_RESOURCE_VERSION = "1.0"; + public static String DEFAULT_USER_ID = "jh0003"; + + public static String MODIFIER_ATT_UID = "jk9990"; + public static String MODIFIER_FIRST_NAME = "Roki"; + public static String MODIFIER_LAST_NAME = "Balaboa"; + +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java new file mode 100644 index 0000000000..699e23affd --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/serialize/TestResourceSerialization.java @@ -0,0 +1,222 @@ +/*- + * ============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.model.serialize; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.StringJoiner; +import java.util.stream.Collectors; + +import org.junit.Test; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.common.util.SerializationUtils; + +import fj.data.Either; + +public class TestResourceSerialization { + + // @Test + public void findAllClassesUsedByResource() { + + Set<Class> classesWithoutSerialzable = new HashSet<>(); + Set<String> classestoIgnore = new HashSet<>(); + classestoIgnore.add("java.util.List"); + classestoIgnore.add("java.util.Map"); + classestoIgnore.add("long"); + + Set<Class> allClasses = new HashSet<>(); + findAllClassesUsedByResource(Resource.class, allClasses); + ArrayList l; + for (Class clazz : allClasses) { + Class[] interfaces = clazz.getInterfaces(); + if (interfaces != null) { + String collect = Arrays.stream(interfaces).map(p -> p.getName()).collect(Collectors.joining("\n")); + + Class orElse = Arrays.stream(interfaces).filter(p -> p.getName().equals("java.io.Serializable")) + .findAny().orElse(null); + if (orElse == null) { + classesWithoutSerialzable.add(clazz); + } + + } + } + + List<Class> collect = classesWithoutSerialzable.stream() + .filter(p -> false == classestoIgnore.contains(p.getName())).collect(Collectors.toList()); + + if (collect != null) { + System.out.println(collect.stream().map(p -> p.getName()).collect(Collectors.joining("\n"))); + assertEquals("check all classes implements Serializable", 0, collect.size()); + } + + } + + public void findAllClassesUsedByResource(Class clazz, Set<Class> allClasses) { + + Class superclass = clazz.getSuperclass(); + findAllClassesOfClass(clazz, allClasses); + + if (superclass != null) { + findAllClassesOfClass(superclass, allClasses); + } + + } + + public void findAllClassesOfClass(Class clazz, Set<Class> allClasses) { + + Field[] fields = clazz.getDeclaredFields(); + if (fields != null) { + for (Field field : fields) { + String name = field.getName(); + Class type = field.getType(); + + if (type.toString().contains(".List")) { + ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); + Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0]; + // System.out.println(stringListClass); // class + // java.lang.String. + allClasses.add(stringListClass); + } + + if (type.toString().contains("java.util.Map")) { + ParameterizedType stringListType = (ParameterizedType) field.getGenericType(); + + Type[] actualTypeArguments = stringListType.getActualTypeArguments(); + if (actualTypeArguments != null) { + for (Type actualType : actualTypeArguments) { + + String typeName = actualType.getTypeName(); + // System.out.println("field " + name + "," + + // typeName); + + if (typeName.startsWith("java.util.List<")) { + String internalClass = typeName.replace("java.util.List<", "").replace(">", ""); + // create class from string + Class myClass; + try { + myClass = Class.forName(internalClass); + allClasses.add(myClass); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + assertTrue("Failed to convert " + internalClass + " to class", false); + } + + } else { + try { + Class myClass = Class.forName(typeName); + allClasses.add(myClass); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + assertTrue("Failed to convert " + typeName + " to class", false); + } + + } + } + } + + } + + // System.out.println(type); + allClasses.add(type); + } + } + + } + + private void addInternalTypeOfList(Class clazz) { + + // clazz. + // ParameterizedType stringListType = (ParameterizedType) + // field.getGenericType(); + // Class<?> stringListClass = (Class<?>) + // stringListType.getActualTypeArguments()[0]; + // //System.out.println(stringListClass); // class java.lang.String. + // allClasses.add(stringListClass); + // + } + + private boolean isClassImplementedSerialize(Class clazz) { + + Type[] genericInterfaces = clazz.getGenericInterfaces(); + if (genericInterfaces != null) { + Type orElse = Arrays.stream(genericInterfaces).filter(p -> p.getTypeName().equals("java.io.Serializable")) + .findAny().orElse(null); + if (orElse != null) { + return true; + } + } + + return false; + } + + // @Test + public void testSimpleResourceSerialize() { + + Resource resource = new Resource(); + String name = "res1"; + Map<String, String> allVersions = new HashMap<String, String>(); + allVersions.put("keya", "valuea"); + + resource.setName(name); + // all versions + resource.setAllVersions(allVersions); + List<ComponentInstance> resourceInstances = new ArrayList<ComponentInstance>(); + // component instances + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setDescription("desc1"); + componentInstance.setComponentUid("comUid"); + resourceInstances.add(componentInstance); + + resource.setComponentInstances(resourceInstances); + + Either<byte[], Boolean> serialize = SerializationUtils.serialize(resource); + assertTrue("check object serialized", serialize.isLeft()); + byte[] value = serialize.left().value(); + + Either<Object, Boolean> deserialize = SerializationUtils.deserialize(value); + assertTrue("check object deserialized", deserialize.isLeft()); + Object obj = deserialize.left().value(); + Resource desResource = (Resource) obj; + assertEquals("check name", name, desResource.getName()); + verifyAllVersions(desResource); + + } + + private void verifyAllVersions(Resource desResource) { + assertNotNull("check all versions", desResource.getAllVersions()); + assertEquals("check all version size", 1, desResource.getAllVersions().size()); + assertEquals("check all version key", "keya", desResource.getAllVersions().keySet().iterator().next()); + assertEquals("check all version value", "valuea", desResource.getAllVersions().values().iterator().next()); + } +} diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java new file mode 100644 index 0000000000..2dfe9a8de7 --- /dev/null +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/IntegerValidatorTest.java @@ -0,0 +1,75 @@ +/*- + * ============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.model.tosca.validators; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertNotNull; +import javax.validation.constraints.AssertTrue; + +import org.junit.Test; +import org.openecomp.sdc.be.model.tosca.validators.IntegerValidator; + +public class IntegerValidatorTest { + private static IntegerValidator validator = IntegerValidator.getInstance(); + + @Test + public void testIntegerValidatorDecimal() { + assertTrue(validator.isValid(null, null)); + assertTrue(validator.isValid("", null)); + assertTrue(validator.isValid("0", null)); + assertTrue(validator.isValid("+0", null)); + assertTrue(validator.isValid("-0", null)); + assertTrue(validator.isValid("+65465", null)); + assertTrue(validator.isValid("-65465", null)); + assertTrue(validator.isValid("2147483647", null)); + assertFalse(validator.isValid("2147483648", null)); + assertTrue(validator.isValid("-2147483648", null)); + assertFalse(validator.isValid("-2147483649", null)); + } + + @Test + public void testIntegerValidatorHexa() { + assertTrue(validator.isValid("-0xadc", null)); + assertTrue(validator.isValid("+0xadf", null)); + assertTrue(validator.isValid("0x7FFFFFFF", null)); + assertFalse(validator.isValid("0x80000000", null)); + assertTrue(validator.isValid("-0x80000000", null)); + assertFalse(validator.isValid("-0x80000001", null)); + } + + public void testIntegerValidatorOctal() { + assertTrue(validator.isValid("0o545435", null)); + assertTrue(validator.isValid("-0o545435", null)); + assertTrue(validator.isValid("0o17777777777", null)); + assertFalse(validator.isValid("0o20000000000", null)); + assertTrue(validator.isValid("-0o20000000000", null)); + assertFalse(validator.isValid("-0o20000000001", null)); + } + + @Test + public void testIntegerValidatorIncorrect() { + assertFalse(validator.isValid("-2.147483649", null)); + assertFalse(validator.isValid("dsfasf342342", null)); + } +} |