diff options
author | sblimkie <steven.blimkie@amdocs.com> | 2017-12-01 16:00:50 -0500 |
---|---|---|
committer | sblimkie <steven.blimkie@amdocs.com> | 2017-12-04 12:06:40 -0500 |
commit | bfb506c057c62cc6e76a3696608182c202e01698 (patch) | |
tree | d386a9700e5ff101523a0d3071b606fbe610fe3b | |
parent | f7b84df35a767b18b8c5f3485cff2ffd5faab0c8 (diff) |
Gizmo uses Champ the microservice
Gizmo modified to use the Champ ms REST API instead of the Champ library
Issue-ID: AAI-525
Change-Id: Ifc5d0302eebfe4eccbe805ecf6cfd059fb6e700b
Signed-off-by: sblimkie <steven.blimkie@amdocs.com>
-rw-r--r-- | janus-deps-pom.xml | 90 | ||||
-rw-r--r-- | pom.xml | 13 | ||||
-rw-r--r-- | src/main/bin/start.sh | 17 | ||||
-rw-r--r-- | src/main/docker/Dockerfile | 3 | ||||
-rw-r--r-- | src/main/java/org/onap/crud/dao/champ/ChampDao.java | 1022 | ||||
-rw-r--r-- | src/main/java/org/onap/crud/dao/champ/ChampEdgeSerializer.java (renamed from src/main/java/org/onap/crud/dao/champion/ChampionEdgeSerializer.java) | 5 | ||||
-rw-r--r-- | src/main/java/org/onap/crud/dao/champ/ChampVertexSerializer.java (renamed from src/main/java/org/onap/crud/dao/champion/ChampionVertexSerializer.java) | 4 | ||||
-rw-r--r-- | src/main/java/org/onap/crud/dao/champion/ChampionDao.java | 623 | ||||
-rw-r--r-- | src/main/java/org/onap/crud/service/CrudGraphDataService.java | 8 | ||||
-rw-r--r-- | src/main/java/org/onap/crud/util/CrudServiceConstants.java | 19 | ||||
-rw-r--r-- | src/test/java/org/onap/crud/dao/champ/ChampDaoTest.java | 624 | ||||
-rw-r--r-- | titan-deps-pom.xml | 89 |
12 files changed, 354 insertions, 2163 deletions
diff --git a/janus-deps-pom.xml b/janus-deps-pom.xml deleted file mode 100644 index 7a0cd77..0000000 --- a/janus-deps-pom.xml +++ /dev/null @@ -1,90 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>com.test</groupId> - <artifactId>myjanus</artifactId> - <version>0.0.1-SNAPSHOT</version> - <packaging>pom</packaging> - - <dependencies> - - <dependency> - <groupId>org.openecomp.aai</groupId> - <artifactId>champ-janus</artifactId> - <version>1.1.1-AMDOCS-SNAPSHOT</version> - </dependency> - <dependency> - <groupId>org.janusgraph</groupId> - <artifactId>janusgraph-cassandra</artifactId> - <version>0.1.1</version> - <optional>true</optional> - <exclusions> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - <exclusion> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> - </exclusion> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-core</artifactId> - </exclusion> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-groovy</artifactId> - </exclusion> - </exclusions> - </dependency> - <dependency> - <groupId>org.janusgraph</groupId> - <artifactId>janusgraph-hbase</artifactId> - <version>0.1.1</version> - <optional>true</optional> - <exclusions> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-groovy</artifactId> - </exclusion> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - <exclusion> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> - </exclusion> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-core</artifactId> - </exclusion> - </exclusions> - </dependency> - - </dependencies> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-dependency-plugin</artifactId> - <version>3.0.1</version> - <executions> - <execution> - <id>copy-dependencies</id> - <phase>package</phase> - <goals> - <goal>copy-dependencies</goal> - </goals> - <configuration> - <outputDirectory>${project.build.directory}/graph-deps/janus-deps</outputDirectory> - <overWriteReleases>false</overWriteReleases> - <overWriteSnapshots>false</overWriteSnapshots> - <overWriteIfNewer>true</overWriteIfNewer> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - -</project>
\ No newline at end of file @@ -122,19 +122,6 @@ <version>2.6.2</version> </dependency> - <!-- Champ graph database library. --> - <dependency> - <groupId>org.openecomp.aai</groupId> - <artifactId>champ</artifactId> - <version>1.1.0-SNAPSHOT</version> - <scope>compile</scope> - <exclusions> - <exclusion> - <groupId>org.apache.hbase</groupId> - <artifactId>hbase-client</artifactId> - </exclusion> - </exclusions> - </dependency> <dependency> <groupId>org.onap.aai</groupId> <artifactId>rest-client</artifactId> diff --git a/src/main/bin/start.sh b/src/main/bin/start.sh index aa1f6b3..843e4c5 100644 --- a/src/main/bin/start.sh +++ b/src/main/bin/start.sh @@ -40,23 +40,6 @@ CLASSPATH="$AJSC_HOME/lib/*" CLASSPATH="$CLASSPATH:$AJSC_HOME/extJars/" CLASSPATH="$CLASSPATH:$AJSC_HOME/etc/" -# Check to see if the provided implementation exists in the image and add it to the classpath -for file in $( find ${BASEDIR}graph-deps/* -maxdepth 0 -type d ); do - CURRIMPL=$(echo $file | cut -d"/" -f6) - if [ "x$GRAPHIMPL" = "x$CURRIMPL" ]; then - CLASSPATH_GRAPHIMPL=$file - echo "Setting up graph implementation of $GRAPHIMPL" - else - SUPPORTED_GRAPHIMPL="$SUPPORTED_GRAPHIMPL $CURRIMPL" - fi -done -if [ -n "$CLASSPATH_GRAPHIMPL" ]; then - cp $CLASSPATH_GRAPHIMPL/* $AJSC_HOME/extJars/ -else - echo "Configured graph implementation '$GRAPHIMPL' is not supported. Acceptable implementations are one of: $SUPPORTED_GRAPHIMPL" - exit 1 -fi - PROPS="-DAJSC_HOME=$AJSC_HOME" PROPS="$PROPS -DAJSC_CONF_HOME=$BASEDIR/bundleconfig/" PROPS="$PROPS -Dlogback.configurationFile=$BASEDIR/bundleconfig/etc/logback.xml" diff --git a/src/main/docker/Dockerfile b/src/main/docker/Dockerfile index c342772..e4459d1 100644 --- a/src/main/docker/Dockerfile +++ b/src/main/docker/Dockerfile @@ -2,7 +2,6 @@ FROM ubuntu:14.04 ARG MICRO_HOME=/opt/app/crud-api ARG BIN_HOME=$MICRO_HOME/bin -ARG GRAPHLIB_HOME=$MICRO_HOME/graph-deps RUN apt-get update @@ -17,8 +16,6 @@ RUN export JAVA_HOME # Build up the deployment folder structure RUN mkdir -p $MICRO_HOME ADD swm/package/nix/dist_files/appl/crud-api/* $MICRO_HOME/ -RUN mkdir -p $GRAPHLIB_HOME -ADD graph-deps $GRAPHLIB_HOME RUN mkdir -p $BIN_HOME COPY *.sh $BIN_HOME RUN chmod 755 $BIN_HOME/* diff --git a/src/main/java/org/onap/crud/dao/champ/ChampDao.java b/src/main/java/org/onap/crud/dao/champ/ChampDao.java index f217897..fa2bab5 100644 --- a/src/main/java/org/onap/crud/dao/champ/ChampDao.java +++ b/src/main/java/org/onap/crud/dao/champ/ChampDao.java @@ -23,861 +23,535 @@ */ package org.onap.crud.dao.champ; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.onap.aai.champcore.ChampGraph; -import org.onap.aai.champcore.ChampTransaction; -import org.onap.aai.champcore.exceptions.ChampMarshallingException; -import org.onap.aai.champcore.exceptions.ChampObjectNotExistsException; -import org.onap.aai.champcore.exceptions.ChampRelationshipNotExistsException; -import org.onap.aai.champcore.exceptions.ChampSchemaViolationException; -import org.onap.aai.champcore.exceptions.ChampTransactionException; -import org.onap.aai.champcore.exceptions.ChampUnmarshallingException; -import org.onap.aai.champcore.model.ChampObject; -import org.onap.aai.champcore.model.ChampRelationship; -import org.onap.aai.champcore.model.fluent.object.ObjectBuildOrPropertiesStep; +import net.dongliu.gson.GsonJava8TypeAdapterFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; + +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.message.BasicNameValuePair; +import org.eclipse.jetty.util.security.Password; +import org.onap.aai.logging.LoggingContext; import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.crud.dao.GraphDao; import org.onap.crud.entity.Edge; import org.onap.crud.entity.Vertex; import org.onap.crud.exception.CrudException; -import org.onap.crud.logging.CrudServiceMsgs; - -/** - * This is the integration layer between the CRUD API service and the low level - * Champ library for graph database interaction. - */ -public class ChampDao implements GraphDao { - - public static final String CONFIG_STORAGE_BACKEND = "storage.backend"; - public static final String CONFIG_STORAGE_BACKEND_DB = "storage.backend.db"; - public static final String STORAGE_HBASE_DB = "hbase"; - public static final String STORAGE_CASSANDRA_DB = "cassandra"; - public static final String CONFIG_STORAGE_HOSTNAMES = "storage.hostnames"; - public static final String CONFIG_STORAGE_PORT = "storage.port"; - public static final String CONFIG_HBASE_ZNODE_PARENT = "storage.hbase.ext.zookeeper.znode.parent"; - public static final String CONFIG_GRAPH_NAME = "graph.name"; - public static final String GRAPH_UNQ_INSTANCE_ID_SUFFIX = "graph.unique-instance-id-suffix"; +import org.onap.crud.util.CrudServiceConstants; +import org.openecomp.restclient.client.OperationResult; +import org.openecomp.restclient.client.RestClient; +import org.openecomp.restclient.enums.RestAuthenticationMode; +import org.slf4j.MDC; - public static final String CONFIG_EVENT_STREAM_PUBLISHER = "event.stream.publisher"; - public static final String CONFIG_EVENT_STREAM_NUM_PUBLISHERS = "event.stream.num-publishers"; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; - private static Map<String, ChampTransaction> transactions = new ConcurrentHashMap<String, ChampTransaction>(); - public static final String DEFAULT_GRAPH_NAME = "default_graph"; +public class ChampDao implements GraphDao { + private RestClient client; + private String baseObjectUrl; + private String baseRelationshipUrl; + private String baseTransactionUrl; + + private static final String HEADER_FROM_APP = "X-FromAppId"; + private static final String HEADER_TRANS_ID = "X-TransactionId"; + private static final String FROM_APP_NAME = "Gizmo"; + private static final String OBJECT_SUB_URL = "objects"; + private static final String RELATIONSHIP_SUB_URL = "relationships"; + private static final String TRANSACTION_SUB_URL = "transaction"; - private enum GraphType { - IN_MEMORY, TITAN, DSE - } + private Logger logger = LoggerFactory.getInstance().getLogger(ChampDao.class.getName()); - /** - * Instance of the API used for interacting with the Champ library. - */ - private ChampGraph champApi = null; + // We use a custom vertex serializer for champ because it expects "key" + // instead of "id" + private static final Gson champGson = new GsonBuilder() + .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory()) + .registerTypeAdapter(Vertex.class, new ChampVertexSerializer()) + .registerTypeAdapter(Edge.class, new ChampEdgeSerializer()).create(); - private Logger logger = LoggerFactory.getInstance().getLogger(ChampDao.class.getName()); + public ChampDao(String champUrl, String certPassword) { + try { + client = new RestClient().authenticationMode(RestAuthenticationMode.SSL_CERT).validateServerHostname(false) + .validateServerCertChain(false).clientCertFile(CrudServiceConstants.CRD_CHAMP_AUTH_FILE) + .clientCertPassword(Password.deobfuscate(certPassword)); - /** - * Creates a new instance of the ChampDao. - * - * @param champGraph - * - Concrete implementation of the graph dao layer - */ - public ChampDao(ChampGraph champGraph) { - this.champApi = champGraph; + baseObjectUrl = champUrl + OBJECT_SUB_URL; + baseRelationshipUrl = champUrl + RELATIONSHIP_SUB_URL; + baseTransactionUrl = champUrl + TRANSACTION_SUB_URL; + } catch (Exception e) { + System.out.println("Error setting up Champ configuration"); + e.printStackTrace(); + System.exit(1); + } } @Override public Vertex getVertex(String id) throws CrudException { + String url = baseObjectUrl + "/" + id; + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - try { - - if (logger.isDebugEnabled()) { - logger.debug("getVertex with id: " + id); - } - - long idAsLong = Long.parseLong(id); - - Optional<ChampObject> retrievedVertex = champApi.retrieveObject(idAsLong); - - String nodeType = org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(); - if (retrievedVertex.isPresent() && retrievedVertex.get().getProperties().get(nodeType) != null) { - return vertexFromChampObject(retrievedVertex.get(), - retrievedVertex.get().getProperties().get(nodeType).toString()); - } else { - - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - - } catch (ChampUnmarshallingException | ChampTransactionException e) { - - // Something went wrong - throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == 200) { + return Vertex.fromJson(getResult.getResult()); + } else { + // We didn't find a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("No vertex with id " + id + " found in graph", + javax.ws.rs.core.Response.Status.NOT_FOUND); } } @Override public Vertex getVertex(String id, String type) throws CrudException { + String url = baseObjectUrl + "/" + id; + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - try { - - if (logger.isDebugEnabled()) { - logger.debug("getVertex with id: " + id); - } - - long idAsLong = Long.parseLong(id); - - // Request the vertex from the graph db. - Optional<ChampObject> retrievedVertex = champApi.retrieveObject(idAsLong); - - // Did we find it? - if (retrievedVertex.isPresent() - && retrievedVertex.get().getProperties() - .get(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) != null - && retrievedVertex.get().getProperties() - .get(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString() - .equalsIgnoreCase(type)) { + if (getResult.getResultCode() == 200) { + Vertex vert = Vertex.fromJson(getResult.getResult()); - // Yup, convert it to a Vector object and return it. - return vertexFromChampObject(retrievedVertex.get(), type); - - } else { - - // We didn't find a vertex with the supplied id, so just throw an + if (!vert.getType().equalsIgnoreCase(type)) { + // We didn't find a vertex with the supplied type, so just throw an // exception. - throw new CrudException("No vertex with id " + id + " found in graph", + throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); } - - } catch (ChampUnmarshallingException | ChampTransactionException e) { - - // Something went wrong - throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + return vert; + } else { + // We didn't find a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("No vertex with id " + id + " found in graph", + javax.ws.rs.core.Response.Status.NOT_FOUND); } } @Override public List<Edge> getVertexEdges(String id) throws CrudException { + String url = baseObjectUrl + "/relationships/" + id; - if (logger.isDebugEnabled()) { - logger.debug("get Edges incident to vertex with id: " + id + " from graph"); - } - - try { - long idAsLong = Long.parseLong(id); // GDF - what to do about id??? - - // Request the vertex from the graph db. - Optional<ChampObject> retrievedVertex = champApi.retrieveObject(idAsLong); - - // Did we find it? - if (retrievedVertex.isPresent()) { - - // Query the Champ library for the edges which are incident to the - // specified - // vertex. - Stream<ChampRelationship> relationships = champApi.retrieveRelationships(retrievedVertex.get()); - - // Build an edge list from the result stream. - List<Edge> edges = new ArrayList<Edge>(); - relationships.forEach(r -> edges.add(edgeFromChampRelationship(r))); - - return edges; - - } else { + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - // We couldn't find the specified vertex, so throw an exception. - throw new CrudException("No vertex with id " + id + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - - } catch (ChampUnmarshallingException e) { - - // Something went wrong, so throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - - } catch (ChampObjectNotExistsException e) { - - // We couldn't find the specified vertex, so throw an exception. + if (getResult.getResultCode() == 200) { + return champGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() { + }.getType()); + } else { + // We didn't find a vertex with the supplied id, so just throw an + // exception. throw new CrudException("No vertex with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); - } catch (ChampTransactionException e) { - throw new CrudException("Transaction error occured", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } - - @Override - public Vertex addVertex(String type, Map<String, Object> properties) throws CrudException { - - if (logger.isDebugEnabled()) { - logger.debug("Add/update vertex: {label: " + type + " properties:" + propertiesMapToString(properties)); - } - - // Add the aai_node_type so that AAI can read the data created by gizmo - properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - // Create an object to represent our vertex in the format expected by the - // Champ library. - ChampObject objectToCreate = buildChampObject(type, properties); - - try { - - // Ask the Champ library to store our vertex, placing the returned object - // into a - // list so that we can easily put that into our result object. - return vertexFromChampObject(champApi.storeObject(objectToCreate), type); - - } catch (ChampMarshallingException | ChampSchemaViolationException | ChampObjectNotExistsException - | ChampTransactionException e) { - - // Something went wrong - throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } - - @Override - public Vertex updateVertex(String id, String type, Map<String, Object> properties) throws CrudException { - - if (logger.isDebugEnabled()) { - logger.debug("Update vertex with id: " + id + " with properties: " + propertiesMapToString(properties)); - } - // Add the aai_node_type so that AAI can read the data created by gizmo - properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - try { - // Now, build the updated version of the Champ Object... - ChampObject updateObject = buildChampObject(id, type, properties); - // ...and send it to the Champ library. - return vertexFromChampObject(champApi.replaceObject(updateObject), type); - - } catch (ChampObjectNotExistsException e) { - throw new CrudException("Not Found", javax.ws.rs.core.Response.Status.NOT_FOUND); - } catch (NumberFormatException | ChampMarshallingException | ChampSchemaViolationException e) { - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } catch (ChampTransactionException e) { - throw new CrudException("Transaction error occured", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); } - } @Override public List<Vertex> getVertices(String type, Map<String, Object> filter) throws CrudException { - - if (logger.isDebugEnabled()) { - logger.debug("Retrieve vertices with type label: " + type + " which map query parameters: " - + propertiesMapToString(filter)); - } - filter.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - Stream<ChampObject> retrievedVertices; - try { - retrievedVertices = champApi.queryObjects(filter); - - } catch (ChampTransactionException e) { - throw new CrudException("Transaction error occured", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - - List<Vertex> vertices = retrievedVertices.map(v -> vertexFromChampObject(v, type)).collect(Collectors.toList()); - - if (logger.isDebugEnabled()) { - logger.debug("Resulting vertex list: " + retrievedVertices); - } + String url = baseObjectUrl + "/filter" + "?" + + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); - // ...and return it to the caller. - return vertices; - } + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - private Object getRelKey(String id) { - Object key = id; - // convert into Long if applicable . TODO : revisit in story NUC-304 - try { - key = Long.parseLong(id); - } catch (NumberFormatException e) { - // The id isn't a Long, leave it as a string + if (getResult.getResultCode() == 200) { + return champGson.fromJson(getResult.getResult(), new TypeToken<List<Vertex>>() { + }.getType()); + } else { + // We didn't find a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("No vertices found in graph for given filters", + javax.ws.rs.core.Response.Status.NOT_FOUND); } - - return key; } @Override public Edge getEdge(String id, String type) throws CrudException { + String url = baseRelationshipUrl + "/" + id; + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - if (logger.isDebugEnabled()) { - logger.debug("Get edge with id: " + id); - } - - try { - - // Request the edge from the graph db. - Optional<ChampRelationship> relationship = champApi.retrieveRelationship(getRelKey(id)); - - // Did we find it? - if (relationship.isPresent() && relationship.get().getType().equals(type)) { - - // Yup - return the result. - return edgeFromChampRelationship(relationship.get()); - - } else { + if (getResult.getResultCode() == 200) { + Edge edge = Edge.fromJson(getResult.getResult()); - // We didn't find an edge with the supplied id, so throw an exception. - throw new CrudException("No edge with id " + id + " found in graph", + if (!edge.getType().equalsIgnoreCase(type)) { + // We didn't find an edge with the supplied type, so just throw an + // exception. + throw new CrudException("No edge with id " + id + "and type " + type + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); } - - } catch (ChampUnmarshallingException | ChampTransactionException e) { - - // Something went wrong, so throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + return edge; + } else { + // We didn't find a edge with the supplied type, so just throw an + // exception. + throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); } } @Override - public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties) throws CrudException { - - // For now, assume source and target are straight ids... - try { - - Optional<ChampObject> sourceObject = champApi.retrieveObject(Long.parseLong(source.getId().get())); - if (!sourceObject.isPresent() || !sourceObject.get().getType().equals(source.getType())) { - throw new CrudException( - "Error creating edge - source vertex with id " + source + " does not exist in graph data base", - javax.ws.rs.core.Response.Status.BAD_REQUEST); - } - - Optional<ChampObject> targetObject = champApi.retrieveObject(Long.parseLong(target.getId().get())); - if (!targetObject.isPresent() || !targetObject.get().getType().equals(target.getType())) { - throw new CrudException( - "Error creating edge - target vertex with id " + target + " does not exist in graph data base", - javax.ws.rs.core.Response.Status.BAD_REQUEST); - } - - // Now, create the ChampRelationship object for our edge and store it in - // the graph database. - return edgeFromChampRelationship(champApi.storeRelationship( - new ChampRelationship.Builder(sourceObject.get(), targetObject.get(), type).properties(properties).build())); + public List<Edge> getEdges(String type, Map<String, Object> filter) throws CrudException { + String url = baseRelationshipUrl + "/filter" + "?" + + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); - } catch (ChampMarshallingException | ChampObjectNotExistsException | ChampSchemaViolationException - | ChampRelationshipNotExistsException | ChampUnmarshallingException | NumberFormatException - | ChampTransactionException e) { + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - throw new CrudException("Error creating edge: " + e.getMessage(), - javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == 200) { + return champGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() { + }.getType()); + } else { + // We didn't find a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("No edges found in graph for given filters", javax.ws.rs.core.Response.Status.NOT_FOUND); } } @Override - public List<Edge> getEdges(String type, Map<String, Object> filter) throws CrudException { - - filter.put(ChampRelationship.ReservedPropertyKeys.CHAMP_RELATIONSHIP_TYPE.toString(), type); - - Stream<ChampRelationship> retrievedRelationships; - try { - retrievedRelationships = champApi.queryRelationships(filter); - - } catch (ChampTransactionException e) { - throw new CrudException("Transaction error occured", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - - // Process the result stream from the Champ library into an Edge list, - // keeping only - // edges of the specified type. - List<Edge> edges = retrievedRelationships.map(r -> edgeFromChampRelationship(r)).collect(Collectors.toList()); + public Vertex addVertex(String type, Map<String, Object> properties) throws CrudException { + String url = baseObjectUrl; - return edges; - } + // Add the aai_node_type so that AAI can read the data created by gizmo + // TODO: This probably shouldn't be here + properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - @Override - public Edge updateEdge(Edge edge) throws CrudException { + Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); + properties.forEach(insertVertexBuilder::property); + Vertex insertVertex = insertVertexBuilder.build(); - if (logger.isDebugEnabled()) { - logger.debug( - "Update edge with id: " + edge.getId() + " with properties: " + propertiesMapToString(edge.getProperties())); - } + OperationResult getResult = client.post(url, insertVertex.toJson(), createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); - try { - // Now, build the updated version of the Champ Relationship... - ChampRelationship updateRelationship = new ChampRelationship.Builder( - buildChampObject(edge.getSource().getId().get(), edge.getSource().getType(), - edge.getSource().getProperties()), - buildChampObject(edge.getTarget().getId().get(), edge.getTarget().getType(), - edge.getTarget().getProperties()), - edge.getType()).key(getRelKey(edge.getId().get())).properties(edge.getProperties()).build(); - // ...and send it to the Champ library. - return edgeFromChampRelationship(champApi.replaceRelationship(updateRelationship)); - - } catch (ChampRelationshipNotExistsException ex) { - throw new CrudException("Not Found", javax.ws.rs.core.Response.Status.NOT_FOUND); - } catch (NumberFormatException | ChampUnmarshallingException | ChampMarshallingException - | ChampSchemaViolationException | ChampTransactionException ex) { - - throw new CrudException(ex.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { + return Vertex.fromJson(getResult.getResult()); + } else { + // We didn't create a vertex with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode())); } } @Override - public void deleteVertex(String id, String type) throws CrudException { - - try { - - // First, retrieve the vertex that we intend to delete. - Optional<ChampObject> retrievedVertex = champApi.retrieveObject(Long.parseLong(id)); - - // Did we find it? - if (!retrievedVertex.isPresent() || !retrievedVertex.get().getType().equals(type)) { - throw new CrudException("Failed to delete vertex with id: " + id + " - vertex does not exist.", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - - // Now, verify that there are no edges incident to the vertex (they must - // be deleted - // first if so). - Stream<ChampRelationship> relationships = champApi.retrieveRelationships(retrievedVertex.get()); + public Vertex updateVertex(String id, String type, Map<String, Object> properties) throws CrudException { + String url = baseObjectUrl + "/" + id; - if (relationships.count() > 0) { - throw new CrudException("Attempt to delete vertex with id " + id + " which has incident edges.", - javax.ws.rs.core.Response.Status.BAD_REQUEST); - } + // Add the aai_node_type so that AAI can read the data created by gizmo + // TODO: This probably shouldn't be here + properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - // Finally, we can attempt to delete our vertex. - champApi.deleteObject(Long.parseLong(id)); + Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); + insertVertexBuilder.id(id); + properties.forEach(insertVertexBuilder::property); + Vertex insertVertex = insertVertexBuilder.build(); - } catch (NumberFormatException | ChampUnmarshallingException | ChampObjectNotExistsException - | ChampTransactionException e) { + String payload = insertVertex.toJson(champGson); + OperationResult getResult = client.put(url, payload, createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { + return Vertex.fromJson(getResult.getResult()); + } else { + // We didn't create a vertex with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to update vertex", Response.Status.fromStatusCode(getResult.getResultCode())); } } @Override - public void deleteEdge(String id, String type) throws CrudException { - - try { - - // First, retrieve the edge that we want to delete. - Optional<ChampRelationship> relationshipToDelete = champApi.retrieveRelationship(getRelKey(id)); - - // Did we find it? - if (!relationshipToDelete.isPresent() || !relationshipToDelete.get().getType().equals(type)) { - throw new CrudException("Failed to delete edge with id: " + id + " - edge does not exist", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - - // Now we can delete the edge. - champApi.deleteRelationship(relationshipToDelete.get()); - - } catch (ChampRelationshipNotExistsException | NumberFormatException | ChampUnmarshallingException - | ChampTransactionException e) { + public void deleteVertex(String id, String type) throws CrudException { + String url = baseObjectUrl + "/" + id; + OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) { + // We didn't delete a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("Failed to delete vertex", Response.Status.fromStatusCode(getResult.getResultCode())); } } - /** - * This helper method generates a string representation of a properties map - * for logging purposes. - * - * @param properties - * - The properties map to be converted. - * @return - The log statement friendly conversion of the properties map. - */ - private String propertiesMapToString(Map<String, Object> properties) { - - StringBuilder sb = new StringBuilder(); - sb.append("{"); - - for (String key : properties.keySet()) { - sb.append("(").append(key).append(" -> ").append(properties.get(key)).append(") "); - } + @Override + public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties) throws CrudException { + String url = baseRelationshipUrl; - sb.append("}"); + // Try requests to ensure source and target exist in Champ + Vertex dbSource = getVertex(source.getId().get(), source.getType()); + Vertex dbTarget = getVertex(target.getId().get(), target.getType()); - return sb.toString(); - } + Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget); + properties.forEach(insertEdgeBuilder::property); + Edge insertEdge = insertEdgeBuilder.build(); - /** - * This helper method constructs a {@link ChampObject} suitable for passing to - * the Champ library. - * - * @param type - * - The type to assign to our ChampObject - * @param properties - * - The set of properties to assign to our ChampObject - * @return - A populated ChampObject - */ - private ChampObject buildChampObject(String type, Map<String, Object> properties) { - - ObjectBuildOrPropertiesStep objectInProgress = ChampObject.create().ofType(type).withoutKey(); - - for (String key : properties.keySet()) { - objectInProgress.withProperty(key, properties.get(key)); - } - return objectInProgress.build(); - } + String edgeJson = insertEdge.toJson(champGson); + OperationResult getResult = client.post(url, edgeJson, createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); - /** - * This helper method constructs a {@link ChampObject} suitable for passing to - * the Champ library. - * - * @param id - * - Unique identifier for this object. - * @param type - * - The type to assign to our ChampObject - * @param properties - * - The set of properties to assign to our ChampObject - * @return - A populated ChampObject - */ - private ChampObject buildChampObject(String id, String type, Map<String, Object> properties) { - - ObjectBuildOrPropertiesStep objectInProgress = ChampObject.create().ofType(type).withKey(Long.parseLong(id)); - - for (String key : properties.keySet()) { - objectInProgress.withProperty(key, properties.get(key)); + if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { + return Edge.fromJson(getResult.getResult()); + } else { + // We didn't create an edge with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to create edge", Response.Status.fromStatusCode(getResult.getResultCode())); } - return objectInProgress.build(); } - private Vertex vertexFromChampObject(ChampObject champObject, String type) { - - // Get the identifier for this vertex from the Champ object. - Object id = champObject.getKey().orElse(""); - - // Start building our {@link Vertex} object. - Vertex.Builder vertexBuilder = new Vertex.Builder(type); - vertexBuilder.id(id.toString()); - - // Convert the properties associated with the Champ object into the form - // expected for - // a Vertex object. - for (String key : champObject.getProperties().keySet()) { - vertexBuilder.property(key, champObject.getProperties().get(key)); + @Override + public Edge updateEdge(Edge edge) throws CrudException { + if (!edge.getId().isPresent()) { + throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST); } + String url = baseRelationshipUrl + "/" + edge.getId().get(); - // ...and return it. - return vertexBuilder.build(); - } + String edgeJson = edge.toJson(champGson); + OperationResult getResult = client.put(url, edgeJson, createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); - /** - * This helper method converts a {@link ChampRelationship} from the Champ - * library into an equivalent {@link Edge} object that is understood by the - * CRUD Service. - * - * @param relationship - * - The ChampRelationship object to be converted. - * @return - An Edge object corresponding to the supplied ChampRelationship - */ - private Edge edgeFromChampRelationship(ChampRelationship relationship) { - - // Populate the edge's id, if available. - Object relationshipId = relationship.getKey().orElse(""); - - Edge.Builder edgeBuilder = new Edge.Builder(relationship.getType()).id(relationshipId.toString()); - edgeBuilder.source(vertexFromChampObject(relationship.getSource(), - relationship.getSource().getProperties() - .get(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) == null - ? relationship.getSource().getType() - : relationship.getSource().getProperties() - .get(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString())); - edgeBuilder.target(vertexFromChampObject(relationship.getTarget(), - relationship.getTarget().getProperties() - .get(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) == null - ? relationship.getTarget().getType() - : relationship.getTarget().getProperties() - .get(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString())); - - for (String key : relationship.getProperties().keySet()) { - edgeBuilder.property(key, relationship.getProperties().get(key).toString()); + if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { + return Edge.fromJson(getResult.getResult()); + } else { + // We didn't create an edge with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to update edge", Response.Status.fromStatusCode(getResult.getResultCode())); } - - return edgeBuilder.build(); } - /** - * Performs any necessary shut down operations when the DAO is no longer - * needed. - */ - public void close() { - - if (champApi != null) { - - logger.info(CrudServiceMsgs.STOPPING_CHAMP_DAO); + @Override + public void deleteEdge(String id, String type) throws CrudException { + String url = baseRelationshipUrl + "/" + id; + OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - champApi.shutdown(); + if (getResult.getResultCode() != 200) { + // We didn't find an edge with the supplied type, so just throw an + // exception. + throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); } } @Override public String openTransaction() { + String url = baseTransactionUrl; - ChampTransaction transaction = champApi.openTransaction(); + OperationResult getResult = client.post(url, "", createHeader(), MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_PLAIN_TYPE); - transactions.put(transaction.id(), transaction); - logger.info(CrudServiceMsgs.TRANSACTION, "Stored transaction " + transaction.id() + " in hashmap"); - logger.info(CrudServiceMsgs.TRANSACTION, "Hash map contents:"); - for (String key : transactions.keySet()) { - logger.info(CrudServiceMsgs.TRANSACTION, key); + if (getResult.getResultCode() == 200) { + return getResult.getResult(); + } else { + return null; } - return transaction.id(); } @Override public void commitTransaction(String id) throws CrudException { + String url = baseTransactionUrl + "/" + id; - try { - champApi.commitTransaction(getTransaction(id)); - } catch (ChampTransactionException e) { - throw new CrudException("Error while commiting transaction " + id, - javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + OperationResult getResult = client.put(url, "{\"method\": \"commit\"}", createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.TEXT_PLAIN_TYPE); + + if (getResult.getResultCode() != 200) { + throw new CrudException("Unable to commit transaction", + Response.Status.fromStatusCode(getResult.getResultCode())); } - transactions.remove(id); } @Override public void rollbackTransaction(String id) throws CrudException { + String url = baseTransactionUrl + "/" + id; - try { - champApi.rollbackTransaction(getTransaction(id)); - } catch (ChampTransactionException e) { - throw new CrudException("Error while transaction rollback " + id, - javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + OperationResult getResult = client.put(url, "{\"method\": \"rollback\"}", createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.TEXT_PLAIN_TYPE); + + if (getResult.getResultCode() != 200) { + throw new CrudException("Unable to rollback transaction", + Response.Status.fromStatusCode(getResult.getResultCode())); } - transactions.remove(id); } - private ChampTransaction getTransaction(String id) throws CrudException { + @Override + public boolean transactionExists(String id) throws CrudException { + String url = baseTransactionUrl + "/" + id; + Map<String, List<String>> headers = new HashMap<>(); + headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); + headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - logger.info(CrudServiceMsgs.TRANSACTION, "Looking up transaction " + id); - if (transactions.containsKey(id)) { - logger.info(CrudServiceMsgs.TRANSACTION, "Found it!"); - return (transactions.get(id)); - } else { - logger.info(CrudServiceMsgs.TRANSACTION, "Didn't find transaction id " + id + ". Hash map contains: "); - for (String key : transactions.keySet()) { - logger.info(CrudServiceMsgs.TRANSACTION, key); - } - throw new CrudException("No open transaction with id: " + id, javax.ws.rs.core.Response.Status.NOT_FOUND); - } + OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); + + return getResult.getResultCode() == 200; } @Override public Vertex addVertex(String type, Map<String, Object> properties, String txId) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("Add/update vertex: {label: " + type + " properties:" + propertiesMapToString(properties)); - } + String url = baseObjectUrl + "?transactionId=" + txId; // Add the aai_node_type so that AAI can read the data created by gizmo + // TODO: This probably shouldn't be here properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - // Create an object to represent our vertex in the format expected by the - // Champ library. - ChampObject objectToCreate = buildChampObject(type, properties); + Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); + properties.forEach(insertVertexBuilder::property); + Vertex insertVertex = insertVertexBuilder.build(); - try { - - // Ask the Champ library to store our vertex, placing the returned object - // into a - // list so that we can easily put that into our result object. - return vertexFromChampObject(champApi.storeObject(objectToCreate, Optional.of(getTransaction(txId))), type); + OperationResult getResult = client.post(url, insertVertex.toJson(), createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); - } catch (ChampMarshallingException | ChampSchemaViolationException | ChampObjectNotExistsException - | ChampTransactionException e) { - - // Something went wrong - throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { + return Vertex.fromJson(getResult.getResult()); + } else { + // We didn't create a vertex with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode())); } } @Override public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties, String txId) throws CrudException { - // For now, assume source and target are straight ids... - try { - - Optional<ChampObject> sourceObject = champApi.retrieveObject(Long.parseLong(source.getId().get()), - Optional.of(getTransaction(txId))); - if (!sourceObject.isPresent() || !sourceObject.get().getType().equals(source.getType())) { - throw new CrudException( - "Error creating edge - source vertex with id " + source + " does not exist in graph data base", - javax.ws.rs.core.Response.Status.BAD_REQUEST); - } + String url = baseRelationshipUrl + "?transactionId=" + txId; - Optional<ChampObject> targetObject = champApi.retrieveObject(Long.parseLong(target.getId().get()), - Optional.of(getTransaction(txId))); - if (!targetObject.isPresent() || !targetObject.get().getType().equals(target.getType())) { - throw new CrudException( - "Error creating edge - target vertex with id " + target + " does not exist in graph data base", - javax.ws.rs.core.Response.Status.BAD_REQUEST); - } + // Try requests to ensure source and target exist in Champ + Vertex dbSource = getVertex(source.getId().get(), source.getType(), txId); + Vertex dbTarget = getVertex(target.getId().get(), target.getType(), txId); - // Now, create the ChampRelationship object for our edge and store it in - // the graph database. - return edgeFromChampRelationship(champApi.storeRelationship( - new ChampRelationship.Builder(sourceObject.get(), targetObject.get(), type).properties(properties).build(), - Optional.of(getTransaction(txId)))); + Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget); + properties.forEach(insertEdgeBuilder::property); + Edge insertEdge = insertEdgeBuilder.build(); - } catch (ChampMarshallingException | ChampObjectNotExistsException | ChampSchemaViolationException - | ChampTransactionException | ChampRelationshipNotExistsException | ChampUnmarshallingException e) { + OperationResult getResult = client.post(url, insertEdge.toJson(champGson), createHeader(), + MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); - throw new CrudException("Error creating edge: " + e.getMessage(), - javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { + return Edge.fromJson(getResult.getResult()); + } else { + // We didn't create an edge with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to create edge", Response.Status.fromStatusCode(getResult.getResultCode())); } - } @Override public Vertex updateVertex(String id, String type, Map<String, Object> properties, String txId) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("Update vertex with id: " + id + " with properties: " + propertiesMapToString(properties)); - } + String url = baseObjectUrl + "/" + id + "?transactionId=" + txId; + // Add the aai_node_type so that AAI can read the data created by gizmo + // TODO: This probably shouldn't be here properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - try { - // Now, build the updated version of the Champ Object... - ChampObject updateObject = buildChampObject(id, type, properties); - // ...and send it to the Champ library. - return vertexFromChampObject(champApi.replaceObject(updateObject, Optional.of(getTransaction(txId))), type); - - } catch (ChampObjectNotExistsException e) { - throw new CrudException("Not Found", javax.ws.rs.core.Response.Status.NOT_FOUND); - } catch (NumberFormatException | ChampMarshallingException | ChampTransactionException - | ChampSchemaViolationException e) { - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } + Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); + insertVertexBuilder.id(id); + properties.forEach(insertVertexBuilder::property); + Vertex insertVertex = insertVertexBuilder.build(); - @Override - public boolean transactionExists(String id) throws CrudException { - return transactions.containsKey(id); + String payload = insertVertex.toJson(champGson); + OperationResult getResult = client.put(url, payload, createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); + + if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { + return Vertex.fromJson(getResult.getResult()); + } else { + // We didn't create a vertex with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to update vertex", Response.Status.fromStatusCode(getResult.getResultCode())); + } } @Override public void deleteVertex(String id, String type, String txId) throws CrudException { - try { - - // First, retrieve the vertex that we intend to delete. - Optional<ChampObject> retrievedVertex = champApi.retrieveObject(Long.parseLong(id), - Optional.of(getTransaction(txId))); - - // Did we find it? - if (!retrievedVertex.isPresent() || !retrievedVertex.get().getType().equals(type)) { - throw new CrudException("Failed to delete vertex with id: " + id + " - vertex does not exist.", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - - // Now, verify that there are no edges incident to the vertex (they must - // be deleted - // first if so). - Stream<ChampRelationship> relationships = champApi.retrieveRelationships(retrievedVertex.get(), - Optional.of(getTransaction(txId))); - - if (relationships.count() > 0) { - throw new CrudException("Attempt to delete vertex with id " + id + " which has incident edges.", - javax.ws.rs.core.Response.Status.BAD_REQUEST); - } + String url = baseObjectUrl + "/" + id + "?transactionId=" + txId; + OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - // Finally, we can attempt to delete our vertex. - champApi.deleteObject(Long.parseLong(id), Optional.of(getTransaction(txId))); - - } catch (NumberFormatException | ChampUnmarshallingException | ChampObjectNotExistsException - | ChampTransactionException e) { - - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) { + // We didn't delete a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("Failed to delete vertex", Response.Status.fromStatusCode(getResult.getResultCode())); } - } @Override public Edge updateEdge(Edge edge, String txId) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug( - "Update edge with id: " + edge.getId() + " with properties: " + propertiesMapToString(edge.getProperties())); + if (!edge.getId().isPresent()) { + throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST); } + String url = baseRelationshipUrl + "/" + edge.getId().get() + "?transactionId=" + txId; + OperationResult getResult = client.put(url, edge.toJson(champGson), createHeader(), MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); - try { - // Now, build the updated version of the Champ Relationship... - ChampRelationship updateRelationship = new ChampRelationship.Builder( - buildChampObject(edge.getSource().getId().get(), edge.getSource().getType(), - edge.getSource().getProperties()), - buildChampObject(edge.getTarget().getId().get(), edge.getTarget().getType(), - edge.getTarget().getProperties()), - edge.getType()).key(getRelKey(edge.getId().get())).properties(edge.getProperties()).build(); - // ...and send it to the Champ library. - return edgeFromChampRelationship( - champApi.replaceRelationship(updateRelationship, Optional.of(getTransaction(txId)))); - - } catch (ChampRelationshipNotExistsException ex) { - throw new CrudException("Not Found", javax.ws.rs.core.Response.Status.NOT_FOUND); - } catch (NumberFormatException | ChampUnmarshallingException | ChampMarshallingException - | ChampSchemaViolationException | ChampTransactionException ex) { - - throw new CrudException(ex.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { + return Edge.fromJson(getResult.getResult()); + } else { + // We didn't create an edge with the supplied type, so just throw an + // exception. + throw new CrudException("Failed to update edge: " + getResult.getFailureCause(), + Response.Status.fromStatusCode(getResult.getResultCode())); } } @Override public void deleteEdge(String id, String type, String txId) throws CrudException { - try { - - // First, retrieve the edge that we want to delete. - Optional<ChampRelationship> relationshipToDelete = champApi.retrieveRelationship(getRelKey(id), - Optional.of(getTransaction(txId))); - - // Did we find it? - if (!relationshipToDelete.isPresent() || !relationshipToDelete.get().getType().equals(type)) { - throw new CrudException("Failed to delete edge with id: " + id + " - edge does not exist", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - - // Now we can delete the edge. - champApi.deleteRelationship(relationshipToDelete.get(), Optional.of(getTransaction(txId))); - - } catch (ChampRelationshipNotExistsException | NumberFormatException | ChampUnmarshallingException - | ChampTransactionException e) { + String url = baseRelationshipUrl + "/" + id + "?transactionId=" + txId; + OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + if (getResult.getResultCode() != 200) { + // We didn't find an edge with the supplied type, so just throw an + // exception. + throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); } - } @Override public Edge getEdge(String id, String type, String txId) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("Get edge with id: " + id); - } - - try { + String url = baseRelationshipUrl + "/" + id + "?transactionId=" + txId; + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - // Request the edge from the graph db. - Optional<ChampRelationship> relationship = champApi.retrieveRelationship(getRelKey(id), - Optional.of(getTransaction(txId))); + if (getResult.getResultCode() == 200) { + Edge edge = Edge.fromJson(getResult.getResult()); - // Did we find it? - if (relationship.isPresent() && relationship.get().getType().equals(type)) { + if (!edge.getType().equalsIgnoreCase(type)) { + // We didn't find an edge with the supplied type, so just throw an + // exception. + throw new CrudException("No edge with id " + id + "and type " + type + " found in graph", + javax.ws.rs.core.Response.Status.NOT_FOUND); + } + return edge; + } else { + // We didn't find an edge with the supplied id, so just throw an + // exception. + throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); + } + } - // Yup - return the result. - return edgeFromChampRelationship(relationship.get()); + public Vertex getVertex(String id, String type, String txId) throws CrudException { + String url = baseObjectUrl + "/" + id + "?transactionId=" + txId; + OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE); - } else { + if (getResult.getResultCode() == 200) { + Vertex vert = Vertex.fromJson(getResult.getResult()); - // We didn't find an edge with the supplied id, so throw an exception. - throw new CrudException("No edge with id " + id + " found in graph", + if (!vert.getType().equalsIgnoreCase(type)) { + // We didn't find a vertex with the supplied type, so just throw an + // exception. + throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); } - - } catch (ChampUnmarshallingException | ChampTransactionException e) { - - // Something went wrong, so throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + return vert; + } else { + // We didn't find a vertex with the supplied id, so just throw an + // exception. + throw new CrudException("No vertex with id " + id + " found in graph", + javax.ws.rs.core.Response.Status.NOT_FOUND); } } + // https://stackoverflow.com/questions/26942330/convert-mapstring-string-to-listnamevaluepair-is-this-the-most-efficient + private List<NameValuePair> convertToNameValuePair(Map<String, Object> pairs) { + List<NameValuePair> nvpList = new ArrayList<>(pairs.size()); + + pairs.forEach((key, value) -> nvpList.add(new BasicNameValuePair(key, value.toString()))); + + return nvpList; + } + + private Map<String, List<String>> createHeader() { + Map<String, List<String>> headers = new HashMap<>(); + headers.put(HEADER_FROM_APP, Arrays.asList(FROM_APP_NAME)); + headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); + return headers; + } } diff --git a/src/main/java/org/onap/crud/dao/champion/ChampionEdgeSerializer.java b/src/main/java/org/onap/crud/dao/champ/ChampEdgeSerializer.java index 655d096..ed92b48 100644 --- a/src/main/java/org/onap/crud/dao/champion/ChampionEdgeSerializer.java +++ b/src/main/java/org/onap/crud/dao/champ/ChampEdgeSerializer.java @@ -21,7 +21,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -package org.onap.crud.dao.champion; +package org.onap.crud.dao.champ; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -29,11 +29,10 @@ import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import org.onap.crud.entity.Edge; -import org.onap.crud.entity.Vertex; import java.lang.reflect.Type; -public class ChampionEdgeSerializer implements JsonSerializer<Edge> { +public class ChampEdgeSerializer implements JsonSerializer<Edge> { @Override public JsonElement serialize(Edge edge, Type type, JsonSerializationContext jsonSerializationContext) { final JsonObject edgeObj = new JsonObject(); diff --git a/src/main/java/org/onap/crud/dao/champion/ChampionVertexSerializer.java b/src/main/java/org/onap/crud/dao/champ/ChampVertexSerializer.java index 904ad2e..bdeb3d6 100644 --- a/src/main/java/org/onap/crud/dao/champion/ChampionVertexSerializer.java +++ b/src/main/java/org/onap/crud/dao/champ/ChampVertexSerializer.java @@ -21,7 +21,7 @@ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -package org.onap.crud.dao.champion; +package org.onap.crud.dao.champ; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -32,7 +32,7 @@ import org.onap.crud.entity.Vertex; import java.lang.reflect.Type; -public class ChampionVertexSerializer implements JsonSerializer<Vertex> { +public class ChampVertexSerializer implements JsonSerializer<Vertex> { @Override public JsonElement serialize(Vertex vertex, Type type, JsonSerializationContext jsonSerializationContext) { final JsonObject vertexObj = new JsonObject(); diff --git a/src/main/java/org/onap/crud/dao/champion/ChampionDao.java b/src/main/java/org/onap/crud/dao/champion/ChampionDao.java deleted file mode 100644 index 4bde2e0..0000000 --- a/src/main/java/org/onap/crud/dao/champion/ChampionDao.java +++ /dev/null @@ -1,623 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * Gizmo - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.crud.dao.champion; - -import net.dongliu.gson.GsonJava8TypeAdapterFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import org.apache.http.NameValuePair; -import org.apache.http.client.utils.URLEncodedUtils; -import org.apache.http.message.BasicNameValuePair; -import org.eclipse.jetty.util.security.Password; -import org.onap.aai.logging.LoggingContext; -import org.onap.aai.cl.api.Logger; -import org.onap.aai.cl.eelf.LoggerFactory; -import org.onap.crud.dao.GraphDao; -import org.onap.crud.entity.Edge; -import org.onap.crud.entity.Vertex; -import org.onap.crud.exception.CrudException; -import org.onap.crud.util.CrudServiceConstants; -import org.onap.aai.restclient.client.OperationResult; -import org.onap.aai.restclient.client.RestClient; -import org.onap.aai.restclient.enums.RestAuthenticationMode; -import org.slf4j.MDC; - -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -public class ChampionDao implements GraphDao { - private RestClient client; - private String baseUrl; - - private static final String HEADER_FROM_APP = "X-FromAppId"; - private static final String HEADER_TRANS_ID = "X-TransactionId"; - - private Logger logger = LoggerFactory.getInstance().getLogger(ChampionDao.class.getName()); - - // We use a custom vertex serializer for Champion because it expects "key" - // instead of "id" - private static final Gson championGson = new GsonBuilder() - .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory()) - .registerTypeAdapter(Vertex.class, new ChampionVertexSerializer()) - .registerTypeAdapter(Edge.class, new ChampionEdgeSerializer()).create(); - - public ChampionDao(String championUrl, String certPassword) { - try { - client = new RestClient().authenticationMode(RestAuthenticationMode.SSL_CERT).validateServerHostname(false) - .validateServerCertChain(false).clientCertFile(CrudServiceConstants.CRD_CHAMPION_AUTH_FILE) - .clientCertPassword(Password.deobfuscate(certPassword)); - - baseUrl = championUrl; - } catch (Exception e) { - System.out.println("Error setting up Champion configuration"); - e.printStackTrace(); - System.exit(1); - } - } - - @Override - public Vertex getVertex(String id) throws CrudException { - String url = baseUrl + "objects/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - return Vertex.fromJson(getResult.getResult()); - } else { - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public Vertex getVertex(String id, String type) throws CrudException { - String url = baseUrl + "objects/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - Vertex vert = Vertex.fromJson(getResult.getResult()); - - if (!vert.getType().equalsIgnoreCase(type)) { - // We didn't find a vertex with the supplied type, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - return vert; - } else { - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public List<Edge> getVertexEdges(String id) throws CrudException { - String url = baseUrl + "objects/relationships/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - return championGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() { - }.getType()); - } else { - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public List<Vertex> getVertices(String type, Map<String, Object> filter) throws CrudException { - filter.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - String url = baseUrl + "objects/filter" + "?" - + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); - - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - return championGson.fromJson(getResult.getResult(), new TypeToken<List<Vertex>>() { - }.getType()); - } else { - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No vertices found in graph for given filters", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public Edge getEdge(String id, String type) throws CrudException { - String url = baseUrl + "relationships/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - Edge edge = Edge.fromJson(getResult.getResult()); - - if (!edge.getType().equalsIgnoreCase(type)) { - // We didn't find an edge with the supplied type, so just throw an - // exception. - throw new CrudException("No edge with id " + id + "and type " + type + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - return edge; - } else { - // We didn't find a edge with the supplied type, so just throw an - // exception. - throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public List<Edge> getEdges(String type, Map<String, Object> filter) throws CrudException { - String url = baseUrl + "relationships/filter" + "?" - + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); - - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - return championGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() { - }.getType()); - } else { - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No edges found in graph for given filters", javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public Vertex addVertex(String type, Map<String, Object> properties) throws CrudException { - String url = baseUrl + "objects"; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - // Add the aai_node_type so that AAI can read the data created by gizmo - // TODO: This probably shouldn't be here - properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); - properties.forEach(insertVertexBuilder::property); - Vertex insertVertex = insertVertexBuilder.build(); - - OperationResult getResult = client.post(url, insertVertex.toJson(), headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { - return Vertex.fromJson(getResult.getResult()); - } else { - // We didn't create a vertex with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public Vertex updateVertex(String id, String type, Map<String, Object> properties) throws CrudException { - String url = baseUrl + "objects/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - // Add the aai_node_type so that AAI can read the data created by gizmo - // TODO: This probably shouldn't be here - properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); - insertVertexBuilder.id(id); - properties.forEach(insertVertexBuilder::property); - Vertex insertVertex = insertVertexBuilder.build(); - - String payload = insertVertex.toJson(championGson); - OperationResult getResult = client.put(url, payload, headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { - return Vertex.fromJson(getResult.getResult()); - } else { - // We didn't create a vertex with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to update vertex", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public void deleteVertex(String id, String type) throws CrudException { - String url = baseUrl + "objects/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.delete(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) { - // We didn't delete a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("Failed to delete vertex", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties) throws CrudException { - String url = baseUrl + "relationships"; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - // Try requests to ensure source and target exist in Champion - Vertex dbSource = getVertex(source.getId().get(), source.getType()); - Vertex dbTarget = getVertex(target.getId().get(), target.getType()); - - Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget); - properties.forEach(insertEdgeBuilder::property); - Edge insertEdge = insertEdgeBuilder.build(); - - String edgeJson = insertEdge.toJson(championGson); - OperationResult getResult = client.post(url, edgeJson, headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { - return Edge.fromJson(getResult.getResult()); - } else { - // We didn't create an edge with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to create edge", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public Edge updateEdge(Edge edge) throws CrudException { - if (!edge.getId().isPresent()) { - throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST); - } - String url = baseUrl + "relationships/" + edge.getId().get(); - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - String edgeJson = edge.toJson(championGson); - OperationResult getResult = client.put(url, edgeJson, headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { - return Edge.fromJson(getResult.getResult()); - } else { - // We didn't create an edge with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to update edge", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public void deleteEdge(String id, String type) throws CrudException { - String url = baseUrl + "relationships/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.delete(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() != 200) { - // We didn't find an edge with the supplied type, so just throw an - // exception. - throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public String openTransaction() { - String url = baseUrl + "transaction"; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.post(url, "", headers, MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_PLAIN_TYPE); - - if (getResult.getResultCode() == 200) { - return getResult.getResult(); - } else { - return null; - } - } - - @Override - public void commitTransaction(String id) throws CrudException { - String url = baseUrl + "transaction/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.put(url, "{\"method\": \"commit\"}", headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.TEXT_PLAIN_TYPE); - - if (getResult.getResultCode() != 200) { - throw new CrudException("Unable to commit transaction", - Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public void rollbackTransaction(String id) throws CrudException { - String url = baseUrl + "transaction/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.put(url, "{\"method\": \"rollback\"}", headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.TEXT_PLAIN_TYPE); - - if (getResult.getResultCode() != 200) { - throw new CrudException("Unable to rollback transaction", - Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public boolean transactionExists(String id) throws CrudException { - String url = baseUrl + "transaction/" + id; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - return getResult.getResultCode() == 200; - } - - @Override - public Vertex addVertex(String type, Map<String, Object> properties, String txId) throws CrudException { - String url = baseUrl + "objects?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - // Add the aai_node_type so that AAI can read the data created by gizmo - // TODO: This probably shouldn't be here - properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); - properties.forEach(insertVertexBuilder::property); - Vertex insertVertex = insertVertexBuilder.build(); - - OperationResult getResult = client.post(url, insertVertex.toJson(), headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { - return Vertex.fromJson(getResult.getResult()); - } else { - // We didn't create a vertex with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties, String txId) - throws CrudException { - String url = baseUrl + "relationships?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - // Try requests to ensure source and target exist in Champion - Vertex dbSource = getVertex(source.getId().get(), source.getType(), txId); - Vertex dbTarget = getVertex(target.getId().get(), target.getType(), txId); - - Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget); - properties.forEach(insertEdgeBuilder::property); - Edge insertEdge = insertEdgeBuilder.build(); - - OperationResult getResult = client.post(url, insertEdge.toJson(championGson), headers, - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) { - return Edge.fromJson(getResult.getResult()); - } else { - // We didn't create an edge with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to create edge", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public Vertex updateVertex(String id, String type, Map<String, Object> properties, String txId) throws CrudException { - String url = baseUrl + "objects/" + id + "?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - // Add the aai_node_type so that AAI can read the data created by gizmo - // TODO: This probably shouldn't be here - properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - - Vertex.Builder insertVertexBuilder = new Vertex.Builder(type); - insertVertexBuilder.id(id); - properties.forEach(insertVertexBuilder::property); - Vertex insertVertex = insertVertexBuilder.build(); - - String payload = insertVertex.toJson(championGson); - OperationResult getResult = client.put(url, payload, headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { - return Vertex.fromJson(getResult.getResult()); - } else { - // We didn't create a vertex with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to update vertex", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public void deleteVertex(String id, String type, String txId) throws CrudException { - String url = baseUrl + "objects/" + id + "?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.delete(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) { - // We didn't delete a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("Failed to delete vertex", Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public Edge updateEdge(Edge edge, String txId) throws CrudException { - if (!edge.getId().isPresent()) { - throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST); - } - String url = baseUrl + "relationships/" + edge.getId().get() + "?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.put(url, edge.toJson(championGson), headers, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) { - return Edge.fromJson(getResult.getResult()); - } else { - // We didn't create an edge with the supplied type, so just throw an - // exception. - throw new CrudException("Failed to update edge: " + getResult.getFailureCause(), - Response.Status.fromStatusCode(getResult.getResultCode())); - } - } - - @Override - public void deleteEdge(String id, String type, String txId) throws CrudException { - String url = baseUrl + "relationships/" + id + "?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.delete(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() != 200) { - // We didn't find an edge with the supplied type, so just throw an - // exception. - throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - @Override - public Edge getEdge(String id, String type, String txId) throws CrudException { - String url = baseUrl + "relationships/" + id + "?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - Edge edge = Edge.fromJson(getResult.getResult()); - - if (!edge.getType().equalsIgnoreCase(type)) { - // We didn't find an edge with the supplied type, so just throw an - // exception. - throw new CrudException("No edge with id " + id + "and type " + type + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - return edge; - } else { - // We didn't find an edge with the supplied id, so just throw an - // exception. - throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - public Vertex getVertex(String id, String type, String txId) throws CrudException { - String url = baseUrl + "objects/" + id + "?transactionId=" + txId; - Map<String, List<String>> headers = new HashMap<>(); - headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); - headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString()))); - - OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); - - if (getResult.getResultCode() == 200) { - Vertex vert = Vertex.fromJson(getResult.getResult()); - - if (!vert.getType().equalsIgnoreCase(type)) { - // We didn't find a vertex with the supplied type, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - return vert; - } else { - // We didn't find a vertex with the supplied id, so just throw an - // exception. - throw new CrudException("No vertex with id " + id + " found in graph", - javax.ws.rs.core.Response.Status.NOT_FOUND); - } - } - - // https://stackoverflow.com/questions/26942330/convert-mapstring-string-to-listnamevaluepair-is-this-the-most-efficient - private List<NameValuePair> convertToNameValuePair(Map<String, Object> pairs) { - List<NameValuePair> nvpList = new ArrayList<>(pairs.size()); - - pairs.forEach((key, value) -> nvpList.add(new BasicNameValuePair(key, value.toString()))); - - return nvpList; - } -} diff --git a/src/main/java/org/onap/crud/service/CrudGraphDataService.java b/src/main/java/org/onap/crud/service/CrudGraphDataService.java index 268e492..d7def67 100644 --- a/src/main/java/org/onap/crud/service/CrudGraphDataService.java +++ b/src/main/java/org/onap/crud/service/CrudGraphDataService.java @@ -31,9 +31,7 @@ import java.util.Map; import javax.ws.rs.core.Response.Status; import org.onap.aaiutils.oxm.OxmModelLoader; -import org.onap.aai.champcore.ChampGraph; import org.onap.crud.dao.GraphDao; -import org.onap.crud.dao.champ.ChampDao; import org.onap.crud.entity.Edge; import org.onap.crud.entity.Vertex; @@ -49,12 +47,6 @@ public class CrudGraphDataService { private GraphDao dao; - public CrudGraphDataService(ChampGraph graphImpl) throws CrudException { - this.dao = new ChampDao(graphImpl); - - loadModels(); - } - public CrudGraphDataService(GraphDao dao) throws CrudException { this.dao = dao; diff --git a/src/main/java/org/onap/crud/util/CrudServiceConstants.java b/src/main/java/org/onap/crud/util/CrudServiceConstants.java index 0d07707..d3adaaa 100644 --- a/src/main/java/org/onap/crud/util/CrudServiceConstants.java +++ b/src/main/java/org/onap/crud/util/CrudServiceConstants.java @@ -30,25 +30,10 @@ public class CrudServiceConstants { : System.getProperty("file.separator"); public static final String CRD_SPECIFIC_CONFIG = System.getProperty("CONFIG_HOME") + CRD_FILESEP; - + public static final String CRD_CONFIG_FILE = CRD_SPECIFIC_CONFIG + "crud-api.properties"; public static final String CRD_HOME_MODEL = CRD_SPECIFIC_CONFIG + "model" + CRD_FILESEP; public static final String CRD_HOME_AUTH = CRD_SPECIFIC_CONFIG + "auth" + CRD_FILESEP; - - public static final String CRD_GRAPH_HOST = "crud.graph.host"; - public static final String CRD_GRAPH_PORT = "crud.graph.port"; - public static final String CRD_GRAPH_NAME = "crud.graph.name"; - public static final String CRD_STORAGE_BACKEND_DB = "crud.storage.backend.db"; - public static final String CRD_HBASE_ZNODE_PARENT - = "crud.storage.hbase.ext.zookeeper.znode.parent"; - - public static final String CRD_CONFIG_FILE = CRD_SPECIFIC_CONFIG + "crud-api.properties"; public static final String CRD_AUTH_FILE = CRD_HOME_AUTH + "crud_policy.json"; - public static final String CRD_CHAMPION_AUTH_FILE = CRD_HOME_AUTH + "champion-cert.p12"; - + public static final String CRD_CHAMP_AUTH_FILE = CRD_HOME_AUTH + "champ-cert.p12"; public static final String CRD_AUTH_POLICY_NAME = "crud"; - - public static final String CRD_EVENT_STREAM_HOSTS = "event.stream.hosts"; - - - } diff --git a/src/test/java/org/onap/crud/dao/champ/ChampDaoTest.java b/src/test/java/org/onap/crud/dao/champ/ChampDaoTest.java deleted file mode 100644 index eb1e987..0000000 --- a/src/test/java/org/onap/crud/dao/champ/ChampDaoTest.java +++ /dev/null @@ -1,624 +0,0 @@ -package org.onap.crud.dao.champ; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.aai.champcore.graph.impl.InMemoryChampGraphImpl; -import org.onap.crud.dao.GraphDao; -import org.onap.crud.entity.Edge; -import org.onap.crud.entity.Vertex; -import org.onap.crud.exception.CrudException; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.*; - - -/** - * This suite of tests validates the basic functionality of the {@link ChampDao}. - */ -public class ChampDaoTest { - - private static final String GRAPH_NAME = "my_test_graph"; - - private GraphDao champDao = null; - - - /** - * Perform setup steps that must be done prior to executing each test. - */ - @Before - public void setup() { - - // Create an instance of the Champ DAO, backed by the Champ library's in-memory back end - // for testing purposes. - Map<String, Object> champDaoProperties = new HashMap<String, Object>(); - champDaoProperties.put(ChampDao.CONFIG_STORAGE_BACKEND, "in-memory"); - champDaoProperties.put(ChampDao.CONFIG_GRAPH_NAME, GRAPH_NAME); - champDao = new ChampDao(new InMemoryChampGraphImpl.Builder().properties(champDaoProperties).build()); - } - - - /** - * Perform tear down steps that must be done after executing each test. - */ - @After - public void tearDown() { - - // Release the Champ DAO instance that we were using for the test. - if (champDao != null) { - ((ChampDao) champDao).close(); - } - } - - - /** - * Tests the ability of the {@link ChampDao} to create a vertex. - * - * @throws CrudException - */ - @Test - public void createVertexTest() throws CrudException { - - String VERTEX_TYPE = "Test_Vertex"; - - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put("property1", "something"); - properties.put("property2", "something else"); - - // Create the vertex. - Vertex createdVertex = champDao.addVertex(VERTEX_TYPE, properties); - - // Validate that the returned {@link Vertex} has the right label assigned to it. - assertTrue("Unexpected vertex type '" + createdVertex.getType() + "' returned from DAO", - createdVertex.getType().equals(VERTEX_TYPE)); - - // Validate that all of the properties that we provided to the DAO are in fact assigned - // to the {@link Vertex} that we got back. - assertTrue("Vertex property list returned from DAO did not contain all expected properties - expected: " + - properties.keySet() + " actual: " + createdVertex.getProperties().keySet(), - createdVertex.getProperties().keySet().containsAll(properties.keySet())); - - // Validate that the values assigned to the properties in the returned {@link Vertex} - // match the ones that we provided. - for (String propertyKey : properties.keySet()) { - - assertTrue(createdVertex.getProperties().get(propertyKey).equals(properties.get(propertyKey))); - } - } - - - /** - * Tests the ability of the {@link ChampDao} to retrieve a vertex from the graph data store - * by its unique identifier. - * - * @throws CrudException - */ - @Test - public void getVertexByIdTest() throws CrudException { - - String VERTEX_TYPE = "Test_Vertex"; - - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put("property1", "something"); - properties.put("property2", "something else"); - - // Create the vertex. - Vertex createdVertex = champDao.addVertex(VERTEX_TYPE, properties); - - // Make sure the {@link Vertex} returned from the create method includes an id that we can - // use to retrieve it. - assertTrue("No valid id returned for the created vertex", createdVertex.getId().isPresent()); - - // Now, retrieve the {@link Vertex} by its identifier. - Vertex retrievedVertex = champDao.getVertex(createdVertex.getId().get(), VERTEX_TYPE); - - // Validate that the retrieved {@link Vertex} has the right label assigned to it. - assertTrue("Unexpected vertex type '" + retrievedVertex.getType() + "' returned from DAO", - retrievedVertex.getType().equals(VERTEX_TYPE)); - - // Validate that all of the properties that we provided when we created the {@link Vertex} - // are present in the {@link Vertex} that we retrieved. - assertTrue("Vertex property list returned from DAO did not contain all expected properties - expected: " + - properties.keySet() + " actual: " + retrievedVertex.getProperties().keySet(), - retrievedVertex.getProperties().keySet().containsAll(properties.keySet())); - - // Validate that the values assigned to the properties in the retrieved {@link Vertex} - // match the ones that we provided when we created it. - for (String propertyKey : properties.keySet()) { - - assertTrue(retrievedVertex.getProperties().get(propertyKey).equals(properties.get(propertyKey))); - } - } - - - /** - * Tests the ability of the {@link ChampDao} to update an already existing vertex. - * - * @throws CrudException - */ - @Test - public void updateVertexTest() throws CrudException { - - final String VERTEX_TYPE = "Test_Vertex"; - - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put("property1", "something"); - properties.put("property2", "something else"); - - // Create the vertex. - Vertex createdVertex = champDao.addVertex(VERTEX_TYPE, properties); - - // Make sure the {@link Vertex} returned from the create method includes an id that we can - // use to retrieve it. - assertTrue("No valid id returned for the created vertex", createdVertex.getId().isPresent()); - - // Modify the properties list... - properties.put("property3", "a new property"); - properties.remove("property1"); - - // ...and apply it to our vertex. - Vertex updatedVertex = champDao.updateVertex(createdVertex.getId().get(), createdVertex.getType(), properties); - - assertTrue("Vertex property list returned from DAO update operation did not contain all expected properties - expected: " + - properties.keySet() + " actual: " + updatedVertex.getProperties().keySet(), - updatedVertex.getProperties().keySet().containsAll(properties.keySet())); - - // Validate that the values assigned to the properties in the updated {@link Vertex} - // match the ones that we provided when we created it. - for (String propertyKey : properties.keySet()) { - - assertTrue("Unexpected value for property '" + propertyKey + "' - Expected: " + - properties.get(propertyKey) + " Actual: " + - updatedVertex.getProperties().get(propertyKey), - updatedVertex.getProperties().get(propertyKey).equals(properties.get(propertyKey))); - } - - // Validate that the property that we removed is NOT in the set of properties from our - // updated {@link Vertex}. - assertFalse("Property 'property1' should no longer be associated with updated vertex", - updatedVertex.getProperties().containsKey("property1")); - } - - - /** - * Tests the ability of the {@link ChampDao} to retrieve multiple vertices which match - * a particular set of supplied properties. - * - * @throws CrudException - */ - @Test - public void getVerticesTest() throws CrudException { - - final String FIRST_VERTEX_TYPE = "pserver"; - final String SECOND_VERTEX_TYPE = "complex"; - - // Create some vertices. - - Map<String, Object> vertex1Properties = new HashMap<String, Object>(); - vertex1Properties.put("O/S", "Linux"); - vertex1Properties.put("version", "6.5"); - vertex1Properties.put("hostname", "kll0001"); - champDao.addVertex(FIRST_VERTEX_TYPE, vertex1Properties); - - Map<String, Object> vertex2Properties = new HashMap<String, Object>(); - vertex2Properties.put("O/S", "Linux"); - vertex2Properties.put("version", "6.5"); - vertex2Properties.put("hostname", "kll0002"); - champDao.addVertex(FIRST_VERTEX_TYPE, vertex2Properties); - - Map<String, Object> vertex3Properties = new HashMap<String, Object>(); - vertex3Properties.put("O/S", "Linux"); - vertex3Properties.put("version", "7.2"); - vertex3Properties.put("hostname", "kll0003"); - champDao.addVertex(FIRST_VERTEX_TYPE, vertex3Properties); - - Map<String, Object> vertex4Properties = new HashMap<String, Object>(); - vertex4Properties.put("O/S", "Windows"); - vertex4Properties.put("version", "10"); - vertex4Properties.put("hostname", "Dev Laptop"); - champDao.addVertex(FIRST_VERTEX_TYPE, vertex4Properties); - - Map<String, Object> vertex5Properties = new HashMap<String, Object>(); - vertex5Properties.put("Street", "Baker"); - vertex5Properties.put("Number", "222B"); - champDao.addVertex(SECOND_VERTEX_TYPE, vertex5Properties); - - // Create a set of properties to use for our query. - Map<String, Object> queryProperties = new HashMap<String, Object>(); - queryProperties.put("O/S", "Linux"); - queryProperties.put("version", "6.5"); - - // Validate that we filter our 'get vertices' results by type - List<Vertex> allVerticesByType = champDao.getVertices(FIRST_VERTEX_TYPE, MapBuilder.builder().build()); - for (Vertex v : allVerticesByType) { - assertTrue("Unexpected vertex type returned from query. Expected: " + - FIRST_VERTEX_TYPE + " Actual: " + v.getType(), - v.getType().equals(FIRST_VERTEX_TYPE)); - } - - // Now, request the vertices that match our parameters. - List<Vertex> vertices = champDao.getVertices(FIRST_VERTEX_TYPE, queryProperties); - - // Validate that got back the expected number of vertices. - assertEquals(vertices.size(), 2); - - // Validate that the vertices we got back contain the expected parameters. - for (Vertex v : vertices) { - - assertTrue("Vertex from query result does not contain expected vertex 'O/S'", - v.getProperties().containsKey("O/S")); - assertTrue("Vertex from query result contains unexpected value for 'O/S' parameter - Expected: 'Linux' Actual: '" + - v.getProperties().get("O/S") + "'", - v.getProperties().get("O/S").equals("Linux")); - - assertTrue("Vertex from query result does not contain expected vertex 'O/S'", - v.getProperties().containsKey("version")); - assertTrue("Vertex from query result contains unexpected value for 'O/S' parameter - Expected: 'Linux' Actual: '" + - v.getProperties().get("O/S") + "'", - v.getProperties().get("version").equals("6.5")); - } - } - - @Test - public void deleteVertexTest() throws CrudException { - - boolean deletedVertexNotFound = false; - - // Create a vertex. - Vertex createdVertex = champDao.addVertex("test_type", MapBuilder.builder() - .withKeyValue("O/S", "Linux") - .withKeyValue("version", "6.5") - .withKeyValue("hostname", "kll0001") - .build()); - - // Verify that we can retrieve the vertex from the graph data base. - Vertex retrievedVertex = champDao.getVertex(createdVertex.getId().get(), "test_type"); - - // Now, delete the vertex. - champDao.deleteVertex(createdVertex.getId().get(), "test_type"); - - // Now, try to retrieve it again. This time we should fail to find it. - try { - champDao.getVertex(createdVertex.getId().get(), "test_type"); - - } catch (CrudException e) { - assertTrue(e.getMessage().contains("No vertex with id")); - deletedVertexNotFound = true; - } - - assertTrue("Should not have been able to retrieve deleted vertex", deletedVertexNotFound); - } - - @Test - public void createEdgeTest() throws CrudException { - - String EDGE_TYPE = "has"; - - // Create the source vertex for the edge. - Map<String, Object> srcVertexProperties = new HashMap<String, Object>(); - srcVertexProperties.put("O/S", "Linux"); - srcVertexProperties.put("version", "6.5"); - srcVertexProperties.put("hostname", "kll0001"); - Vertex sourceVertex = champDao.addVertex("vserver", srcVertexProperties); - - // Create the target vertex for the edge. - Map<String, Object> dstVertexProperties = new HashMap<String, Object>(); - dstVertexProperties.put("O/S", "Linux"); - dstVertexProperties.put("version", "6.5"); - dstVertexProperties.put("hostname", "kll0002"); - Vertex destVertex = champDao.addVertex("VNF", dstVertexProperties); - - // Now, create the edge itself. - Map<String, Object> edgeProperties = new HashMap<String, Object>(); - edgeProperties.put("prop", "val"); - Edge createdEdge = champDao.addEdge("has", sourceVertex, destVertex, edgeProperties); - - // Validate that the Edge object returned from the create method matches what we were - // trying to create. - assertTrue("Unexpected type for Edge returned from create method. Expected: " + EDGE_TYPE - + " Actual: " + createdEdge.getType(), - createdEdge.getType().equals("has")); - assertTrue("Unexpected properties for Edge returned from create method. Expected: " + edgeProperties - + " Actual: " + createdEdge.getProperties(), - createdEdge.getProperties().equals(edgeProperties)); - - } - - @Test - public void createEdgeWithMissingSrcOrTargetTest() throws CrudException { - - String EDGE_TYPE = "has"; - - // Create the source vertex for the edge. - Map<String, Object> srcVertexProperties = new HashMap<String, Object>(); - srcVertexProperties.put("O/S", "Linux"); - srcVertexProperties.put("version", "6.5"); - srcVertexProperties.put("hostname", "kll0001"); - Vertex sourceVertex = champDao.addVertex("vserver", srcVertexProperties); - - // Create the target vertex for the edge. - Map<String, Object> dstVertexProperties = new HashMap<String, Object>(); - dstVertexProperties.put("O/S", "Linux"); - dstVertexProperties.put("version", "6.5"); - dstVertexProperties.put("hostname", "kll0002"); - Vertex destVertex = champDao.addVertex("VNF", dstVertexProperties); - - // Now, try creating the Edge but specify an id for the source vertex that does - // not exist. - Map<String, Object> edgeProperties = new HashMap<String, Object>(); - edgeProperties.put("prop", "val"); - try { - champDao.addEdge(EDGE_TYPE, new Vertex.Builder("miss").id("99").build(), destVertex, edgeProperties); - } catch (CrudException e) { - assertTrue(e.getMessage().contains("Error creating edge - source vertex")); - } - - // Now, try created the Edge with a valid source vertex, but specify an id for the - // target vertex that does not exist. - try { - champDao.addEdge(EDGE_TYPE, sourceVertex, new Vertex.Builder("miss").id("99").build(), edgeProperties); - } catch (CrudException e) { - assertTrue(e.getMessage().contains("Error creating edge - target vertex")); - } - - } - - @Test - public void getEdgeByIdTest() throws CrudException { - - String EDGE_TYPE = "has"; - - // Create the source vertex for the edge. - Map<String, Object> srcVertexProperties = new HashMap<String, Object>(); - srcVertexProperties.put("O/S", "Linux"); - srcVertexProperties.put("version", "6.5"); - srcVertexProperties.put("hostname", "kll0001"); - Vertex sourceVertex = champDao.addVertex("vserver", srcVertexProperties); - - // Create the target vertex for the edge. - Map<String, Object> dstVertexProperties = new HashMap<String, Object>(); - dstVertexProperties.put("O/S", "Linux"); - dstVertexProperties.put("version", "6.5"); - dstVertexProperties.put("hostname", "kll0002"); - Vertex destVertex = champDao.addVertex("VNF", dstVertexProperties); - - // Now, create the edge itself. - Map<String, Object> edgeProperties = new HashMap<String, Object>(); - edgeProperties.put("prop", "val"); - Edge createdEdge = champDao.addEdge("has", sourceVertex, destVertex, edgeProperties); - - // Retrieve the edge we just created by specifying its unique identifier. - Edge retrievedEdge = champDao.getEdge(createdEdge.getId().get(), "has"); - - // Validate that the contents of the object that we got back matches what we thought we - // created. - assertTrue("Unexpected type for Edge returned from get method. Expected: " + EDGE_TYPE - + " Actual: " + retrievedEdge.getType(), - retrievedEdge.getType().equals(EDGE_TYPE)); - assertTrue("Unexpected properties for Edge returned from get method. Expected: " + edgeProperties - + " Actual: " + retrievedEdge.getProperties(), - retrievedEdge.getProperties().equals(edgeProperties)); - } - - @Test - public void getEdgesTest() throws CrudException { - - final String EDGE_TYPE_HAS = "has"; - final String EDGE_TYPE_RUNS = "runs"; - - // Create some vertices and edges that we can query agains. - Vertex complex = champDao.addVertex("complex", MapBuilder.builder() - .withKeyValue("Province", "Ontario") - .withKeyValue("City", "Ottawa") - .withKeyValue("Street", "303 Terry Fox") - .build()); - - Vertex vserver = champDao.addVertex("vserver", MapBuilder.builder() - .withKeyValue("O/S", "Linux") - .withKeyValue("version", "6.5") - .withKeyValue("hostname", "kll0001") - .build()); - - Vertex vnf1 = champDao.addVertex("vserver", MapBuilder.builder() - .withKeyValue("Application", "OpenDaylight") - .build()); - - Vertex vnf2 = champDao.addVertex("vserver", MapBuilder.builder() - .withKeyValue("Application", "Cammunda") - .build()); - - Edge edge1 = champDao.addEdge(EDGE_TYPE_HAS, complex, vserver, - MapBuilder.builder() - .withKeyValue("usesResource", "false") - .withKeyValue("hasDelTarget", "false") - .build()); - - Edge edge2 = champDao.addEdge(EDGE_TYPE_RUNS, vserver, vnf1, - MapBuilder.builder() - .withKeyValue("usesResource", "false") - .withKeyValue("hasDelTarget", "true") - .build()); - - Edge edge3 = champDao.addEdge(EDGE_TYPE_RUNS, vserver, vnf2, - MapBuilder.builder() - .withKeyValue("usesResource", "false") - .withKeyValue("hasDelTarget", "false") - .build()); - - // Query for all HAS edges. - List<Edge> hasEdges = champDao.getEdges(EDGE_TYPE_HAS, new HashMap<String, Object>()); - - assertEquals("Unexpected number of edges of type 'has' found. Expected: 1 Actual: " + hasEdges.size(), - hasEdges.size(), 1); - assertTrue("Result of query for 'has' type edges does not contain the expected results", - containsEdge(edge1, hasEdges)); - - // Query for all RUNS edges. - List<Edge> runsEdges = champDao.getEdges(EDGE_TYPE_RUNS, new HashMap<String, Object>()); - - assertEquals("Unexpected number of edges of type 'runs' found. Expected: 2 Actual: " + runsEdges.size(), - runsEdges.size(), 2); - assertTrue("Result of query for 'runs' type edges does not contain the expected results", - containsEdge(edge2, runsEdges)); - assertTrue("Result of query for 'runs' type edges does not contain the expected results", - containsEdge(edge2, runsEdges)); - - // Query for all HAS edges with the property 'hasDelTarget' equal to 'true'. - List<Edge> runsEdgesWithDelTargetTrue = - champDao.getEdges(EDGE_TYPE_RUNS, MapBuilder.builder() - .withKeyValue("hasDelTarget", "true") - .build()); - - assertEquals("Unexpected number of edges of type 'has' with 'hasDelTarget=true' found. Expected: 1 Actual: " - + runsEdgesWithDelTargetTrue.size(), - runsEdgesWithDelTargetTrue.size(), 1); - assertTrue("Result of query for 'runs' type edges with delTarget set to TRUE does not contain the expected results", - containsEdge(edge2, runsEdgesWithDelTargetTrue)); - } - - @Test - @Ignore // For now - pending some expected fixes to the Champ library. - public void updateEdgeTest() throws CrudException { - - // Create the source vertex for the edge. - Vertex sourceVertex = champDao.addVertex("vserver", MapBuilder.builder() - .withKeyValue("O/S", "Linux") - .withKeyValue("version", "6.5") - .withKeyValue("hostname", "kll0001") - .build()); - - // Create the target vertex for the edge. - Vertex destVertex = champDao.addVertex("VNF", MapBuilder.builder() - .withKeyValue("O/S", "Linux") - .withKeyValue("version", "6.5") - .withKeyValue("hostname", "kll0002") - .build()); - - // Now, create the edge itself. - Edge createdEdge = champDao.addEdge("has", - sourceVertex, - destVertex, - MapBuilder.builder() - .withKeyValue("key1", "value1") - .withKeyValue("key2", "value2") - .withKeyValue("key3", "value3") - .build()); - - // Make sure the Edge returned from the create method includes an id that we can - // use to retrieve it. - assertTrue("No valid id returned for the created edge", createdEdge.getId().isPresent()); - - // Retrieve the properties map for our edge and make some changes. - Map<String, Object> properties = createdEdge.getProperties(); - properties.put("key4", "value4"); - properties.remove("key2"); - - // Now update the edge with the new properties map. - Edge updatedEdge = champDao.updateEdge(createdEdge); - - assertTrue("Edge property list returned from DAO update operation did not contain all expected properties - expected: " + - properties.keySet() + " actual: " + updatedEdge.getProperties().keySet(), - updatedEdge.getProperties().keySet().containsAll(properties.keySet())); - - // Validate that the values assigned to the properties in the updated Edge - // match the ones that we provided when we created it. - for (String propertyKey : properties.keySet()) { - - assertTrue("Unexpected value for property '" + propertyKey + "' - Expected: " + - properties.get(propertyKey) + " Actual: " + - updatedEdge.getProperties().get(propertyKey), - updatedEdge.getProperties().get(propertyKey).equals(properties.get(propertyKey))); - } - - // Validate that the property that we removed is NOT in the set of properties from our - // updated edge. - // *** We will leave this validation commented out for now, as the Champ library actually - // merges update properties instead of replacing them... - assertFalse("Property 'key2' should no longer be associated with updated edge", - updatedEdge.getProperties().containsKey("key2")); - } - - @Test - public void deleteEdgeTest() throws CrudException { - - boolean deletedEdgeNotFound = false; - - // Create the source vertex for the edge. - Vertex sourceVertex = champDao.addVertex("vserver", MapBuilder.builder() - .withKeyValue("O/S", "Linux") - .withKeyValue("version", "6.5") - .withKeyValue("hostname", "kll0001") - .build()); - - // Create the target vertex for the edge. - Vertex destVertex = champDao.addVertex("VNF", MapBuilder.builder() - .withKeyValue("O/S", "Linux") - .withKeyValue("version", "6.5") - .withKeyValue("hostname", "kll0002") - .build()); - - // Now, create the edge itself. - Edge createdEdge = champDao.addEdge("has", - sourceVertex, - destVertex, - MapBuilder.builder() - .withKeyValue("key1", "value1") - .withKeyValue("key2", "value2") - .withKeyValue("key3", "value3") - .build()); - - // Verify that we can retrieve the edge that we just created. - Edge retrievedEdge = champDao.getEdge(createdEdge.getId().get(), "has"); - - // Now, delete it. - champDao.deleteEdge(createdEdge.getId().get(), "has"); - - // Try retrieving it again. This time we should not find it. - try { - champDao.getEdge(createdEdge.getId().get(), "has"); - } catch (CrudException e) { - - assertTrue(e.getMessage().contains("No edge with id")); - deletedEdgeNotFound = true; - } - - assertTrue("Should not have been able to retrieve deleted edge.", deletedEdgeNotFound); - } - - private boolean containsEdge(Edge anEdge, List<Edge> edges) { - - for (Edge e : edges) { - if (e.getId().isPresent() && anEdge.getId().isPresent() && (e.getId().get().equals(anEdge.getId().get()))) { - return true; - } - - } - return false; - } - - public static class MapBuilder { - - private Map<String, Object> map; - - private MapBuilder() { - map = new HashMap<String, Object>(); - } - - public static MapBuilder builder() { - return new MapBuilder(); - } - - public MapBuilder withKeyValue(String key, Object value) { - map.put(key, value); - return this; - } - - public Map<String, Object> build() { - return map; - } - } -} diff --git a/titan-deps-pom.xml b/titan-deps-pom.xml deleted file mode 100644 index 869c9a1..0000000 --- a/titan-deps-pom.xml +++ /dev/null @@ -1,89 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>com.test</groupId> - <artifactId>mytitan</artifactId> - <version>0.0.1-SNAPSHOT</version> - <packaging>pom</packaging> - - <dependencies> - - - <dependency> - <groupId>org.openecomp.aai</groupId> - <artifactId>champ-titan</artifactId> - <version>1.1.1-AMDOCS-SNAPSHOT</version> - </dependency> - <dependency> - <groupId>com.thinkaurelius.titan</groupId> - <artifactId>titan-cassandra</artifactId> - <version>1.0.0</version> - <exclusions> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-groovy</artifactId> - </exclusion> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - <exclusion> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> - </exclusion> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-core</artifactId> - </exclusion> - </exclusions> - </dependency> - <dependency> - <groupId>com.thinkaurelius.titan</groupId> - <artifactId>titan-hbase</artifactId> - <version>1.0.0</version> - <exclusions> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-groovy</artifactId> - </exclusion> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - <exclusion> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> - </exclusion> - <exclusion> - <groupId>org.apache.tinkerpop</groupId> - <artifactId>gremlin-core</artifactId> - </exclusion> - </exclusions> - </dependency> - - </dependencies> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-dependency-plugin</artifactId> - <version>3.0.1</version> - <executions> - <execution> - <id>copy-dependencies</id> - <phase>package</phase> - <goals> - <goal>copy-dependencies</goal> - </goals> - <configuration> - <outputDirectory>${project.build.directory}/graph-deps/titan-deps</outputDirectory> - <overWriteReleases>false</overWriteReleases> - <overWriteSnapshots>false</overWriteSnapshots> - <overWriteIfNewer>true</overWriteIfNewer> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - -</project>
\ No newline at end of file |