resource-registry/src/test/java/org/gcube/informationsystem/resourceregistry/instances/ERManagementTest.java

862 lines
35 KiB
Java

/**
*
*/
package org.gcube.informationsystem.resourceregistry.instances;
import java.net.URI;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.informationsystem.base.reference.IdentifiableElement;
import org.gcube.informationsystem.model.impl.properties.EncryptedImpl;
import org.gcube.informationsystem.model.impl.properties.PropagationConstraintImpl;
import org.gcube.informationsystem.model.impl.relations.ConsistsOfImpl;
import org.gcube.informationsystem.model.reference.ERElement;
import org.gcube.informationsystem.model.reference.ModelElement;
import org.gcube.informationsystem.model.reference.entities.Facet;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.model.reference.properties.Encrypted;
import org.gcube.informationsystem.model.reference.properties.Metadata;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.AddConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.DeleteConstraint;
import org.gcube.informationsystem.model.reference.properties.PropagationConstraint.RemoveConstraint;
import org.gcube.informationsystem.model.reference.relations.ConsistsOf;
import org.gcube.informationsystem.model.reference.relations.IsRelatedTo;
import org.gcube.informationsystem.resourceregistry.ContextTest;
import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagement;
import org.gcube.informationsystem.resourceregistry.instances.base.ElementManagementUtility;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.FacetManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.entities.ResourceManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.ConsistsOfManagement;
import org.gcube.informationsystem.resourceregistry.instances.model.relations.IsRelatedToManagement;
import org.gcube.informationsystem.resourceregistry.requests.RequestUtility;
import org.gcube.informationsystem.resourceregistry.requests.ServerRequestInfo;
import org.gcube.informationsystem.resourceregistry.utils.MetadataUtility;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.utils.TypeUtility;
import org.gcube.resourcemanagement.model.impl.entities.facets.AccessPointFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.CPUFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.EventFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.IdentifierFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.LicenseFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.MemoryFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.NetworkingFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.SoftwareFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.facets.StateFacetImpl;
import org.gcube.resourcemanagement.model.impl.entities.resources.ConfigurationImpl;
import org.gcube.resourcemanagement.model.impl.entities.resources.EServiceImpl;
import org.gcube.resourcemanagement.model.impl.entities.resources.HostingNodeImpl;
import org.gcube.resourcemanagement.model.impl.properties.ValueSchemaImpl;
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasPersistentMemoryImpl;
import org.gcube.resourcemanagement.model.impl.relations.consistsof.HasVolatileMemoryImpl;
import org.gcube.resourcemanagement.model.impl.relations.consistsof.IsIdentifiedByImpl;
import org.gcube.resourcemanagement.model.impl.relations.isrelatedto.ActivatesImpl;
import org.gcube.resourcemanagement.model.reference.entities.facets.AccessPointFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.CPUFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.EventFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.IdentifierFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.IdentifierFacet.IdentificationType;
import org.gcube.resourcemanagement.model.reference.entities.facets.LicenseFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.MemoryFacet.MemoryUnit;
import org.gcube.resourcemanagement.model.reference.entities.facets.NetworkingFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.SoftwareFacet;
import org.gcube.resourcemanagement.model.reference.entities.facets.StateFacet;
import org.gcube.resourcemanagement.model.reference.entities.resources.Configuration;
import org.gcube.resourcemanagement.model.reference.entities.resources.EService;
import org.gcube.resourcemanagement.model.reference.entities.resources.HostingNode;
import org.gcube.resourcemanagement.model.reference.properties.ValueSchema;
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasPersistentMemory;
import org.gcube.resourcemanagement.model.reference.relations.consistsof.HasVolatileMemory;
import org.gcube.resourcemanagement.model.reference.relations.consistsof.IsIdentifiedBy;
import org.gcube.resourcemanagement.model.reference.relations.isrelatedto.Activates;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ERManagementTest extends ContextTest {
private static Logger logger = LoggerFactory.getLogger(ERManagementTest.class);
public static final String GROUP = "InformationSystem";
public static final String NAME = "resource-registry";
public static final String VERSION = "1.0.0";
public static final String NEW_VERSION = "2.0.0";
// @Before
// @After
// public void cleanInstances() throws Exception {
// // Clean the environment first to avoid error if a previous tests fails without cleaning the env
// ResourceManagement rm = (ResourceManagement) ElementManagementUtility.getERManagement(Resource.NAME);
// String all = rm.all(true);
// List<Resource> allResources = ElementMapper.unmarshalList(Resource.class, all);
// for(Resource r : allResources) {
// try {
// ERManagementTest.deleteResource(r);
// }catch (ResourceNotFoundException e) {
// // A resource could be already deleted deleting another resource giving the propagation constraint
// }catch (ODatabaseException e) {
// // could occur
// }
// }
// }
@Before
public void before() throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
requestInfo.setLimit(1000);
requestInfo.setOffset(0);
}
public static SoftwareFacet getSoftwareFacet() {
SoftwareFacet softwareFacet = new SoftwareFacetImpl();
softwareFacet.setGroup(GROUP);
softwareFacet.setName(NAME);
softwareFacet.setVersion(VERSION);
return softwareFacet;
}
public static void checkSoftwareFacetAssertion(SoftwareFacet softwareFacet, SoftwareFacet gotSoftwareFacet) {
Assert.assertTrue(gotSoftwareFacet.getGroup().compareTo(softwareFacet.getGroup()) == 0);
Assert.assertTrue(gotSoftwareFacet.getName().compareTo(softwareFacet.getName()) == 0);
Assert.assertTrue(gotSoftwareFacet.getVersion().compareTo(softwareFacet.getVersion()) == 0);
}
public static Configuration instantiateValidConfiguration() throws Exception {
Configuration configuration = new ConfigurationImpl();
IdentifierFacet identifierFacet = new IdentifierFacetImpl();
identifierFacet.setIdentificationType(IdentificationType.STRING);
identifierFacet.setValue("MyID");
identifierFacet.setPersistent(false);
IsIdentifiedBy<Configuration, IdentifierFacet> isIdentifiedBy = new IsIdentifiedByImpl<Configuration, IdentifierFacet>(
configuration, identifierFacet);
configuration.addFacet(isIdentifiedBy);
return configuration;
}
public static EService instantiateValidEService() throws Exception {
EService eService = new EServiceImpl();
SoftwareFacet softwareFacet = getSoftwareFacet();
IsIdentifiedBy<Resource, Facet> isIdentifiedBy = new IsIdentifiedByImpl<Resource, Facet>(eService,
softwareFacet, null);
eService.addFacet(isIdentifiedBy);
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEndpoint(new URI("https://localhost"));
accessPointFacet.setEntryName("port1");
eService.addFacet(accessPointFacet);
EventFacet eventFacet = new EventFacetImpl();
eventFacet.setDate(Calendar.getInstance().getTime());
eventFacet.setEvent("Created");
eService.addFacet(eventFacet);
StateFacet stateFacet = new StateFacetImpl();
stateFacet.setValue("ready");
eService.addFacet(stateFacet);
LicenseFacet licenseFacet = new LicenseFacetImpl();
licenseFacet.setName("EUPL");
licenseFacet.setTextURL(new URL(
"https://joinup.ec.europa.eu/community/etestAddToContextFromDifferentSourceContextupl/og_page/european-union-public-licence-eupl-v11"));
eService.addFacet(licenseFacet);
return eService;
}
public static HostingNode instantiateValidHostingNode() throws Exception {
HostingNode hostingNode = new HostingNodeImpl();
NetworkingFacet networkingFacet = new NetworkingFacetImpl();
networkingFacet.setIPAddress("146.48.87.183");
networkingFacet.setHostName("pc-frosini.isti.cnr.it");
networkingFacet.setDomainName("isti.cnr.it");
networkingFacet.setMask("255.255.248.0");
networkingFacet.setBroadcastAddress("146.48.87.255");
IsIdentifiedBy<HostingNode, NetworkingFacet> isIdentifiedBy = new IsIdentifiedByImpl<HostingNode, NetworkingFacet>(
hostingNode, networkingFacet);
hostingNode.addFacet(isIdentifiedBy);
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
hostingNode.addFacet(cpuFacet);
MemoryFacet persistentMemoryFacet = new MemoryFacetImpl();
persistentMemoryFacet.setSize(1024);
persistentMemoryFacet.setUnit(MemoryUnit.GB);
persistentMemoryFacet.setUsed(512);
HasPersistentMemory<HostingNode, MemoryFacet> hasPersistentMemory = new HasPersistentMemoryImpl<HostingNode, MemoryFacet>(
hostingNode, persistentMemoryFacet);
hostingNode.addFacet(hasPersistentMemory);
MemoryFacet volatileMemoryFacet = new MemoryFacetImpl();
volatileMemoryFacet.setSize(8);
volatileMemoryFacet.setUnit(MemoryUnit.GB);
volatileMemoryFacet.setUsed(4);
HasVolatileMemory<HostingNode, MemoryFacet> hasVolatileMemory = new HasVolatileMemoryImpl<HostingNode, MemoryFacet>(
hostingNode, volatileMemoryFacet);
hostingNode.addFacet(hasVolatileMemory);
StateFacet hnStateFacet = new StateFacetImpl();
hnStateFacet.setValue("certified");
hostingNode.addFacet(hnStateFacet);
EventFacet hnEventFacet = new EventFacetImpl();
hnEventFacet.setDate(Calendar.getInstance().getTime());
hnEventFacet.setEvent("Created");
hostingNode.addFacet(hnEventFacet);
return hostingNode;
}
public static void checkUUIDAndMetadata(IdentifiableElement identifiableElement,
IdentifiableElement createdIdentifiableElement) {
UUID createdUUID = createdIdentifiableElement.getID();
Assert.assertTrue(createdUUID != null);
if (identifiableElement.getID() != null) {
Assert.assertTrue(createdUUID.compareTo(identifiableElement.getID()) == 0);
}
Metadata createdMetadata = createdIdentifiableElement.getMetadata();
Assert.assertTrue(createdMetadata != null);
String createdBy = createdMetadata.getCreatedBy();
Assert.assertTrue(createdBy != null);
String lastUpdateBy = createdMetadata.getLastUpdateBy();
Assert.assertTrue(lastUpdateBy != null);
Date creationTime = createdMetadata.getCreationTime();
Assert.assertTrue(creationTime != null);
Date lastUpdateTime = createdMetadata.getLastUpdateTime();
Assert.assertTrue(lastUpdateTime != null);
Assert.assertTrue(lastUpdateTime.equals(creationTime) || lastUpdateTime.equals(lastUpdateTime));
Metadata metadata = identifiableElement.getMetadata();
if (metadata != null) {
if (metadata.getCreatedBy() != null) {
Assert.assertTrue(createdBy.compareTo(metadata.getCreatedBy()) == 0);
} else {
Assert.assertTrue(createdBy.compareTo(MetadataUtility.getUser()) == 0);
}
if (metadata.getLastUpdateBy() != null) {
Assert.assertTrue(lastUpdateBy.compareTo(metadata.getLastUpdateBy()) == 0);
} else {
Assert.assertTrue(lastUpdateBy.compareTo(MetadataUtility.getUser()) == 0);
}
if (metadata.getLastUpdateTime() != null) {
Assert.assertTrue(lastUpdateTime.after(metadata.getLastUpdateTime())
|| lastUpdateTime.compareTo(metadata.getLastUpdateTime()) == 0);
}
}
}
public static void checkPropagationConstraint(PropagationConstraint propagationConstraint,
PropagationConstraint gotPropagationConstraint) {
Assert.assertTrue(propagationConstraint.getAddConstraint() == gotPropagationConstraint.getAddConstraint());
Assert.assertTrue(
propagationConstraint.getRemoveConstraint() == gotPropagationConstraint.getRemoveConstraint());
}
public static void checkConsistOf(ConsistsOf<? extends Resource, ? extends Facet> consistsOf,
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf) {
checkUUIDAndMetadata(consistsOf, gotConsistsOf);
if (consistsOf.getPropagationConstraint() == null) {
PropagationConstraint propagationConstraint = gotConsistsOf.getPropagationConstraint();
Assert.assertTrue(propagationConstraint.getAddConstraint() == AddConstraint.propagate);
Assert.assertTrue(propagationConstraint.getRemoveConstraint() == RemoveConstraint.cascade);
checkPropagationConstraint(propagationConstraint, gotConsistsOf.getPropagationConstraint());
} else {
checkPropagationConstraint(consistsOf.getPropagationConstraint(), gotConsistsOf.getPropagationConstraint());
}
Map<String, Object> additionalProperties = new HashMap<>(consistsOf.getAdditionalProperties());
additionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Map<String, Object> gotAdditionalProperties = new HashMap<>(gotConsistsOf.getAdditionalProperties());
gotAdditionalProperties.remove(ModelElement.SUPERTYPES_PROPERTY);
Assert.assertTrue(additionalProperties.size() == gotAdditionalProperties.size());
for (String key : additionalProperties.keySet()) {
Assert.assertTrue(gotAdditionalProperties.containsKey(key));
Object additionalProperty = additionalProperties.get(key);
Object gotAdditionalProperty = gotAdditionalProperties.get(key);
Assert.assertTrue(additionalProperty.getClass() == gotAdditionalProperty.getClass());
Assert.assertTrue(additionalProperty.equals(gotAdditionalProperty));
}
}
public static void checkFacet(Facet facet, Facet gotFacet) throws Exception {
checkUUIDAndMetadata(facet, gotFacet);
Class<? extends Facet> clz = facet.getClass();
Class<? extends Facet> gotClz = gotFacet.getClass();
Assert.assertTrue(clz == gotClz);
if (clz == SoftwareFacet.class) {
checkSoftwareFacetAssertion((SoftwareFacet) facet, (SoftwareFacet) gotFacet);
}
}
protected static <R extends Resource> void checkResource(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> consistsOf : resourceConsistsOf) {
@SuppressWarnings("unchecked")
ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf = (ConsistsOf<? extends Resource, ? extends Facet>) gotResource
.getConsistsOf(consistsOf.getClass(), consistsOf.getTarget().getClass()).get(0);
checkConsistOf(consistsOf, gotConsistsOf);
Facet facet = consistsOf.getTarget();
Facet gotFacet = gotConsistsOf.getTarget();
checkFacet(facet, gotFacet);
}
}
protected static <R extends Resource> void checkResourceRootMetaOnly(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
checkUUIDAndMetadata(resource, gotResource);
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
protected static <R extends Resource> void checkResourceNoMeta(R resource, R gotResource) throws Exception {
Assert.assertTrue(resource.getClass() == gotResource.getClass());
Assert.assertNull(gotResource.getMetadata());
List<ConsistsOf<? extends Resource, ? extends Facet>> resourceConsistsOf = resource.getConsistsOf();
List<ConsistsOf<? extends Resource, ? extends Facet>> gotResourceConsistsOf = gotResource.getConsistsOf();
Assert.assertTrue(resourceConsistsOf.size() == gotResourceConsistsOf.size());
for (ConsistsOf<? extends Resource, ? extends Facet> gotConsistsOf : gotResourceConsistsOf) {
Assert.assertNull(gotConsistsOf.getMetadata());
Assert.assertNull(gotConsistsOf.getTarget().getMetadata());
}
}
public <R extends Resource> ResourceManagement getResourceManagement(R r) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(r.getTypeName());
resourceManagement.setJson(ElementMapper.marshal(r));
if (r.getID() != null) {
resourceManagement.setUUID(r.getID());
}
return resourceManagement;
}
public <R extends Resource> IsRelatedToManagement getIsRelatedToManagement(
IsRelatedTo<? extends Resource, ? extends Resource> isRelatedTo) throws Exception {
IsRelatedToManagement isRelatedToManagement = new IsRelatedToManagement();
isRelatedToManagement.setElementType(isRelatedTo.getTypeName());
isRelatedToManagement.setJson(ElementMapper.marshal(isRelatedTo));
if (isRelatedTo.getID() != null) {
isRelatedToManagement.setUUID(isRelatedTo.getID());
}
return isRelatedToManagement;
}
public <R extends Resource> R createResource(R r) throws Exception {
ResourceManagement resourceManagement = getResourceManagement(r);
String json = resourceManagement.create();
logger.debug("Created resource {}", json);
@SuppressWarnings("unchecked")
R createdR = (R) ElementMapper.unmarshal(r.getClass(), json);
logger.debug("Unmarshalled created resource {}", ElementMapper.marshal(createdR));
checkResource(r, createdR);
return createdR;
}
public EService createEService() throws Exception {
EService eService = ERManagementTest.instantiateValidEService();
return createResource(eService);
}
public HostingNode createHostingNode() throws Exception {
return createHostingNode(null);
}
public HostingNode createHostingNode(EService eService) throws Exception {
return createHostingNode(eService, RemoveConstraint.cascade, DeleteConstraint.cascade);
}
public HostingNode createHostingNode(EService eService, RemoveConstraint removeConstraint,
DeleteConstraint deleteConstraint) throws Exception {
HostingNode hostingNode = ERManagementTest.instantiateValidHostingNode();
if (eService != null) {
PropagationConstraint propagationConstraint = new PropagationConstraintImpl();
propagationConstraint.setRemoveConstraint(removeConstraint);
propagationConstraint.setDeleteConstraint(deleteConstraint);
Activates<HostingNode, EService> activates = new ActivatesImpl<HostingNode, EService>(hostingNode, eService,
propagationConstraint);
hostingNode.attachResource(activates);
}
return createResource(hostingNode);
}
public Configuration createConfiguration() throws Exception {
Configuration configuration = ERManagementTest.instantiateValidConfiguration();
return createResource(configuration);
}
public Map<String, Resource> createHostingNodeAndEService() throws Exception {
Map<String, Resource> map = new HashMap<>();
EService eService = createEService();
map.put(EService.NAME, eService);
HostingNode hostingNode = createHostingNode(eService);
map.put(HostingNode.NAME, hostingNode);
return map;
}
public <R extends Resource> void deleteResource(R r) throws Exception {
if (r != null) {
ResourceManagement resourceManagement = getResourceManagement(r);
resourceManagement.delete();
}
}
@Test
public void testCreateEService() throws Exception {
EService eService = null;
try {
eService = createEService();
} finally {
deleteResource(eService);
}
}
@Test
public void testCreateAndReadEService() throws Exception {
EService eService = null;
try {
eService = createEService();
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(true);
EService readEService = (EService) readResource(eService.getID());
checkResource(eService, readEService);
requestInfo.setIncludeMeta(true);
requestInfo.setAllMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceRootMetaOnly(eService, readEService);
requestInfo.setIncludeMeta(false);
readEService = (EService) readResource(eService.getID());
checkResourceNoMeta(eService, readEService);
} finally {
deleteResource(eService);
}
}
protected Resource readResource(UUID uuid) throws Exception {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setUUID(uuid);
String json = resourceManagement.read().toString();
logger.debug(json);
return ElementMapper.unmarshal(Resource.class, json);
}
/*
* @Test public void testReadResource() throws Exception {
* readResource(UUID.fromString("26da57ee-33bd-4c4b-8aef-9206b61c329e")); }
*/
/*
* @Test public void testDeleteResource() throws Exception { ResourceManagement
* resourceManagement = new ResourceManagement();
* resourceManagement.setUUID(UUID.fromString(
* "64635295-7ced-4931-a55f-40fc8199b280")); boolean deleted =
* resourceManagement.delete(); Assert.assertTrue(deleted); }
*/
@Test
public void testCreateHostingNode() throws Exception {
HostingNode hostingNode = null;
try {
hostingNode = createHostingNode();
} finally {
deleteResource(hostingNode);
}
}
@Test
public void testCreateHostingNodeAndEService() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
deleteResource(map.get(HostingNode.NAME));
}
@Test
public void testCreateReadUpdateDeleteFacet() throws Exception {
EService eService = createEService();
try {
CPUFacet cpuFacet = new CPUFacetImpl();
cpuFacet.setClockSpeed("1 GHz");
cpuFacet.setModel("Opteron");
cpuFacet.setVendor("AMD");
ConsistsOf<EService, CPUFacet> consistsOf = new ConsistsOfImpl<EService, CPUFacet>(eService, cpuFacet);
ConsistsOfManagement consistsOfManagement = new ConsistsOfManagement();
consistsOfManagement.setElementType(consistsOf.getTypeName());
consistsOfManagement.setJson(ElementMapper.marshal(consistsOf));
String createdConsistsOfString = consistsOfManagement.create();
@SuppressWarnings("unchecked")
ConsistsOf<EService, CPUFacet> createdConsistsOf = ElementMapper.unmarshal(ConsistsOf.class,
createdConsistsOfString);
CPUFacet createdCpuFacet = createdConsistsOf.getTarget();
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(createdCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(cpuFacet.getModel().compareTo(createdCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(createdCpuFacet.getVendor()) == 0);
UUID uuid = createdCpuFacet.getID();
FacetManagement facetManagement = new FacetManagement();
facetManagement.setElementType(createdCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
String readJson = facetManagement.read().toString();
CPUFacet readCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readJson);
logger.debug("Read:\nRaw Json : {}\nUnmarshalled : {}", readJson, readCpuFacet);
Assert.assertTrue(cpuFacet.getClockSpeed().compareTo(readCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(cpuFacet.getModel().compareTo(readCpuFacet.getModel()) == 0);
Assert.assertTrue(cpuFacet.getVendor().compareTo(readCpuFacet.getVendor()) == 0);
Assert.assertTrue(uuid.compareTo(readCpuFacet.getID()) == 0);
String newVendor = "Intel";
String newClockSpeed = "2 GHz";
readCpuFacet.setVendor(newVendor);
readCpuFacet.setClockSpeed(newClockSpeed);
String additionPropertyKey = "My";
String additionPropertyValue = "Test";
readCpuFacet.setAdditionalProperty(additionPropertyKey, additionPropertyValue);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.setJson(ElementMapper.marshal(readCpuFacet));
String updatedJson = facetManagement.update();
CPUFacet updatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, updatedJson);
logger.debug("Updated:\nRaw Json : {}\nUnmarshalled : {}", updatedJson, updatedCpuFacet);
Assert.assertTrue(updatedCpuFacet.getClockSpeed().compareTo(newClockSpeed) == 0);
Assert.assertTrue(readCpuFacet.getModel().compareTo(updatedCpuFacet.getModel()) == 0);
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(newVendor) == 0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
String user = ContextTest.getUser();
Assert.assertTrue(updatedCpuFacet.getMetadata().getLastUpdateBy().compareTo(user) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(updatedCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
String readUpdatedJson = facetManagement.read().toString();
CPUFacet readUpdatedCpuFacet = ElementMapper.unmarshal(CPUFacet.class, readUpdatedJson);
logger.debug("Read Updated:\nRaw Json : {}\nUnmarshalled : {}", readUpdatedJson, readUpdatedCpuFacet);
Assert.assertTrue(updatedCpuFacet.getClockSpeed().compareTo(readUpdatedCpuFacet.getClockSpeed()) == 0);
Assert.assertTrue(updatedCpuFacet.getModel().compareTo(readUpdatedCpuFacet.getModel()) == 0);
Assert.assertTrue(updatedCpuFacet.getVendor().compareTo(readUpdatedCpuFacet.getVendor()) == 0);
Assert.assertTrue(((String) updatedCpuFacet.getAdditionalProperty(additionPropertyKey))
.compareTo((String) readUpdatedCpuFacet.getAdditionalProperty(additionPropertyKey)) == 0);
Assert.assertTrue(uuid.compareTo(updatedCpuFacet.getID()) == 0);
facetManagement = new FacetManagement();
facetManagement.setElementType(readCpuFacet.getTypeName());
facetManagement.setUUID(uuid);
facetManagement.delete();
} finally {
deleteResource(eService);
}
}
@Test
public void testCreatePropertyTypeNotInSchema() throws Exception {
/*
* A facet cannot be created per se. Going to create a Configuration which does
* not impose any particular constraint except the IdentifierFact
*/
Configuration configuration = instantiateValidConfiguration();
AccessPointFacet accessPointFacet = new AccessPointFacetImpl();
accessPointFacet.setEndpoint(new URI("https://localhost"));
accessPointFacet.setEntryName("port1");
ValueSchema authorization = new ValueSchemaImpl();
authorization.setValue("pwd");
URI uri = new URI("https://www.gcube-system.org");
authorization.setSchema(uri);
accessPointFacet.setAuthorization(authorization);
String additionalPropertyKey = "Test";
String additionlaPropertyValue = "MyTest";
accessPointFacet.setAdditionalProperty(additionalPropertyKey, additionlaPropertyValue);
Encrypted encrypted = new EncryptedImpl();
String plainValue = "Encrypted";
String encryptedValue = StringEncrypter.getEncrypter().encrypt(plainValue);
encrypted.setValue(encryptedValue);
String encryptedKey = "Enc";
accessPointFacet.setAdditionalProperty(encryptedKey, encrypted);
configuration.addFacet(accessPointFacet);
String marshalled = ElementMapper.marshal(configuration);
logger.debug(marshalled);
Configuration createdConfiguration = createResource(configuration);
AccessPointFacet apf = configuration.getFacets(AccessPointFacet.class).get(0);
Assert.assertTrue(apf.getAuthorization() instanceof ValueSchema);
Assert.assertTrue(apf.getAdditionalProperty(encryptedKey) instanceof Encrypted);
Encrypted enc = (Encrypted) apf.getAdditionalProperty(encryptedKey);
String encValue = enc.getValue();
Assert.assertTrue(encValue.compareTo(encryptedValue) == 0);
String decryptedValue = StringEncrypter.getEncrypter().decrypt(encValue);
Assert.assertTrue(decryptedValue.compareTo(plainValue) == 0);
Assert.assertTrue(
((String) apf.getAdditionalProperty(additionalPropertyKey)).compareTo(additionlaPropertyValue) == 0);
deleteResource(createdConfiguration);
}
@Test
public void testUpdateFacetValue() throws Exception {
EService eService = null;
try {
eService = createEService();
final String newVersion = "1.2.0";
eService.getFacets(SoftwareFacet.class).get(0).setVersion(newVersion);
ResourceManagement resourceManagement = getResourceManagement(eService);
String json = resourceManagement.update();
EService updatedEService = ElementMapper.unmarshal(EService.class, json);
checkResource(eService, updatedEService);
SoftwareFacet softwareFacet = updatedEService.getFacets(SoftwareFacet.class).get(0);
Assert.assertTrue(softwareFacet.getVersion().compareTo(newVersion) == 0);
} catch (Throwable e) {
throw e;
} finally {
deleteResource(eService);
}
}
// public static final String TEST_RESOURCE = "test-resource.json";
//
// // @Test
// public void testUpdateResourceFromFile()
// throws JsonParseException, JsonMappingException, IOException, ResourceRegistryException {
// File file = new File("src/test/resources/" + TEST_RESOURCE);
//
// logger.debug("{}", file.getAbsolutePath());
//
// FileInputStream fileInputStream = new FileInputStream(file);
// EService eService = ElementMapper.unmarshal(EService.class, fileInputStream);
//
// ResourceManagement resourceManagement = new ResourceManagement();
// resourceManagement.setUUID(eService.getUUID());
// resourceManagement.setJson(ElementMapper.marshal(eService));
//
// resourceManagement.update();
//
// }
@Test
public void getAllHostingNode() throws ResourceRegistryException {
ResourceManagement resourceManagement = new ResourceManagement();
resourceManagement.setElementType(HostingNode.NAME);
String ret = resourceManagement.all(true);
logger.debug("{}", ret);
}
protected List<ERElement> getPaginatedInstances(Class<? extends ERElement> clz, int offset, int limit) throws Exception {
ServerRequestInfo requestInfo = RequestUtility.getRequestInfo().get();
requestInfo.setOffset(offset);
requestInfo.setLimit(limit);
ElementManagement<?,?> erManagement = ElementManagementUtility.getERManagement(TypeUtility.getTypeName(clz));
String ret = erManagement.all(true);
List<ERElement> list = ElementMapper.unmarshalList(ERElement.class, ret);
return list;
}
@Test
public void testLimitOffset() throws Exception {
Map<String, Resource> map = createHostingNodeAndEService();
logger.debug("---------------------------------------------------------------------");
try {
for(int i=1; i<6; i++) {
testLimitOffset(Resource.class, i);
testLimitOffset(Facet.class, i);
testLimitOffset(IsRelatedTo.class, i);
testLimitOffset(ConsistsOf.class, i);
}
logger.debug("---------------------------------------------------------------------\n\n\n");
} finally {
deleteResource(map.get(HostingNode.NAME));
}
}
public void testLimitOffset(Class<? extends ERElement> clz, int limit) throws Exception {
if(limit <1) {
throw new Exception("This test has been designed for limit>0 to test pagination");
}
String typeName = TypeUtility.getTypeName(clz);
logger.debug("Going to test pagination of {} using limit {}", typeName, limit);
int offset = limit * 0;
List<ERElement> list = getPaginatedInstances(clz, offset, limit);
if (list.size() == 0) {
logger.debug("Found 0 instances");
logger.debug("Successfully tested pagination of {} using limit {}\n\n", typeName, limit);
return;
}
Assert.assertTrue(list.size() <= limit);
Set<UUID> uuids = new HashSet<>();
for (ERElement erElement : list) {
UUID uuid = erElement.getID();
uuids.add(uuid);
logger.debug("[offset={},limit={}] Found {} with UUID {}", offset, limit, erElement.getTypeName(), uuid);
}
if (list.size() < limit) {
logger.debug("Successfully tested pagination of {} using limit {}\n\n", typeName, limit);
return;
}
offset = limit * 1;
list = getPaginatedInstances(clz, offset, limit);
if (list.size() > 0) {
Assert.assertTrue(list.size() <= limit);
for (ERElement erElement : list) {
UUID uuid = erElement.getID();
Assert.assertFalse(uuids.contains(uuid));
uuids.add(uuid);
logger.debug("[offset={},limit={}] Found {} with UUID {}", offset, limit, erElement.getTypeName(), uuid);
}
if (list.size() < limit) {
logger.debug("Successfully tested pagination of {} using limit {}\n\n", typeName, limit);
return;
}
offset = 0;
int doubleLimit = limit * 2;
list = getPaginatedInstances(clz, offset, doubleLimit);
Assert.assertTrue(list.size() <= doubleLimit);
for (ERElement erElement : list) {
UUID uuid = erElement.getID();
logger.debug("[offset={},limit={}] Found {} with UUID {}", offset, doubleLimit, erElement.getTypeName(), uuid);
Assert.assertTrue(uuids.contains(uuid));
}
}
logger.info("Going to check all {} instances", typeName);
List<ERElement> all = getPaginatedInstances(clz, 0, -1);
uuids = new HashSet<>();
int i = -1;
while(true) {
offset = ++i * limit;
list = getPaginatedInstances(clz, offset, limit);
for(ERElement erElement : list) {
UUID uuid = erElement.getID();
logger.info("[offset={},limit={}] Found {} with UUID {}", offset, limit, erElement.getTypeName(), uuid);
uuids.add(uuid);
}
if(list.size()<limit) {
break;
}
}
Assert.assertTrue(all.size()==uuids.size());
for(ERElement erElement : all) {
UUID uuid = erElement.getID();
Assert.assertTrue(uuids.contains(uuid));
logger.info("[UNLIMITED] Found {} with UUID {}", erElement.getTypeName(), uuid);
}
logger.debug("Successfully tested pagination of {} using limit {}\n\n", TypeUtility.getTypeName(clz), limit);
}
}