From 2dd042556f9142fcd525c0277ea21ac3bd828e4f Mon Sep 17 00:00:00 2001 From: "Bansal, Nitin (nb121v)" Date: Thu, 16 Nov 2017 15:19:58 -0500 Subject: [PATCH] Fixing the formatting Fixing the formatting IssueID: AAI-481 Change-Id: I45c53cd24913707716f2dd34f9fc282786ce03b6 Signed-off-by: Bansal, Nitin (nb121v) --- src/main/java/org/openecomp/crud/dao/GraphDao.java | 97 +- .../org/openecomp/crud/dao/champ/ChampDao.java | 1440 ++++++++++---------- .../openecomp/crud/dao/champion/ChampionDao.java | 180 ++- src/main/java/org/openecomp/crud/entity/Edge.java | 12 +- .../java/org/openecomp/crud/entity/Vertex.java | 7 +- .../openecomp/crud/logging/CrudServiceMsgs.java | 41 +- .../org/openecomp/crud/logging/LoggingUtil.java | 20 +- .../openecomp/crud/parser/CrudResponseBuilder.java | 128 +- .../org/openecomp/crud/service/BulkPayload.java | 166 ++- .../crud/service/CrudGraphDataService.java | 328 +++-- .../openecomp/crud/service/CrudRestService.java | 469 +++---- .../org/openecomp/schema/OxmModelValidator.java | 108 +- .../openecomp/schema/RelationshipSchemaLoader.java | 99 +- 13 files changed, 1556 insertions(+), 1539 deletions(-) diff --git a/src/main/java/org/openecomp/crud/dao/GraphDao.java b/src/main/java/org/openecomp/crud/dao/GraphDao.java index 67c1ff3..7e8c043 100644 --- a/src/main/java/org/openecomp/crud/dao/GraphDao.java +++ b/src/main/java/org/openecomp/crud/dao/GraphDao.java @@ -38,40 +38,48 @@ public interface GraphDao { public Vertex getVertex(String id, String type) throws CrudException; /** - * Retrieve all of the edges which are incident to the vertex with the specified identifier. + * Retrieve all of the edges which are incident to the vertex with the + * specified identifier. * - * @param id - The unique identifier of the vertex to retrieve the edges for. + * @param id + * - The unique identifier of the vertex to retrieve the edges for. * @return - A collection of edges. * @throws CrudException */ public List getVertexEdges(String id) throws CrudException; /** - * Retrieve a collection of {@link Vertex} objects which match the supplied type label - * and filter properties. + * Retrieve a collection of {@link Vertex} objects which match the supplied + * type label and filter properties. * - * @param type - The vertex type that we want to retrieve. - * @param filter - The parameters to filter our results by. + * @param type + * - The vertex type that we want to retrieve. + * @param filter + * - The parameters to filter our results by. * @return - A collection of vertices. * @throws CrudException */ public List getVertices(String type, Map filter) throws CrudException; /** - * Retrieve an {@link Edge} from the graph database by specifying its unique identifier. + * Retrieve an {@link Edge} from the graph database by specifying its unique + * identifier. * - * @param id - The unique identifier for the Edge to be retrieved. + * @param id + * - The unique identifier for the Edge to be retrieved. * @return - The Edge corresponding to the specified identifier. * @throws CrudException */ public Edge getEdge(String id, String type) throws CrudException; /** - * Retrieve a collection of {@link Edge} objects with a given type and which match a set of - * supplied filter parameters. + * Retrieve a collection of {@link Edge} objects with a given type and which + * match a set of supplied filter parameters. * - * @param type - The type of edges that we are interested in. - * @param filter - The parameters that we want to filter our edges by. + * @param type + * - The type of edges that we are interested in. + * @param filter + * - The parameters that we want to filter our edges by. * @return - A collection of edges which match the supplied filter parameters. * @throws CrudException */ @@ -80,8 +88,10 @@ public interface GraphDao { /** * Insert a new {@link Vertex} into the graph data store. * - * @param type - The type label to assign to the vertex. - * @param properties - The properties to associated with this vertex. + * @param type + * - The type label to assign to the vertex. + * @param properties + * - The properties to associated with this vertex. * @return - The {@link Vertex} object that was created. * @throws CrudException */ @@ -90,20 +100,23 @@ public interface GraphDao { /** * Updates an existing {@link Vertex}. * - * @param id - The unique identifier of the vertex to be updated. - * @param properties - The properties to associate with the vertex. + * @param id + * - The unique identifier of the vertex to be updated. + * @param properties + * - The properties to associate with the vertex. * @return - The udpated vertex. * @throws CrudException */ - public Vertex updateVertex(String id, String type, Map properties) - throws CrudException; + public Vertex updateVertex(String id, String type, Map properties) throws CrudException; /** * Removes the specified vertex from the graph data base. * - *

NOTE: The vertex MUST contain NO incident edges before it can be deleted. + *

+ * NOTE: The vertex MUST contain NO incident edges before it can be deleted. * - * @param id - The unique identifier of the vertex to be deleted. + * @param id + * - The unique identifier of the vertex to be deleted. * @throws CrudException */ public void deleteVertex(String id, String type) throws CrudException; @@ -111,21 +124,26 @@ public interface GraphDao { /** * Adds an edge to the graph database. * - * @param type - The 'type' label to apply to the edge. - * @param source - The source vertex for this edge. - * @param target - The target vertex for this edge. - * @param properties - The properties map to associate with this edge. + * @param type + * - The 'type' label to apply to the edge. + * @param source + * - The source vertex for this edge. + * @param target + * - The target vertex for this edge. + * @param properties + * - The properties map to associate with this edge. * @return - The {@link Edge} object that was created. * @throws CrudException */ - public Edge addEdge(String type, Vertex source, Vertex target, Map properties) - throws CrudException; + public Edge addEdge(String type, Vertex source, Vertex target, Map properties) throws CrudException; /** * Updates an existing {@link Edge}. * - * @param id - The unique identifier of the edge to be updated. - * @param properties - The properties to associate with the edge. + * @param id + * - The unique identifier of the edge to be updated. + * @param properties + * - The properties to associate with the edge. * @return - The update edge. * @throws CrudException */ @@ -134,25 +152,32 @@ public interface GraphDao { /** * Remove the specified edge from the graph data base. * - * @param id - The unique identifier of the edge to be deleted. + * @param id + * - The unique identifier of the edge to be deleted. * @throws CrudException */ public void deleteEdge(String id, String type) throws CrudException; - - + public String openTransaction(); + public void commitTransaction(String id) throws CrudException; + public void rollbackTransaction(String id) throws CrudException; + public boolean transactionExists(String id) throws CrudException; - + public Vertex addVertex(String type, Map properties, String txId) throws CrudException; + public Edge addEdge(String type, Vertex source, Vertex target, Map properties, String txId) - throws CrudException; - public Vertex updateVertex(String id, String type, Map properties, String txId) - throws CrudException; - + throws CrudException; + + public Vertex updateVertex(String id, String type, Map properties, String txId) throws CrudException; + public Edge updateEdge(Edge edge, String txId) throws CrudException; + public void deleteVertex(String id, String type, String txId) throws CrudException; + public void deleteEdge(String id, String type, String txId) throws CrudException; + public Edge getEdge(String id, String type, String txId) throws CrudException; } diff --git a/src/main/java/org/openecomp/crud/dao/champ/ChampDao.java b/src/main/java/org/openecomp/crud/dao/champ/ChampDao.java index ed01038..93c3cdd 100644 --- a/src/main/java/org/openecomp/crud/dao/champ/ChampDao.java +++ b/src/main/java/org/openecomp/crud/dao/champ/ChampDao.java @@ -51,769 +51,833 @@ import org.openecomp.crud.exception.CrudException; import org.openecomp.crud.logging.CrudServiceMsgs; /** - * This is the integration layer between the CRUD API service and the low level Champ library for graph database - * interaction. + * 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"; + 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"; - public static final String CONFIG_EVENT_STREAM_PUBLISHER = "event.stream.publisher"; - public static final String CONFIG_EVENT_STREAM_NUM_PUBLISHERS = "event.stream.num-publishers"; + public static final String CONFIG_EVENT_STREAM_PUBLISHER = "event.stream.publisher"; + public static final String CONFIG_EVENT_STREAM_NUM_PUBLISHERS = "event.stream.num-publishers"; - private static Map transactions = new ConcurrentHashMap(); - public static final String DEFAULT_GRAPH_NAME = "default_graph"; + private static Map transactions = new ConcurrentHashMap(); + public static final String DEFAULT_GRAPH_NAME = "default_graph"; - private enum GraphType { - IN_MEMORY, TITAN, DSE - } + private enum GraphType { + IN_MEMORY, TITAN, DSE + } - /** - * Instance of the API used for interacting with the Champ library. - */ - private ChampGraph champApi = null; + /** + * Instance of the API used for interacting with the Champ library. + */ + private ChampGraph champApi = null; - private Logger logger = LoggerFactory.getInstance().getLogger(ChampDao.class.getName()); + private Logger logger = LoggerFactory.getInstance().getLogger(ChampDao.class.getName()); - /** - * Creates a new instance of the ChampDao. - * - * @param champGraph - * - Concrete implementation of the graph dao layer - */ - public ChampDao(ChampGraph champGraph) { - this.champApi = champGraph; - } + /** + * Creates a new instance of the ChampDao. + * + * @param champGraph + * - Concrete implementation of the graph dao layer + */ + public ChampDao(ChampGraph champGraph) { + this.champApi = champGraph; + } - @Override - public Vertex getVertex(String id) throws CrudException { + @Override + public Vertex getVertex(String id) throws CrudException { - try { + try { - if (logger.isDebugEnabled()) { - logger.debug("getVertex with id: " + id); - } + if (logger.isDebugEnabled()) { + logger.debug("getVertex with id: " + id); + } - long idAsLong = Long.parseLong(id); + long idAsLong = Long.parseLong(id); - Optional retrievedVertex = champApi.retrieveObject(idAsLong); + Optional retrievedVertex = champApi.retrieveObject(idAsLong); - String nodeType = org.openecomp.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 { + String nodeType = org.openecomp.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); - } + // 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) { + } catch (ChampUnmarshallingException | ChampTransactionException e) { - // Something went wrong - throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } + // Something went wrong - throw an exception. + throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + } - @Override - public Vertex getVertex(String id, String type) throws CrudException { + @Override + public Vertex getVertex(String id, String type) throws CrudException { - try { + try { - if (logger.isDebugEnabled()) { - logger.debug("getVertex with id: " + id); - } + if (logger.isDebugEnabled()) { + logger.debug("getVertex with id: " + id); + } - long idAsLong = Long.parseLong(id); + long idAsLong = Long.parseLong(id); - // Request the vertex from the graph db. - Optional retrievedVertex = champApi.retrieveObject(idAsLong); + // Request the vertex from the graph db. + Optional retrievedVertex = champApi.retrieveObject(idAsLong); - // Did we find it? - if (retrievedVertex.isPresent() - && retrievedVertex.get().getProperties().get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) != null - && retrievedVertex.get().getProperties().get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString() - .equalsIgnoreCase(type)) { + // Did we find it? + if (retrievedVertex.isPresent() + && retrievedVertex.get().getProperties() + .get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) != null + && retrievedVertex.get().getProperties() + .get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString() + .equalsIgnoreCase(type)) { - // Yup, convert it to a Vector object and return it. - return vertexFromChampObject(retrievedVertex.get(), type); + // Yup, convert it to a Vector object and return it. + return vertexFromChampObject(retrievedVertex.get(), type); - } else { + } 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); - } + // 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) { + } catch (ChampUnmarshallingException | ChampTransactionException e) { - // Something went wrong - throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } + // Something went wrong - throw an exception. + throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + } - @Override - public List getVertexEdges(String id) throws CrudException { + @Override + public List getVertexEdges(String id) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("get Edges incident to vertex with id: " + id + " from graph"); - } + 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??? + try { + long idAsLong = Long.parseLong(id); // GDF - what to do about id??? - // Request the vertex from the graph db. - Optional retrievedVertex = champApi.retrieveObject(idAsLong); + // Request the vertex from the graph db. + Optional retrievedVertex = champApi.retrieveObject(idAsLong); - // Did we find it? - if (retrievedVertex.isPresent()) { + // Did we find it? + if (retrievedVertex.isPresent()) { - // Query the Champ library for the edges which are incident to the specified - // vertex. - Stream relationships = champApi.retrieveRelationships(retrievedVertex.get()); + // Query the Champ library for the edges which are incident to the + // specified + // vertex. + Stream relationships = champApi.retrieveRelationships(retrievedVertex.get()); - // Build an edge list from the result stream. - List edges = new ArrayList(); - relationships.forEach(r -> edges.add(edgeFromChampRelationship(r))); + // Build an edge list from the result stream. + List edges = new ArrayList(); + relationships.forEach(r -> edges.add(edgeFromChampRelationship(r))); - return edges; + return edges; - } else { + } else { - // 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); - } + // 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) { + } catch (ChampUnmarshallingException e) { - // Something went wrong, so throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + // Something went wrong, so throw an exception. + throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } catch (ChampObjectNotExistsException e) { + } catch (ChampObjectNotExistsException e) { - // 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 (ChampTransactionException e) { - throw new CrudException("Transaction error occured", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } + // 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 (ChampTransactionException e) { + throw new CrudException("Transaction error occured", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + } - @Override - public Vertex addVertex(String type, Map properties) throws CrudException { + @Override + public Vertex addVertex(String type, Map properties) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("Add/update vertex: {label: " + type + " properties:" + propertiesMapToString(properties)); - } + 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.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); + // Add the aai_node_type so that AAI can read the data created by gizmo + properties.put(org.openecomp.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); + // Create an object to represent our vertex in the format expected by the + // Champ library. + ChampObject objectToCreate = buildChampObject(type, properties); - try { + 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); + // 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) { + } 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); - } - } + // 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 properties) throws CrudException { + @Override + public Vertex updateVertex(String id, String type, Map 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.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); + 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.openecomp.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); + 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); - } + } 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 getVertices(String type, Map filter) throws CrudException { + @Override + public List getVertices(String type, Map filter) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("Retrieve vertices with type label: " + type + " which map query parameters: " + propertiesMapToString(filter)); - } + if (logger.isDebugEnabled()) { + logger.debug("Retrieve vertices with type label: " + type + " which map query parameters: " + + propertiesMapToString(filter)); + } - filter.put(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); + filter.put(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - Stream retrievedVertices; - try { - retrievedVertices = champApi.queryObjects(filter); + Stream retrievedVertices; + try { + retrievedVertices = champApi.queryObjects(filter); - } catch (ChampTransactionException e) { - throw new CrudException("Transaction error occured", 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); + } - List vertices = retrievedVertices.map(v -> vertexFromChampObject(v, type)).collect(Collectors.toList()); + List vertices = retrievedVertices.map(v -> vertexFromChampObject(v, type)).collect(Collectors.toList()); - if (logger.isDebugEnabled()) { - logger.debug("Resulting vertex list: " + retrievedVertices); - } + if (logger.isDebugEnabled()) { + logger.debug("Resulting vertex list: " + retrievedVertices); + } - // ...and return it to the caller. - return vertices; - } + // ...and return it to the caller. + return vertices; + } - 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 - } + 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 + } - return key; - } + return key; + } + + @Override + public Edge getEdge(String id, String type) throws CrudException { + + if (logger.isDebugEnabled()) { + logger.debug("Get edge with id: " + id); + } + + try { + + // Request the edge from the graph db. + Optional 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 { - @Override - public Edge getEdge(String id, String type) throws CrudException { + // 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", + 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); + } + } + + @Override + public Edge addEdge(String type, Vertex source, Vertex target, Map properties) throws CrudException { + + // For now, assume source and target are straight ids... + try { + + Optional 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 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); + } - if (logger.isDebugEnabled()) { - logger.debug("Get edge with id: " + id); - } + // 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())); - try { + } catch (ChampMarshallingException | ChampObjectNotExistsException | ChampSchemaViolationException + | ChampRelationshipNotExistsException | ChampUnmarshallingException | NumberFormatException + | ChampTransactionException e) { - // Request the edge from the graph db. - Optional relationship = champApi.retrieveRelationship(getRelKey(id)); + throw new CrudException("Error creating edge: " + e.getMessage(), + javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + } - // Did we find it? - if (relationship.isPresent() && relationship.get().getType().equals(type)) { + @Override + public List getEdges(String type, Map filter) throws CrudException { - // Yup - return the result. - return edgeFromChampRelationship(relationship.get()); + filter.put(ChampRelationship.ReservedPropertyKeys.CHAMP_RELATIONSHIP_TYPE.toString(), type); - } else { + Stream retrievedRelationships; + try { + retrievedRelationships = champApi.queryRelationships(filter); - // 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", 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); + } + + // Process the result stream from the Champ library into an Edge list, + // keeping only + // edges of the specified type. + List edges = retrievedRelationships.map(r -> edgeFromChampRelationship(r)).collect(Collectors.toList()); + + return edges; + } + + @Override + public Edge updateEdge(Edge edge) throws CrudException { + + if (logger.isDebugEnabled()) { + logger.debug( + "Update edge with id: " + edge.getId() + " with properties: " + propertiesMapToString(edge.getProperties())); + } - } catch (ChampUnmarshallingException | ChampTransactionException e) { + 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); + } + } + + @Override + public void deleteVertex(String id, String type) throws CrudException { + + try { + + // First, retrieve the vertex that we intend to delete. + Optional 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 relationships = champApi.retrieveRelationships(retrievedVertex.get()); + + 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); + } + + // Finally, we can attempt to delete our vertex. + champApi.deleteObject(Long.parseLong(id)); + + } catch (NumberFormatException | ChampUnmarshallingException | ChampObjectNotExistsException + | ChampTransactionException e) { + + throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + } + + @Override + public void deleteEdge(String id, String type) throws CrudException { + + try { + + // First, retrieve the edge that we want to delete. + Optional 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) { + + throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + } + + /** + * 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 properties) { + + StringBuilder sb = new StringBuilder(); + sb.append("{"); + + for (String key : properties.keySet()) { + sb.append("(").append(key).append(" -> ").append(properties.get(key)).append(") "); + } + + sb.append("}"); + + return sb.toString(); + } + + /** + * 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 properties) { + + ObjectBuildOrPropertiesStep objectInProgress = ChampObject.create().ofType(type).withoutKey(); + + for (String key : properties.keySet()) { + objectInProgress.withProperty(key, properties.get(key)); + } + return objectInProgress.build(); + } + + /** + * 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 properties) { + + ObjectBuildOrPropertiesStep objectInProgress = ChampObject.create().ofType(type).withKey(Long.parseLong(id)); + + for (String key : properties.keySet()) { + objectInProgress.withProperty(key, properties.get(key)); + } + 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)); + } + + // ...and return it. + return vertexBuilder.build(); + } + + /** + * 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.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) == null + ? relationship.getSource().getType() + : relationship.getSource().getProperties() + .get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString())); + edgeBuilder.target(vertexFromChampObject(relationship.getTarget(), + relationship.getTarget().getProperties() + .get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) == null + ? relationship.getTarget().getType() + : relationship.getTarget().getProperties() + .get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString())); + + for (String key : relationship.getProperties().keySet()) { + edgeBuilder.property(key, relationship.getProperties().get(key).toString()); + } + + 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); + + champApi.shutdown(); + } + } + + @Override + public String openTransaction() { + + ChampTransaction transaction = champApi.openTransaction(); + + 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); + } + return transaction.id(); + } + + @Override + public void commitTransaction(String id) throws CrudException { + + 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); + } + transactions.remove(id); + } + + @Override + public void rollbackTransaction(String id) throws CrudException { + + 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); + } + transactions.remove(id); + } + + private ChampTransaction getTransaction(String id) throws CrudException { + + 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); + } + } + + @Override + public Vertex addVertex(String type, Map properties, String txId) 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.openecomp.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, Optional.of(getTransaction(txId))), 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 Edge addEdge(String type, Vertex source, Vertex target, Map properties, String txId) + throws CrudException { + // For now, assume source and target are straight ids... + try { + + Optional 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); + } + + Optional 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); + } + + // 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)))); + + } catch (ChampMarshallingException | ChampObjectNotExistsException | ChampSchemaViolationException + | ChampTransactionException | ChampRelationshipNotExistsException | ChampUnmarshallingException e) { + + throw new CrudException("Error creating edge: " + e.getMessage(), + javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + + } + + @Override + public Vertex updateVertex(String id, String type, Map properties, String txId) 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.openecomp.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); + } + } + + @Override + public boolean transactionExists(String id) throws CrudException { + return transactions.containsKey(id); + } + + @Override + public void deleteVertex(String id, String type, String txId) throws CrudException { + try { + + // First, retrieve the vertex that we intend to delete. + Optional 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 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); + } + + // 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); + } + + } + + @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())); + } + + 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); + } + } + + @Override + public void deleteEdge(String id, String type, String txId) throws CrudException { + try { + + // First, retrieve the edge that we want to delete. + Optional 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) { + + throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); + } + + } + + @Override + public Edge getEdge(String id, String type, String txId) throws CrudException { + if (logger.isDebugEnabled()) { + logger.debug("Get edge with id: " + id); + } + + try { + + // Request the edge from the graph db. + Optional relationship = champApi.retrieveRelationship(getRelKey(id), + Optional.of(getTransaction(txId))); + + // Did we find it? + if (relationship.isPresent() && relationship.get().getType().equals(type)) { + + // Yup - return the result. + return edgeFromChampRelationship(relationship.get()); + + } else { + + // 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", + javax.ws.rs.core.Response.Status.NOT_FOUND); + } - // Something went wrong, so throw an exception. - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } - - @Override - public Edge addEdge(String type, Vertex source, Vertex target, Map properties) throws CrudException { - - // For now, assume source and target are straight ids... - try { - - Optional 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 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())); - - } catch (ChampMarshallingException | ChampObjectNotExistsException | ChampSchemaViolationException | ChampRelationshipNotExistsException - | ChampUnmarshallingException | NumberFormatException | ChampTransactionException e) { - - throw new CrudException("Error creating edge: " + e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } - - @Override - public List getEdges(String type, Map filter) throws CrudException { - - filter.put(ChampRelationship.ReservedPropertyKeys.CHAMP_RELATIONSHIP_TYPE.toString(), type); - - Stream 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 edges = retrievedRelationships.map(r -> edgeFromChampRelationship(r)).collect(Collectors.toList()); - - return edges; - } - - @Override - public Edge updateEdge(Edge edge) throws CrudException { - - if (logger.isDebugEnabled()) { - logger.debug("Update edge with id: " + edge.getId() + " with properties: " + propertiesMapToString(edge.getProperties())); - } - - 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); - } - } - - @Override - public void deleteVertex(String id, String type) throws CrudException { - - try { - - // First, retrieve the vertex that we intend to delete. - Optional 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 relationships = champApi.retrieveRelationships(retrievedVertex.get()); - - 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); - } - - // Finally, we can attempt to delete our vertex. - champApi.deleteObject(Long.parseLong(id)); - - } catch (NumberFormatException | ChampUnmarshallingException | ChampObjectNotExistsException | ChampTransactionException e) { - - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } - - @Override - public void deleteEdge(String id, String type) throws CrudException { - - try { - - // First, retrieve the edge that we want to delete. - Optional 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) { - - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - } - - /** - * 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 properties) { - - StringBuilder sb = new StringBuilder(); - sb.append("{"); - - for (String key : properties.keySet()) { - sb.append("(").append(key).append(" -> ").append(properties.get(key)).append(") "); - } - - sb.append("}"); - - return sb.toString(); - } - - /** - * 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 properties) { - - ObjectBuildOrPropertiesStep objectInProgress = ChampObject.create().ofType(type).withoutKey(); - - for (String key : properties.keySet()) { - objectInProgress.withProperty(key, properties.get(key)); - } - return objectInProgress.build(); - } - - /** - * 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 properties) { - - ObjectBuildOrPropertiesStep objectInProgress = ChampObject.create().ofType(type).withKey(Long.parseLong(id)); - - for (String key : properties.keySet()) { - objectInProgress.withProperty(key, properties.get(key)); - } - 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)); - } - - // ...and return it. - return vertexBuilder.build(); - } - - /** - * 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.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) == null - ? relationship.getSource().getType() - : relationship.getSource().getProperties().get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString())); - edgeBuilder.target(vertexFromChampObject(relationship.getTarget(), - relationship.getTarget().getProperties().get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()) == null - ? relationship.getTarget().getType() - : relationship.getTarget().getProperties().get(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName()).toString())); - - for (String key : relationship.getProperties().keySet()) { - edgeBuilder.property(key, relationship.getProperties().get(key).toString()); - } - - 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); - - champApi.shutdown(); - } - } - - @Override - public String openTransaction() { - - ChampTransaction transaction = champApi.openTransaction(); - - 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); - } - return transaction.id(); - } - - @Override - public void commitTransaction(String id) throws CrudException { - - 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); - } - transactions.remove(id); - } - - @Override - public void rollbackTransaction(String id) throws CrudException { - - 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); - } - transactions.remove(id); - } - - private ChampTransaction getTransaction(String id) throws CrudException { - - 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); - } - } - - @Override - public Vertex addVertex(String type, Map properties, String txId) 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.openecomp.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, Optional.of(getTransaction(txId))), 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 Edge addEdge(String type, Vertex source, Vertex target, Map properties, String txId) throws CrudException { - // For now, assume source and target are straight ids... - try { - - Optional 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); - } - - Optional 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); - } - - // 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)))); - - } catch (ChampMarshallingException | ChampObjectNotExistsException | ChampSchemaViolationException | ChampTransactionException - | ChampRelationshipNotExistsException | ChampUnmarshallingException e) { - - throw new CrudException("Error creating edge: " + e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - - } - - @Override - public Vertex updateVertex(String id, String type, Map properties, String txId) 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.openecomp.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); - } - } - - @Override - public boolean transactionExists(String id) throws CrudException { - return transactions.containsKey(id); - } - - @Override - public void deleteVertex(String id, String type, String txId) throws CrudException { - try { - - // First, retrieve the vertex that we intend to delete. - Optional 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 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); - } - - // 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); - } - - } - - @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())); - } - - 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); - } - } - - @Override - public void deleteEdge(String id, String type, String txId) throws CrudException { - try { - - // First, retrieve the edge that we want to delete. - Optional 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) { - - throw new CrudException(e.getMessage(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR); - } - - } - - @Override - public Edge getEdge(String id, String type, String txId) throws CrudException { - if (logger.isDebugEnabled()) { - logger.debug("Get edge with id: " + id); - } - - try { - - // Request the edge from the graph db. - Optional relationship = champApi.retrieveRelationship(getRelKey(id), Optional.of(getTransaction(txId))); - - // Did we find it? - if (relationship.isPresent() && relationship.get().getType().equals(type)) { - - // Yup - return the result. - return edgeFromChampRelationship(relationship.get()); - - } else { - - // 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", 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); - } - } + } 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); + } + } } diff --git a/src/main/java/org/openecomp/crud/dao/champion/ChampionDao.java b/src/main/java/org/openecomp/crud/dao/champion/ChampionDao.java index e1bda7a..48fa6cb 100644 --- a/src/main/java/org/openecomp/crud/dao/champion/ChampionDao.java +++ b/src/main/java/org/openecomp/crud/dao/champion/ChampionDao.java @@ -64,19 +64,17 @@ public class ChampionDao implements GraphDao { private Logger logger = LoggerFactory.getInstance().getLogger(ChampionDao.class.getName()); - // We use a custom vertex serializer for Champion because it expects "key" instead of "id" + // 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(); + .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) + client = new RestClient().authenticationMode(RestAuthenticationMode.SSL_CERT).validateServerHostname(false) + .validateServerCertChain(false).clientCertFile(CrudServiceConstants.CRD_CHAMPION_AUTH_FILE) .clientCertPassword(Password.deobfuscate(certPassword)); baseUrl = championUrl; @@ -99,8 +97,10 @@ public class ChampionDao implements GraphDao { 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); + // 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); } } @@ -117,13 +117,17 @@ public class ChampionDao implements GraphDao { 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); + // 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); + // 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); } } @@ -137,10 +141,13 @@ public class ChampionDao implements GraphDao { OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); if (getResult.getResultCode() == 200) { - return championGson.fromJson(getResult.getResult(), new TypeToken>(){}.getType()); + return championGson.fromJson(getResult.getResult(), new TypeToken>() { + }.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); + // 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); } } @@ -148,8 +155,8 @@ public class ChampionDao implements GraphDao { public List getVertices(String type, Map filter) throws CrudException { filter.put(org.openecomp.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type); - String url = baseUrl + "objects/filter" + "?" + - URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); + String url = baseUrl + "objects/filter" + "?" + + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); Map> headers = new HashMap<>(); headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); @@ -158,10 +165,13 @@ public class ChampionDao implements GraphDao { OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); if (getResult.getResultCode() == 200) { - return championGson.fromJson(getResult.getResult(), new TypeToken>(){}.getType()); + return championGson.fromJson(getResult.getResult(), new TypeToken>() { + }.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); + // 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); } } @@ -178,20 +188,23 @@ public class ChampionDao implements GraphDao { 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); + // 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. + // 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 getEdges(String type, Map filter) throws CrudException { - String url = baseUrl + "relationships/filter" + "?" + - URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); + String url = baseUrl + "relationships/filter" + "?" + + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset()); Map> headers = new HashMap<>(); headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); @@ -200,9 +213,11 @@ public class ChampionDao implements GraphDao { OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE); if (getResult.getResultCode() == 200) { - return championGson.fromJson(getResult.getResult(), new TypeToken>(){}.getType()); + return championGson.fromJson(getResult.getResult(), new TypeToken>() { + }.getType()); } else { - // We didn't find a vertex with the supplied id, so just throw an exception. + // 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); } } @@ -222,13 +237,14 @@ public class ChampionDao implements GraphDao { properties.forEach(insertVertexBuilder::property); Vertex insertVertex = insertVertexBuilder.build(); - OperationResult getResult = client.post(url, insertVertex.toJson(), headers, - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + 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. + // 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())); } } @@ -250,13 +266,14 @@ public class ChampionDao implements GraphDao { Vertex insertVertex = insertVertexBuilder.build(); String payload = insertVertex.toJson(championGson); - OperationResult getResult = client.put(url, payload, headers, - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + 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. + // 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())); } } @@ -271,7 +288,8 @@ public class ChampionDao implements GraphDao { 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. + // 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())); } } @@ -292,21 +310,21 @@ public class ChampionDao implements GraphDao { Edge insertEdge = insertEdgeBuilder.build(); String edgeJson = insertEdge.toJson(championGson); - OperationResult getResult = client.post(url, edgeJson, headers, - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + 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. + // 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()) - { + if (!edge.getId().isPresent()) { throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST); } String url = baseUrl + "relationships/" + edge.getId().get(); @@ -315,13 +333,14 @@ public class ChampionDao implements GraphDao { 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); + 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. + // 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())); } } @@ -336,7 +355,8 @@ public class ChampionDao implements GraphDao { 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. + // 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); } } @@ -364,10 +384,12 @@ public class ChampionDao implements GraphDao { 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); + 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())); + throw new CrudException("Unable to commit transaction", + Response.Status.fromStatusCode(getResult.getResultCode())); } } @@ -378,10 +400,12 @@ public class ChampionDao implements GraphDao { 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); + 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())); + throw new CrudException("Unable to rollback transaction", + Response.Status.fromStatusCode(getResult.getResultCode())); } } @@ -412,19 +436,21 @@ public class ChampionDao implements GraphDao { properties.forEach(insertVertexBuilder::property); Vertex insertVertex = insertVertexBuilder.build(); - OperationResult getResult = client.post(url, insertVertex.toJson(), headers, - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + 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. + // 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 properties, String txId) throws CrudException { + public Edge addEdge(String type, Vertex source, Vertex target, Map properties, String txId) + throws CrudException { String url = baseUrl + "relationships?transactionId=" + txId; Map> headers = new HashMap<>(); headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo")); @@ -444,7 +470,8 @@ public class ChampionDao implements GraphDao { 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. + // 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())); } } @@ -466,13 +493,14 @@ public class ChampionDao implements GraphDao { Vertex insertVertex = insertVertexBuilder.build(); String payload = insertVertex.toJson(championGson); - OperationResult getResult = client.put(url, payload, headers, - MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE); + 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. + // 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())); } } @@ -487,15 +515,15 @@ public class ChampionDao implements GraphDao { 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. + // 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()) - { + 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; @@ -503,14 +531,16 @@ public class ChampionDao implements GraphDao { 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); + 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())); + // 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())); } } @@ -524,7 +554,8 @@ public class ChampionDao implements GraphDao { 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. + // 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); } } @@ -542,12 +573,15 @@ public class ChampionDao implements GraphDao { 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); + // 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. + // 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); } } @@ -564,13 +598,17 @@ public class ChampionDao implements GraphDao { 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); + // 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); + // 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); } } diff --git a/src/main/java/org/openecomp/crud/entity/Edge.java b/src/main/java/org/openecomp/crud/entity/Edge.java index ceae494..4d2de24 100644 --- a/src/main/java/org/openecomp/crud/entity/Edge.java +++ b/src/main/java/org/openecomp/crud/entity/Edge.java @@ -34,18 +34,16 @@ import java.util.Map; import java.util.Optional; public class Edge { - private static final Gson gson = new GsonBuilder() - .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory()) + private static final Gson gson = new GsonBuilder().registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory()) .create(); - @SerializedName(value="id", alternate={"key"}) + @SerializedName(value = "id", alternate = { "key" }) private final Optional id; private final String type; private final Map properties; private final Vertex source; private final Vertex target; - private Edge(Builder builder) { this.id = builder.id; this.type = builder.type; @@ -101,11 +99,10 @@ public class Edge { } } - @Override public String toString() { - return "Edge [id=" + id + ", type=" + type + ", properties=" + properties - + ", source=" + source + ", target=" + target + "]"; + return "Edge [id=" + id + ", type=" + type + ", properties=" + properties + ", source=" + source + ", target=" + + target + "]"; } public String toJson() { @@ -140,5 +137,4 @@ public class Edge { return target; } - } diff --git a/src/main/java/org/openecomp/crud/entity/Vertex.java b/src/main/java/org/openecomp/crud/entity/Vertex.java index d2f2b08..12c274f 100644 --- a/src/main/java/org/openecomp/crud/entity/Vertex.java +++ b/src/main/java/org/openecomp/crud/entity/Vertex.java @@ -34,16 +34,15 @@ import java.util.Map; import java.util.Optional; public class Vertex { - private static final Gson gson = new GsonBuilder() - .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory()).create(); + private static final Gson gson = new GsonBuilder().registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory()) + .create(); - @SerializedName(value="id", alternate={"key"}) + @SerializedName(value = "id", alternate = { "key" }) private final Optional id; private final String type; private final Map properties; - private Vertex(Builder builder) { this.id = builder.id; this.type = builder.type; diff --git a/src/main/java/org/openecomp/crud/logging/CrudServiceMsgs.java b/src/main/java/org/openecomp/crud/logging/CrudServiceMsgs.java index 98cc4fa..4298709 100644 --- a/src/main/java/org/openecomp/crud/logging/CrudServiceMsgs.java +++ b/src/main/java/org/openecomp/crud/logging/CrudServiceMsgs.java @@ -30,63 +30,56 @@ import org.openecomp.cl.eelf.LogMessageEnum; public enum CrudServiceMsgs implements LogMessageEnum { /** - * Received request {0} {1} from {2}. Sending response: {3} + * Received request {0} {1} from {2}. Sending response: {3} * - *

Arguments: - * {0} = operation - * {1} = target URL - * {2} = source - * {3} = response code + *

+ * Arguments: {0} = operation {1} = target URL {2} = source {3} = response + * code */ PROCESS_REST_REQUEST, - INVALID_OXM_FILE, - INVALID_OXM_DIR, - OXM_FILE_CHANGED, - TRANSACTION, + INVALID_OXM_FILE, INVALID_OXM_DIR, OXM_FILE_CHANGED, TRANSACTION, /** * Successfully loaded schema: {0} * - *

Arguments: - * {0} = oxm filename + *

+ * Arguments: {0} = oxm filename */ LOADED_OXM_FILE, /** * Unable to load OXM schema: {0} * - *

Arguments: - * {0} = error + *

+ * Arguments: {0} = error */ OXM_LOAD_ERROR, /** * Stopping ChampDAO... * - *

Arguments: + *

+ * Arguments: */ STOPPING_CHAMP_DAO, /** - * Failure instantiating CRUD Rest Service. Cause: {0} + * Failure instantiating CRUD Rest Service. Cause: {0} * - *

Arguments: - * {0} - Failure cause. + *

+ * Arguments: {0} - Failure cause. */ INSTANTIATE_AUTH_ERR, /** - * Arguments: - * {0} Opertaion - * {1} URI - * {2} = Exception + * Arguments: {0} Opertaion {1} URI {2} = Exception */ EXCEPTION_DURING_METHOD_CALL; - /** - * Static initializer to ensure the resource bundles for this class are loaded... + * Static initializer to ensure the resource bundles for this class are + * loaded... */ static { EELFResourceManager.loadMessageBundle("logging/CrudServiceMsgs"); diff --git a/src/main/java/org/openecomp/crud/logging/LoggingUtil.java b/src/main/java/org/openecomp/crud/logging/LoggingUtil.java index 2ef2772..b66a309 100644 --- a/src/main/java/org/openecomp/crud/logging/LoggingUtil.java +++ b/src/main/java/org/openecomp/crud/logging/LoggingUtil.java @@ -34,7 +34,6 @@ import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; - public class LoggingUtil { /** * Initializes mdc context. @@ -61,28 +60,23 @@ public class LoggingUtil { /** * Logs the rest request. */ - public static void logRestRequest(Logger logger, Logger auditLogger, - HttpServletRequest req, Response response) { + public static void logRestRequest(Logger logger, Logger auditLogger, HttpServletRequest req, Response response) { String respStatusString = ""; if (Response.Status.fromStatusCode(response.getStatus()) != null) { respStatusString = Response.Status.fromStatusCode(response.getStatus()).toString(); } // Generate error log - logger.info(CrudServiceMsgs.PROCESS_REST_REQUEST, req.getMethod(), - req.getRequestURL().toString(), req.getRemoteHost(), - Integer.toString(response.getStatus())); + logger.info(CrudServiceMsgs.PROCESS_REST_REQUEST, req.getMethod(), req.getRequestURL().toString(), + req.getRemoteHost(), Integer.toString(response.getStatus())); // Generate audit log. auditLogger.info(CrudServiceMsgs.PROCESS_REST_REQUEST, - new LogFields() - .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus()) + new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus()) .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, respStatusString), - (req != null) ? req.getMethod() : "Unknown", - (req != null) ? req.getRequestURL().toString() : "Unknown", - (req != null) ? req.getRemoteHost() : "Unknown", - Integer.toString(response.getStatus()) + " payload: " + (response.getEntity() == null ? "" - : response.getEntity().toString())); + (req != null) ? req.getMethod() : "Unknown", (req != null) ? req.getRequestURL().toString() : "Unknown", + (req != null) ? req.getRemoteHost() : "Unknown", Integer.toString(response.getStatus()) + " payload: " + + (response.getEntity() == null ? "" : response.getEntity().toString())); MDC.clear(); } } diff --git a/src/main/java/org/openecomp/crud/parser/CrudResponseBuilder.java b/src/main/java/org/openecomp/crud/parser/CrudResponseBuilder.java index 308583d..b527fa1 100644 --- a/src/main/java/org/openecomp/crud/parser/CrudResponseBuilder.java +++ b/src/main/java/org/openecomp/crud/parser/CrudResponseBuilder.java @@ -52,45 +52,44 @@ public class CrudResponseBuilder { public static final String SOURCE = "source"; public static final String TARGET = "target"; public static final String URL_BASE = "services/inventory/"; - - public static String buildUpsertBulkResponse(HashMap vertices, HashMap edges , String version,BulkPayload incomingPayload) - throws CrudException { - - for (JsonElement e : incomingPayload.getObjects()) { - List> entries = new ArrayList>(e.getAsJsonObject().entrySet()); - - Map.Entry item = entries.get(1); - - Vertex responseVertex = vertices.get(item.getKey()); - if(responseVertex != null){ - JsonObject v = gson.fromJson(buildUpsertVertexResponse(responseVertex,version), JsonObject.class); - item.setValue(v); - }else{ - item.setValue(gson.fromJson("{}", JsonObject.class)); - } - - } - for (JsonElement e : incomingPayload.getRelationships()) { - List> entries = new ArrayList>(e.getAsJsonObject().entrySet()); - - Map.Entry item = entries.get(1); - - Edge responseEdge = edges.get(item.getKey()); - if(responseEdge != null){ - JsonObject v = gson.fromJson(buildUpsertEdgeResponse(responseEdge,version), JsonObject.class); - item.setValue(v); - }else{ - item.setValue(gson.fromJson("{}", JsonObject.class)); - } - - } - return incomingPayload.toJson(); - } - - - - public static String buildUpsertVertexResponse(Vertex vertex, String version) - throws CrudException { + + public static String buildUpsertBulkResponse(HashMap vertices, HashMap edges, + String version, BulkPayload incomingPayload) throws CrudException { + + for (JsonElement e : incomingPayload.getObjects()) { + List> entries = new ArrayList>( + e.getAsJsonObject().entrySet()); + + Map.Entry item = entries.get(1); + + Vertex responseVertex = vertices.get(item.getKey()); + if (responseVertex != null) { + JsonObject v = gson.fromJson(buildUpsertVertexResponse(responseVertex, version), JsonObject.class); + item.setValue(v); + } else { + item.setValue(gson.fromJson("{}", JsonObject.class)); + } + + } + for (JsonElement e : incomingPayload.getRelationships()) { + List> entries = new ArrayList>( + e.getAsJsonObject().entrySet()); + + Map.Entry item = entries.get(1); + + Edge responseEdge = edges.get(item.getKey()); + if (responseEdge != null) { + JsonObject v = gson.fromJson(buildUpsertEdgeResponse(responseEdge, version), JsonObject.class); + item.setValue(v); + } else { + item.setValue(gson.fromJson("{}", JsonObject.class)); + } + + } + return incomingPayload.toJson(); + } + + public static String buildUpsertVertexResponse(Vertex vertex, String version) throws CrudException { VertexPayload payload = new VertexPayload(); payload.setId(vertex.getId().get()); payload.setType(vertex.getType()); @@ -107,8 +106,7 @@ public class CrudResponseBuilder { return buildGetEdgeResponse(edge, version); } - public static String buildGetVertexResponse(Vertex vertex, List edges, String version) - throws CrudException { + public static String buildGetVertexResponse(Vertex vertex, List edges, String version) throws CrudException { VertexPayload vertexPayload = new VertexPayload(); vertexPayload.setId(vertex.getId().get()); vertexPayload.setType(vertex.getType()); @@ -125,43 +123,36 @@ public class CrudResponseBuilder { EdgePayload inEdge = new EdgePayload(); inEdge.setId(e.getId().get()); inEdge.setType(e.getType()); - inEdge.setUrl(URL_BASE + "relationships/" - + RelationshipSchemaLoader.getLatestSchemaVersion() - + "/" + e.getType() + "/" + e.getId().get()); - inEdge.setSource( - URL_BASE + version + "/" + e.getSource().getType() + "/" + e.getSource().getId().get()); + inEdge.setUrl(URL_BASE + "relationships/" + RelationshipSchemaLoader.getLatestSchemaVersion() + "/" + + e.getType() + "/" + e.getId().get()); + inEdge.setSource(URL_BASE + version + "/" + e.getSource().getType() + "/" + e.getSource().getId().get()); inEdges.add(inEdge); } else if (e.getSource().getId().get().equals(vertex.getId().get())) { EdgePayload outEdge = new EdgePayload(); outEdge.setId(e.getId().get()); outEdge.setType(e.getType()); - outEdge.setUrl(URL_BASE + "relationships/" - + RelationshipSchemaLoader.getLatestSchemaVersion() - + "/" + e.getType() + "/" + e.getId().get()); - outEdge.setTarget( - URL_BASE + version + "/" + e.getTarget().getType() + "/" + e.getTarget().getId().get()); + outEdge.setUrl(URL_BASE + "relationships/" + RelationshipSchemaLoader.getLatestSchemaVersion() + "/" + + e.getType() + "/" + e.getId().get()); + outEdge.setTarget(URL_BASE + version + "/" + e.getTarget().getType() + "/" + e.getTarget().getId().get()); outEdges.add(outEdge); } } - vertexPayload.setIn(inEdges); vertexPayload.setOut(outEdges); return vertexPayload.toJson(); } - public static String buildGetVerticesResponse(List items, String version) - throws CrudException { + public static String buildGetVerticesResponse(List items, String version) throws CrudException { JsonArray arry = new JsonArray(); for (Vertex v : items) { JsonObject item = new JsonObject(); item.addProperty("id", v.getId().get()); item.addProperty("type", v.getType()); - item.addProperty("url", "services/inventory/" + version + "/" - + v.getType() + "/" + v.getId().get()); + item.addProperty("url", "services/inventory/" + version + "/" + v.getType() + "/" + v.getId().get()); arry.add(item); } @@ -174,14 +165,9 @@ public class CrudResponseBuilder { EdgePayload payload = new EdgePayload(); payload.setId(edge.getId().get()); payload.setType(edge.getType()); - payload.setUrl(URL_BASE + "relationships/" + version + "/" + edge.getType() - + "/" + edge.getId().get()); - payload.setSource( - URL_BASE + version + "/" + edge.getSource().getType() - + "/" + edge.getSource().getId().get()); - payload.setTarget( - URL_BASE + version + "/" + edge.getTarget().getType() - + "/" + edge.getTarget().getId().get()); + payload.setUrl(URL_BASE + "relationships/" + version + "/" + edge.getType() + "/" + edge.getId().get()); + payload.setSource(URL_BASE + version + "/" + edge.getSource().getType() + "/" + edge.getSource().getId().get()); + payload.setTarget(URL_BASE + version + "/" + edge.getTarget().getType() + "/" + edge.getTarget().getId().get()); JsonObject props = new JsonObject(); for (String key : edge.getProperties().keySet()) { @@ -191,20 +177,18 @@ public class CrudResponseBuilder { return payload.toJson(); } - public static String buildGetEdgesResponse(List items, String version) - throws CrudException { + public static String buildGetEdgesResponse(List items, String version) throws CrudException { JsonArray arry = new JsonArray(); for (Edge e : items) { JsonObject item = new JsonObject(); item.addProperty("id", e.getId().get()); item.addProperty("type", e.getType()); - item.addProperty("url", URL_BASE + "relationships/" + version + "/" + e.getType() - + "/" + e.getId().get()); - item.addProperty(SOURCE, "services/inventory/" + version + "/" + e.getSource().getType() - + "/" + e.getSource().getId().get()); - item.addProperty(TARGET, "services/inventory/" + version + "/" + e.getTarget().getType() - + "/" + e.getTarget().getId().get()); + item.addProperty("url", URL_BASE + "relationships/" + version + "/" + e.getType() + "/" + e.getId().get()); + item.addProperty(SOURCE, + "services/inventory/" + version + "/" + e.getSource().getType() + "/" + e.getSource().getId().get()); + item.addProperty(TARGET, + "services/inventory/" + version + "/" + e.getTarget().getType() + "/" + e.getTarget().getId().get()); arry.add(item); } diff --git a/src/main/java/org/openecomp/crud/service/BulkPayload.java b/src/main/java/org/openecomp/crud/service/BulkPayload.java index 28cf420..619c53b 100644 --- a/src/main/java/org/openecomp/crud/service/BulkPayload.java +++ b/src/main/java/org/openecomp/crud/service/BulkPayload.java @@ -39,90 +39,86 @@ import java.util.Set; import javax.ws.rs.core.Response.Status; public class BulkPayload { - public enum OperationType { - CREATE, UPDATE, DELETE - } - - - - private List objects = new ArrayList(); - private List relationships = new ArrayList(); - - private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - - public String toJson() { - return gson.toJson(this); - } - - public static BulkPayload fromJson(String payload) throws CrudException { - try { - if (payload == null || payload.isEmpty()) { - throw new CrudException("Invalid Json Payload", Status.BAD_REQUEST); - } - return gson.fromJson(payload, BulkPayload.class); - } catch (Exception ex) { - throw new CrudException("Invalid Json Payload", Status.BAD_REQUEST); - } - } - - public List getObjects() { - return objects; - } - - public void setObjects(List objects) { - this.objects = objects; - } - - public List getRelationships() { - return relationships; - } - - public void setRelationships(List relationships) { - this.relationships = relationships; - } - - @Override - public String toString() { - return "BulkPayload [objects=" + objects + ", relationships=" + relationships + "]"; - } - - public static void main(String[] args) throws Exception { - BulkPayload p = new BulkPayload(); - JsonObject root = new JsonObject(); - JsonArray vertices = new JsonArray(); - JsonObject v1 = new JsonObject(); - JsonObject v2 = new JsonObject(); - JsonObject prop = new JsonObject(); - - prop.addProperty("p1","value1"); - prop.addProperty("p2","value2"); - v1.add("v1", prop); - v2.add("v2",prop); - - vertices.add(v1); - vertices.add(v2); - - - root.add("objects", vertices); - - String s = "{\"objects\":[{\"v1\":{\"p1\":\"value1\",\"p2\":\"value2\"}},{\"v2\":{\"p1\":\"value1\",\"p2\":\"value2\"}}]}"; - - p = BulkPayload.fromJson(s); - - List po = p.getObjects(); - List ids = new ArrayList(); - for (JsonElement e : po){ - Set> entries = e.getAsJsonObject().entrySet(); - - for (Map.Entry entry : entries) { - ids.add(entry.getKey()); - } - } - - - System.out.println("root: " + root.toString()); - System.out.println("payload ids: " + ids.toString()); - - } + public enum OperationType { + CREATE, UPDATE, DELETE + } + + private List objects = new ArrayList(); + private List relationships = new ArrayList(); + + private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + + public String toJson() { + return gson.toJson(this); + } + + public static BulkPayload fromJson(String payload) throws CrudException { + try { + if (payload == null || payload.isEmpty()) { + throw new CrudException("Invalid Json Payload", Status.BAD_REQUEST); + } + return gson.fromJson(payload, BulkPayload.class); + } catch (Exception ex) { + throw new CrudException("Invalid Json Payload", Status.BAD_REQUEST); + } + } + + public List getObjects() { + return objects; + } + + public void setObjects(List objects) { + this.objects = objects; + } + + public List getRelationships() { + return relationships; + } + + public void setRelationships(List relationships) { + this.relationships = relationships; + } + + @Override + public String toString() { + return "BulkPayload [objects=" + objects + ", relationships=" + relationships + "]"; + } + + public static void main(String[] args) throws Exception { + BulkPayload p = new BulkPayload(); + JsonObject root = new JsonObject(); + JsonArray vertices = new JsonArray(); + JsonObject v1 = new JsonObject(); + JsonObject v2 = new JsonObject(); + JsonObject prop = new JsonObject(); + + prop.addProperty("p1", "value1"); + prop.addProperty("p2", "value2"); + v1.add("v1", prop); + v2.add("v2", prop); + + vertices.add(v1); + vertices.add(v2); + + root.add("objects", vertices); + + String s = "{\"objects\":[{\"v1\":{\"p1\":\"value1\",\"p2\":\"value2\"}},{\"v2\":{\"p1\":\"value1\",\"p2\":\"value2\"}}]}"; + + p = BulkPayload.fromJson(s); + + List po = p.getObjects(); + List ids = new ArrayList(); + for (JsonElement e : po) { + Set> entries = e.getAsJsonObject().entrySet(); + + for (Map.Entry entry : entries) { + ids.add(entry.getKey()); + } + } + + System.out.println("root: " + root.toString()); + System.out.println("payload ids: " + ids.toString()); + + } } \ No newline at end of file diff --git a/src/main/java/org/openecomp/crud/service/CrudGraphDataService.java b/src/main/java/org/openecomp/crud/service/CrudGraphDataService.java index c6b6a48..340fafa 100644 --- a/src/main/java/org/openecomp/crud/service/CrudGraphDataService.java +++ b/src/main/java/org/openecomp/crud/service/CrudGraphDataService.java @@ -50,148 +50,155 @@ public class CrudGraphDataService { private GraphDao dao; public CrudGraphDataService(ChampGraph graphImpl) throws CrudException { - this.dao = new ChampDao(graphImpl); - - loadModels(); - } + this.dao = new ChampDao(graphImpl); + loadModels(); + } - public CrudGraphDataService(GraphDao dao) throws CrudException { - this.dao = dao; + public CrudGraphDataService(GraphDao dao) throws CrudException { + this.dao = dao; - loadModels(); - } + loadModels(); + } - private void loadModels() throws CrudException { - //load the schemas - try { + private void loadModels() throws CrudException { + // load the schemas + try { OxmModelLoader.loadModels(); } catch (Exception e) { throw new CrudException(e); } - RelationshipSchemaLoader.loadModels(); - } + RelationshipSchemaLoader.loadModels(); + } public String addVertex(String version, String type, VertexPayload payload) throws CrudException { - Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, type, - payload.getProperties()); + Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, type, payload.getProperties()); return addVertex(version, vertex); } - - public String addBulk(String version, BulkPayload payload) throws CrudException { - HashMap vertices = new HashMap(); - HashMap edges = new HashMap(); - String txId = dao.openTransaction(); - try { - // Handle vertices - for (JsonElement v : payload.getObjects()) { - List> entries = new ArrayList>(v.getAsJsonObject().entrySet()); - - if (entries.size() != 2) { - throw new CrudException("", Status.BAD_REQUEST); - } - Map.Entry opr = entries.get(0); - Map.Entry item = entries.get(1); - - VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString()); - - if (opr.getValue().getAsString().equalsIgnoreCase("add") || opr.getValue().getAsString().equalsIgnoreCase("modify")) { - Vertex validatedVertex; - Vertex persistedVertex; - if (opr.getValue().getAsString().equalsIgnoreCase("add")) { - validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, vertexPayload.getType(), - vertexPayload.getProperties()); - // Call champDAO to add the vertex - persistedVertex = dao.addVertex(validatedVertex.getType(), validatedVertex.getProperties(), txId); - } else { - validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(vertexPayload.getId(), version, vertexPayload.getType(), - vertexPayload.getProperties()); - // Call champDAO to update the vertex - persistedVertex = dao.updateVertex(vertexPayload.getId(), validatedVertex.getType(), validatedVertex.getProperties(), txId); - } - - Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex); - - vertices.put(item.getKey(), outgoingVertex); - - } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) { - dao.deleteVertex(vertexPayload.getId(), OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), txId); - } - - } - // Handle Edges - for (JsonElement v : payload.getRelationships()) { - List> entries = new ArrayList>(v.getAsJsonObject().entrySet()); - - if (entries.size() != 2) { - throw new CrudException("", Status.BAD_REQUEST); - } - Map.Entry opr = entries.get(0); - Map.Entry item = entries.get(1); - - EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString()); - - if (opr.getValue().getAsString().equalsIgnoreCase("add") || opr.getValue().getAsString().equalsIgnoreCase("modify")) { - Edge validatedEdge; - Edge persistedEdge; - if (opr.getValue().getAsString().equalsIgnoreCase("add")) { - // Fix the source/detination - if (edgePayload.getSource().startsWith("$")) { - Vertex source = vertices.get(edgePayload.getSource().substring(1)); - if (source == null) { - throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1), Status.INTERNAL_SERVER_ERROR); - } - edgePayload.setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get()); - } - if (edgePayload.getTarget().startsWith("$")) { - Vertex target = vertices.get(edgePayload.getTarget().substring(1)); - if (target == null) { - throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1), Status.INTERNAL_SERVER_ERROR); - } - edgePayload.setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get()); - } - validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(), edgePayload); - persistedEdge = dao.addEdge(validatedEdge.getType(), validatedEdge.getSource(), validatedEdge.getTarget(), - validatedEdge.getProperties(), txId); - } else { - Edge edge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId); - validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload); - persistedEdge = dao.updateEdge(edge, txId); - } - - Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge); - - edges.put(item.getKey(), outgoingEdge); - - } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) { - RelationshipSchemaValidator.validateType(version, edgePayload.getType()); - dao.deleteEdge(edgePayload.getId(), edgePayload.getType(), txId); - } - - } - // close champ TX - dao.commitTransaction(txId); - } catch (CrudException ex) { - dao.rollbackTransaction(txId); - throw ex; - } catch (Exception ex) { - dao.rollbackTransaction(txId); - throw ex; - } finally { - if (dao.transactionExists(txId)) { - dao.rollbackTransaction(txId); - } - } - - - return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload); - } + + public String addBulk(String version, BulkPayload payload) throws CrudException { + HashMap vertices = new HashMap(); + HashMap edges = new HashMap(); + String txId = dao.openTransaction(); + try { + // Handle vertices + for (JsonElement v : payload.getObjects()) { + List> entries = new ArrayList>( + v.getAsJsonObject().entrySet()); + + if (entries.size() != 2) { + throw new CrudException("", Status.BAD_REQUEST); + } + Map.Entry opr = entries.get(0); + Map.Entry item = entries.get(1); + + VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString()); + + if (opr.getValue().getAsString().equalsIgnoreCase("add") + || opr.getValue().getAsString().equalsIgnoreCase("modify")) { + Vertex validatedVertex; + Vertex persistedVertex; + if (opr.getValue().getAsString().equalsIgnoreCase("add")) { + validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, vertexPayload.getType(), + vertexPayload.getProperties()); + // Call champDAO to add the vertex + persistedVertex = dao.addVertex(validatedVertex.getType(), validatedVertex.getProperties(), txId); + } else { + validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(vertexPayload.getId(), version, + vertexPayload.getType(), vertexPayload.getProperties()); + // Call champDAO to update the vertex + persistedVertex = dao.updateVertex(vertexPayload.getId(), validatedVertex.getType(), + validatedVertex.getProperties(), txId); + } + + Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex); + + vertices.put(item.getKey(), outgoingVertex); + + } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) { + dao.deleteVertex(vertexPayload.getId(), + OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), txId); + } + + } + // Handle Edges + for (JsonElement v : payload.getRelationships()) { + List> entries = new ArrayList>( + v.getAsJsonObject().entrySet()); + + if (entries.size() != 2) { + throw new CrudException("", Status.BAD_REQUEST); + } + Map.Entry opr = entries.get(0); + Map.Entry item = entries.get(1); + + EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString()); + + if (opr.getValue().getAsString().equalsIgnoreCase("add") + || opr.getValue().getAsString().equalsIgnoreCase("modify")) { + Edge validatedEdge; + Edge persistedEdge; + if (opr.getValue().getAsString().equalsIgnoreCase("add")) { + // Fix the source/detination + if (edgePayload.getSource().startsWith("$")) { + Vertex source = vertices.get(edgePayload.getSource().substring(1)); + if (source == null) { + throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1), + Status.INTERNAL_SERVER_ERROR); + } + edgePayload + .setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get()); + } + if (edgePayload.getTarget().startsWith("$")) { + Vertex target = vertices.get(edgePayload.getTarget().substring(1)); + if (target == null) { + throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1), + Status.INTERNAL_SERVER_ERROR); + } + edgePayload + .setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get()); + } + validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(), + edgePayload); + persistedEdge = dao.addEdge(validatedEdge.getType(), validatedEdge.getSource(), validatedEdge.getTarget(), + validatedEdge.getProperties(), txId); + } else { + Edge edge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId); + validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload); + persistedEdge = dao.updateEdge(edge, txId); + } + + Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge); + + edges.put(item.getKey(), outgoingEdge); + + } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) { + RelationshipSchemaValidator.validateType(version, edgePayload.getType()); + dao.deleteEdge(edgePayload.getId(), edgePayload.getType(), txId); + } + + } + // close champ TX + dao.commitTransaction(txId); + } catch (CrudException ex) { + dao.rollbackTransaction(txId); + throw ex; + } catch (Exception ex) { + dao.rollbackTransaction(txId); + throw ex; + } finally { + if (dao.transactionExists(txId)) { + dao.rollbackTransaction(txId); + } + } + + return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload); + } private String addVertex(String version, Vertex vertex) throws CrudException { Vertex addedVertex = dao.addVertex(vertex.getType(), vertex.getProperties()); return CrudResponseBuilder - .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, addedVertex), - version); + .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, addedVertex), version); } public String addEdge(String version, String type, EdgePayload payload) throws CrudException { @@ -200,52 +207,41 @@ public class CrudGraphDataService { } private String addEdge(String version, Edge edge) throws CrudException { - Edge addedEdge = dao.addEdge(edge.getType(), edge.getSource(), edge.getTarget(), - edge.getProperties()); - return CrudResponseBuilder.buildUpsertEdgeResponse( - RelationshipSchemaValidator.validateOutgoingPayload(version, addedEdge), version); + Edge addedEdge = dao.addEdge(edge.getType(), edge.getSource(), edge.getTarget(), edge.getProperties()); + return CrudResponseBuilder + .buildUpsertEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, addedEdge), version); } public String getEdge(String version, String id, String type) throws CrudException { RelationshipSchemaValidator.validateType(version, type); Edge edge = dao.getEdge(id, type); - return CrudResponseBuilder.buildGetEdgeResponse(RelationshipSchemaValidator - .validateOutgoingPayload(version, edge), + return CrudResponseBuilder.buildGetEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, edge), version); } - public String getEdges(String version, String type, Map filter) - throws CrudException { + public String getEdges(String version, String type, Map filter) throws CrudException { RelationshipSchemaValidator.validateType(version, type); - List items = dao.getEdges(type, RelationshipSchemaValidator - .resolveCollectionfilter(version, type, filter)); + List items = dao.getEdges(type, RelationshipSchemaValidator.resolveCollectionfilter(version, type, filter)); return CrudResponseBuilder.buildGetEdgesResponse(items, version); } - - public String updateVertex(String version, String id, String type, VertexPayload payload) - throws CrudException { - Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(id, version, type, - payload.getProperties()); + public String updateVertex(String version, String id, String type, VertexPayload payload) throws CrudException { + Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(id, version, type, payload.getProperties()); return updateVertex(version, vertex); } private String updateVertex(String version, Vertex vertex) throws CrudException { - Vertex updatedVertex = dao.updateVertex(vertex.getId().get(), vertex.getType(), - vertex.getProperties()); + Vertex updatedVertex = dao.updateVertex(vertex.getId().get(), vertex.getType(), vertex.getProperties()); return CrudResponseBuilder - .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, - updatedVertex), version); + .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, updatedVertex), version); } - public String patchVertex(String version, String id, String type, VertexPayload payload) - throws CrudException { - Vertex existingVertex = dao.getVertex(id, OxmModelValidator.resolveCollectionType(version, - type)); - Vertex vertex = OxmModelValidator.validateIncomingPatchPayload(id, version, type, - payload.getProperties(), existingVertex); + public String patchVertex(String version, String id, String type, VertexPayload payload) throws CrudException { + Vertex existingVertex = dao.getVertex(id, OxmModelValidator.resolveCollectionType(version, type)); + Vertex vertex = OxmModelValidator.validateIncomingPatchPayload(id, version, type, payload.getProperties(), + existingVertex); return updateVertex(version, vertex); } @@ -264,26 +260,22 @@ public class CrudGraphDataService { } - public String updateEdge(String version, String id, String type, EdgePayload payload) - throws CrudException { + public String updateEdge(String version, String id, String type, EdgePayload payload) throws CrudException { Edge edge = dao.getEdge(id, type); - Edge validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, - version, payload); + Edge validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, payload); return updateEdge(version, validatedEdge); } private String updateEdge(String version, Edge edge) throws CrudException { Edge updatedEdge = dao.updateEdge(edge); - return CrudResponseBuilder.buildUpsertEdgeResponse( - RelationshipSchemaValidator.validateOutgoingPayload(version, updatedEdge), version); + return CrudResponseBuilder + .buildUpsertEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, updatedEdge), version); } - public String patchEdge(String version, String id, String type, EdgePayload payload) - throws CrudException { + public String patchEdge(String version, String id, String type, EdgePayload payload) throws CrudException { Edge edge = dao.getEdge(id, type); - Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(edge, - version, payload); + Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(edge, version, payload); return updateEdge(version, patchedEdge); } @@ -291,23 +283,19 @@ public class CrudGraphDataService { public Vertex getVertex(String id) throws CrudException { return dao.getVertex(id); } - + public String getVertex(String version, String id, String type) throws CrudException { type = OxmModelValidator.resolveCollectionType(version, type); Vertex vertex = dao.getVertex(id, type); List edges = dao.getVertexEdges(id); - return CrudResponseBuilder.buildGetVertexResponse(OxmModelValidator - .validateOutgoingPayload(version, vertex), edges, version); + return CrudResponseBuilder.buildGetVertexResponse(OxmModelValidator.validateOutgoingPayload(version, vertex), edges, + version); } - public String getVertices(String version, String type, Map filter) - throws CrudException { + public String getVertices(String version, String type, Map filter) throws CrudException { type = OxmModelValidator.resolveCollectionType(version, type); - List items = dao.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, - type, filter)); + List items = dao.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, type, filter)); return CrudResponseBuilder.buildGetVerticesResponse(items, version); } - - } diff --git a/src/main/java/org/openecomp/crud/service/CrudRestService.java b/src/main/java/org/openecomp/crud/service/CrudRestService.java index 8a9f1c0..79b5624 100644 --- a/src/main/java/org/openecomp/crud/service/CrudRestService.java +++ b/src/main/java/org/openecomp/crud/service/CrudRestService.java @@ -87,12 +87,11 @@ public class CrudRestService { @GET @Path("/{version}/{type}/{id}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response getVertex(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response getVertex(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); @@ -109,8 +108,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -119,12 +117,11 @@ public class CrudRestService { @GET @Path("/{version}/{type}/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response getVertices(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("uri") @Encoded String uri, - @Context HttpHeaders headers, @Context UriInfo uriInfo, - @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response getVertices(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, @Context UriInfo uriInfo, + @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); @@ -146,8 +143,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -156,12 +152,11 @@ public class CrudRestService { @GET @Path("/relationships/{version}/{type}/{id}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response getEdge(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response getEdge(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); @@ -179,8 +174,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -189,12 +183,11 @@ public class CrudRestService { @GET @Path("/relationships/{version}/{type}/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response getEdges(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("uri") @Encoded String uri, - @Context HttpHeaders headers, @Context UriInfo uriInfo, - @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response getEdges(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, @Context UriInfo uriInfo, + @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); @@ -217,8 +210,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } @@ -228,12 +220,11 @@ public class CrudRestService { @PUT @Path("/relationships/{version}/{type}/{id}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response updateEdge(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response updateEdge(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); @@ -253,8 +244,7 @@ public class CrudRestService { String result; if (headers.getRequestHeaders().getFirst(HTTP_PATCH_METHOD_OVERRIDE) != null - && headers.getRequestHeaders().getFirst(HTTP_PATCH_METHOD_OVERRIDE) - .equalsIgnoreCase("PATCH")) { + && headers.getRequestHeaders().getFirst(HTTP_PATCH_METHOD_OVERRIDE).equalsIgnoreCase("PATCH")) { result = crudGraphDataService.patchEdge(version, id, type, payload); } else { @@ -268,8 +258,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } @@ -279,19 +268,17 @@ public class CrudRestService { @PATCH @Path("/relationships/{version}/{type}/{id}") - @Consumes({"application/merge-patch+json"}) - @Produces({MediaType.APPLICATION_JSON}) - public Response patchEdge(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ "application/merge-patch+json" }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response patchEdge(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.PATCH, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { + if (validateRequest(req, uri, content, Action.PATCH, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { EdgePayload payload = EdgePayload.fromJson(content); @@ -310,8 +297,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -320,12 +306,11 @@ public class CrudRestService { @PUT @Path("/{version}/{type}/{id}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response updateVertex(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response updateVertex(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); @@ -344,8 +329,7 @@ public class CrudRestService { } String result; if (headers.getRequestHeaders().getFirst(HTTP_PATCH_METHOD_OVERRIDE) != null - && headers.getRequestHeaders().getFirst(HTTP_PATCH_METHOD_OVERRIDE) - .equalsIgnoreCase("PATCH")) { + && headers.getRequestHeaders().getFirst(HTTP_PATCH_METHOD_OVERRIDE).equalsIgnoreCase("PATCH")) { result = crudGraphDataService.patchVertex(version, id, type, payload); } else { @@ -358,8 +342,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -368,20 +351,18 @@ public class CrudRestService { @PATCH @Path("/{version}/{type}/{id}") - @Consumes({"application/merge-patch+json"}) - @Produces({MediaType.APPLICATION_JSON}) - public Response patchVertex(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ "application/merge-patch+json" }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response patchVertex(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.PATCH, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { + if (validateRequest(req, uri, content, Action.PATCH, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { VertexPayload payload = VertexPayload.fromJson(content); if (payload.getProperties() == null || payload.getProperties().isJsonNull()) { @@ -399,8 +380,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -409,20 +389,18 @@ public class CrudRestService { @POST @Path("/{version}/{type}/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response addVertex(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("uri") @Encoded String uri, - @Context HttpHeaders headers, @Context UriInfo uriInfo, - @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response addVertex(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, @Context UriInfo uriInfo, + @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.POST, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { + if (validateRequest(req, uri, content, Action.POST, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { VertexPayload payload = VertexPayload.fromJson(content); @@ -430,8 +408,7 @@ public class CrudRestService { throw new CrudException("Invalid request Payload", Status.BAD_REQUEST); } if (payload.getId() != null) { - throw new CrudException("ID specified , use Http PUT to update Vertex", - Status.BAD_REQUEST); + throw new CrudException("ID specified , use Http PUT to update Vertex", Status.BAD_REQUEST); } if (payload.getType() != null && !payload.getType().equals(type)) { @@ -446,135 +423,138 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); return response; } - - private void validateBulkPayload(BulkPayload payload) throws CrudException { - List vertices = new ArrayList(); - List edges = new ArrayList(); - - for (JsonElement v : payload.getObjects()) { - List> entries = new ArrayList>(v.getAsJsonObject().entrySet()); - - if (entries.size() != 2) { - throw new CrudException("", Status.BAD_REQUEST); - } - Map.Entry opr = entries.get(0); - Map.Entry item = entries.get(1); - - if (vertices.contains(item.getKey())) { - throw new CrudException("duplicate vertex in payload: " + item.getKey(), Status.BAD_REQUEST); - } - VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString()); - if (vertexPayload.getType() == null) { - throw new CrudException("Vertex Type cannot be null for: " + item.getKey(), Status.BAD_REQUEST); - } - - if (!opr.getKey().equalsIgnoreCase("operation")) { - throw new CrudException("operation missing in item: " + item.getKey(), Status.BAD_REQUEST); - } - - if (!opr.getValue().getAsString().equalsIgnoreCase("add") && !opr.getValue().getAsString().equalsIgnoreCase("modify") - && !opr.getValue().getAsString().equalsIgnoreCase("delete")) { - throw new CrudException("Invalid operation at item: " + item.getKey(), Status.BAD_REQUEST); - } - // check if ID is populate for modify/delete operation - if ((opr.getValue().getAsString().equalsIgnoreCase("modify") || opr.getValue().getAsString().equalsIgnoreCase("delete")) - && (vertexPayload.getId() == null)) { - - throw new CrudException("Mising ID at item: " + item.getKey(), Status.BAD_REQUEST); - - } - - vertices.add(item.getKey()); - } - - for (JsonElement v : payload.getRelationships()) { - List> entries = new ArrayList>(v.getAsJsonObject().entrySet()); - - if (entries.size() != 2) { - throw new CrudException("", Status.BAD_REQUEST); - } - Map.Entry opr = entries.get(0); - Map.Entry item = entries.get(1); - - if (edges.contains(item.getKey())) { - throw new CrudException("duplicate Edge in payload: " + item.getKey(), Status.BAD_REQUEST); - } - - EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString()); - - if (edgePayload.getType() == null) { - throw new CrudException("Edge Type cannot be null for: " + item.getKey(), Status.BAD_REQUEST); - } - - if (!opr.getKey().equalsIgnoreCase("operation")) { - throw new CrudException("operation missing in item: " + item.getKey(), Status.BAD_REQUEST); - } - - if (!opr.getValue().getAsString().equalsIgnoreCase("add") && !opr.getValue().getAsString().equalsIgnoreCase("modify") - && !opr.getValue().getAsString().equalsIgnoreCase("delete")) { - throw new CrudException("Invalid operation at item: " + item.getKey(), Status.BAD_REQUEST); - } - // check if ID is populate for modify/delete operation - if ((edgePayload.getId() == null) && (opr.getValue().getAsString().equalsIgnoreCase("modify") - || opr.getValue().getAsString().equalsIgnoreCase("delete"))) { - - throw new CrudException("Mising ID at item: " + item.getKey(), Status.BAD_REQUEST); - - } - if (opr.getValue().getAsString().equalsIgnoreCase("add")) { - if(edgePayload.getSource()==null || edgePayload.getTarget()==null){ - throw new CrudException("Source/Target cannot be null for edge: " + item.getKey(), - Status.BAD_REQUEST); - } - if (edgePayload.getSource().startsWith("$") && !vertices.contains(edgePayload.getSource().substring(1))) { - throw new CrudException("Source Vertex " + edgePayload.getSource().substring(1) + " not found for Edge: " + item.getKey(), - Status.BAD_REQUEST); - } - - if (edgePayload.getTarget().startsWith("$") && !vertices.contains(edgePayload.getTarget().substring(1))) { - throw new CrudException("Target Vertex " + edgePayload.getSource().substring(1) + " not found for Edge: " + item.getKey(), - Status.BAD_REQUEST); - } - } - edges.add(item.getKey()); - - } - - } - + + private void validateBulkPayload(BulkPayload payload) throws CrudException { + List vertices = new ArrayList(); + List edges = new ArrayList(); + + for (JsonElement v : payload.getObjects()) { + List> entries = new ArrayList>( + v.getAsJsonObject().entrySet()); + + if (entries.size() != 2) { + throw new CrudException("", Status.BAD_REQUEST); + } + Map.Entry opr = entries.get(0); + Map.Entry item = entries.get(1); + + if (vertices.contains(item.getKey())) { + throw new CrudException("duplicate vertex in payload: " + item.getKey(), Status.BAD_REQUEST); + } + VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString()); + if (vertexPayload.getType() == null) { + throw new CrudException("Vertex Type cannot be null for: " + item.getKey(), Status.BAD_REQUEST); + } + + if (!opr.getKey().equalsIgnoreCase("operation")) { + throw new CrudException("operation missing in item: " + item.getKey(), Status.BAD_REQUEST); + } + + if (!opr.getValue().getAsString().equalsIgnoreCase("add") + && !opr.getValue().getAsString().equalsIgnoreCase("modify") + && !opr.getValue().getAsString().equalsIgnoreCase("delete")) { + throw new CrudException("Invalid operation at item: " + item.getKey(), Status.BAD_REQUEST); + } + // check if ID is populate for modify/delete operation + if ((opr.getValue().getAsString().equalsIgnoreCase("modify") + || opr.getValue().getAsString().equalsIgnoreCase("delete")) && (vertexPayload.getId() == null)) { + + throw new CrudException("Mising ID at item: " + item.getKey(), Status.BAD_REQUEST); + + } + + vertices.add(item.getKey()); + } + + for (JsonElement v : payload.getRelationships()) { + List> entries = new ArrayList>( + v.getAsJsonObject().entrySet()); + + if (entries.size() != 2) { + throw new CrudException("", Status.BAD_REQUEST); + } + Map.Entry opr = entries.get(0); + Map.Entry item = entries.get(1); + + if (edges.contains(item.getKey())) { + throw new CrudException("duplicate Edge in payload: " + item.getKey(), Status.BAD_REQUEST); + } + + EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString()); + + if (edgePayload.getType() == null) { + throw new CrudException("Edge Type cannot be null for: " + item.getKey(), Status.BAD_REQUEST); + } + + if (!opr.getKey().equalsIgnoreCase("operation")) { + throw new CrudException("operation missing in item: " + item.getKey(), Status.BAD_REQUEST); + } + + if (!opr.getValue().getAsString().equalsIgnoreCase("add") + && !opr.getValue().getAsString().equalsIgnoreCase("modify") + && !opr.getValue().getAsString().equalsIgnoreCase("delete")) { + throw new CrudException("Invalid operation at item: " + item.getKey(), Status.BAD_REQUEST); + } + // check if ID is populate for modify/delete operation + if ((edgePayload.getId() == null) && (opr.getValue().getAsString().equalsIgnoreCase("modify") + || opr.getValue().getAsString().equalsIgnoreCase("delete"))) { + + throw new CrudException("Mising ID at item: " + item.getKey(), Status.BAD_REQUEST); + + } + if (opr.getValue().getAsString().equalsIgnoreCase("add")) { + if (edgePayload.getSource() == null || edgePayload.getTarget() == null) { + throw new CrudException("Source/Target cannot be null for edge: " + item.getKey(), Status.BAD_REQUEST); + } + if (edgePayload.getSource().startsWith("$") && !vertices.contains(edgePayload.getSource().substring(1))) { + throw new CrudException( + "Source Vertex " + edgePayload.getSource().substring(1) + " not found for Edge: " + item.getKey(), + Status.BAD_REQUEST); + } + + if (edgePayload.getTarget().startsWith("$") && !vertices.contains(edgePayload.getTarget().substring(1))) { + throw new CrudException( + "Target Vertex " + edgePayload.getSource().substring(1) + " not found for Edge: " + item.getKey(), + Status.BAD_REQUEST); + } + } + edges.add(item.getKey()); + + } + + } + @POST @Path("/{version}/bulk/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response addBulk(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("uri") @Encoded String uri, - @Context HttpHeaders headers, @Context UriInfo uriInfo, - @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response addBulk(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, @Context UriInfo uriInfo, + @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.POST, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { + if (validateRequest(req, uri, content, Action.POST, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { BulkPayload payload = BulkPayload.fromJson(content); - if ((payload.getObjects() == null && payload.getRelationships() == null) || (payload.getObjects() != null && payload.getObjects().isEmpty() - && payload.getRelationships() != null && payload.getRelationships().isEmpty())) { + if ((payload.getObjects() == null && payload.getRelationships() == null) + || (payload.getObjects() != null && payload.getObjects().isEmpty() && payload.getRelationships() != null + && payload.getRelationships().isEmpty())) { throw new CrudException("Invalid request Payload", Status.BAD_REQUEST); } - - validateBulkPayload(payload); - String result = crudGraphDataService.addBulk(version, payload); + + validateBulkPayload(payload); + String result = crudGraphDataService.addBulk(version, payload); response = Response.status(Status.OK).entity(result).type(mediaType).build(); } catch (CrudException ce) { response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build(); @@ -582,8 +562,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -592,19 +571,17 @@ public class CrudRestService { @POST @Path("/{version}/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response addVertex(String content, @PathParam("version") String version, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response addVertex(String content, @PathParam("version") String version, @PathParam("uri") @Encoded String uri, + @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.POST, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { + if (validateRequest(req, uri, content, Action.POST, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { VertexPayload payload = VertexPayload.fromJson(content); @@ -612,8 +589,7 @@ public class CrudRestService { throw new CrudException("Invalid request Payload", Status.BAD_REQUEST); } if (payload.getId() != null) { - throw new CrudException("ID specified , use Http PUT to update Vertex", - Status.BAD_REQUEST); + throw new CrudException("ID specified , use Http PUT to update Vertex", Status.BAD_REQUEST); } if (payload.getType() == null || payload.getType().isEmpty()) { @@ -627,8 +603,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -637,21 +612,18 @@ public class CrudRestService { @POST @Path("/relationships/{version}/{type}/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response addEdge(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("uri") @Encoded String uri, - @Context HttpHeaders headers, @Context UriInfo uriInfo, - @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response addEdge(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, @Context UriInfo uriInfo, + @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.POST, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { - + if (validateRequest(req, uri, content, Action.POST, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { EdgePayload payload = EdgePayload.fromJson(content); @@ -673,8 +645,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -683,20 +654,17 @@ public class CrudRestService { @POST @Path("/relationships/{version}/") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response addEdge(String content, @PathParam("version") String version, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response addEdge(String content, @PathParam("version") String version, @PathParam("uri") @Encoded String uri, + @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.POST, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { - + if (validateRequest(req, uri, content, Action.POST, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { EdgePayload payload = EdgePayload.fromJson(content); @@ -719,8 +687,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -729,21 +696,18 @@ public class CrudRestService { @DELETE @Path("/{version}/{type}/{id}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response deleteVertex(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response deleteVertex(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.DELETE, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { - + if (validateRequest(req, uri, content, Action.DELETE, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { String result = crudGraphDataService.deleteVertex(version, id, type); @@ -754,8 +718,7 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); @@ -764,19 +727,17 @@ public class CrudRestService { @DELETE @Path("/relationships/{version}/{type}/{id}") - @Consumes({MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_JSON}) - public Response deleteEdge(String content, @PathParam("version") String version, - @PathParam("type") String type, @PathParam("id") String id, - @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, - @Context UriInfo uriInfo, @Context HttpServletRequest req) { + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response deleteEdge(String content, @PathParam("version") String version, @PathParam("type") String type, + @PathParam("id") String id, @PathParam("uri") @Encoded String uri, @Context HttpHeaders headers, + @Context UriInfo uriInfo, @Context HttpServletRequest req) { LoggingUtil.initMdcContext(req, headers); logger.debug("Incoming request..." + content); Response response = null; - if (validateRequest(req, uri, content, Action.DELETE, - CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { + if (validateRequest(req, uri, content, Action.DELETE, CrudServiceConstants.CRD_AUTH_POLICY_NAME)) { try { String result = crudGraphDataService.deleteEdge(version, id, type); @@ -787,28 +748,25 @@ public class CrudRestService { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } else { - response = Response.status(Status.FORBIDDEN).entity(content) - .type(MediaType.APPLICATION_JSON).build(); + response = Response.status(Status.FORBIDDEN).entity(content).type(MediaType.APPLICATION_JSON).build(); } LoggingUtil.logRestRequest(logger, auditLogger, req, response); return response; } - protected boolean validateRequest(HttpServletRequest req, String uri, String content, - Action action, String authPolicyFunctionName) { + protected boolean validateRequest(HttpServletRequest req, String uri, String content, Action action, + String authPolicyFunctionName) { try { String cipherSuite = (String) req.getAttribute("javax.servlet.request.cipher_suite"); String authUser = null; if (cipherSuite != null) { - X509Certificate[] certChain = (X509Certificate[]) req - .getAttribute("javax.servlet.request.X509Certificate"); + X509Certificate[] certChain = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); X509Certificate clientCert = certChain[0]; X500Principal subjectDn = clientCert.getSubjectX500Principal(); authUser = subjectDn.toString(); } - return this.auth.validateRequest(authUser.toLowerCase(), action.toString() - + ":" + authPolicyFunctionName); + return this.auth.validateRequest(authUser.toLowerCase(), action.toString() + ":" + authPolicyFunctionName); } catch (Exception e) { logResult(action, uri, e); return false; @@ -817,8 +775,7 @@ public class CrudRestService { void logResult(Action op, String uri, Exception e) { - logger.error(CrudServiceMsgs.EXCEPTION_DURING_METHOD_CALL, op.toString(), uri, - e.getStackTrace().toString()); + logger.error(CrudServiceMsgs.EXCEPTION_DURING_METHOD_CALL, op.toString(), uri, e.getStackTrace().toString()); // Clear the MDC context so that no other transaction inadvertently // uses our transaction id. diff --git a/src/main/java/org/openecomp/schema/OxmModelValidator.java b/src/main/java/org/openecomp/schema/OxmModelValidator.java index e51b23f..79136e4 100644 --- a/src/main/java/org/openecomp/schema/OxmModelValidator.java +++ b/src/main/java/org/openecomp/schema/OxmModelValidator.java @@ -44,11 +44,8 @@ import javax.ws.rs.core.Response.Status; public class OxmModelValidator { public enum Metadata { - NODE_TYPE("aai-node-type"), - URI("aai-uri"), - CREATED_TS("aai-created-ts"), - SOT("source-of-truth"), - LAST_MOD_SOT("last-mod-source-of-truth"); + NODE_TYPE("aai-node-type"), URI("aai-uri"), CREATED_TS("aai-created-ts"), SOT("source-of-truth"), LAST_MOD_SOT( + "last-mod-source-of-truth"); private final String propName; @@ -70,9 +67,7 @@ public class OxmModelValidator { } } - - public static Map resolveCollectionfilter(String version, String type, - Map filter) + public static Map resolveCollectionfilter(String version, String type, Map filter) throws CrudException { DynamicJAXBContext jaxbContext = null; @@ -86,18 +81,15 @@ public class OxmModelValidator { if (jaxbContext == null) { throw new CrudException("", Status.NOT_FOUND); } - final DynamicType modelObjectType = jaxbContext.getDynamicType(CaseFormat.LOWER_CAMEL - .to(CaseFormat.UPPER_CAMEL, - CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type))); + final DynamicType modelObjectType = jaxbContext.getDynamicType( + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type))); for (String key : filter.keySet()) { String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key); if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) { try { - DatabaseMapping mapping = modelObjectType.getDescriptor() - .getMappingForAttributeName(keyJavaName); - Object value = CrudServiceUtil.validateFieldType(filter.get(key), - mapping.getField().getType()); + DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName); + Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType()); result.put(key, value); } catch (Exception ex) { // Skip any exceptions thrown while validating the filter @@ -125,9 +117,8 @@ public class OxmModelValidator { } // Determine if the Object part is a collection type in the model // definition - final DynamicType modelObjectType = jaxbContext.getDynamicType(CaseFormat.LOWER_CAMEL - .to(CaseFormat.UPPER_CAMEL, - CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type))); + final DynamicType modelObjectType = jaxbContext.getDynamicType( + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type))); if (modelObjectType == null) { throw new CrudException("", Status.NOT_FOUND); @@ -135,8 +126,7 @@ public class OxmModelValidator { if (modelObjectType.getDescriptor().getMappings().size() == 1 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) { - String childJavaObjectName = modelObjectType.getDescriptor().getMappings() - .get(0).getAttributeName(); + String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName(); childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName); final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName); if (childObjectType == null) { @@ -151,9 +141,7 @@ public class OxmModelValidator { } - - public static Vertex validateIncomingUpsertPayload(String id, String version, String type, - JsonElement properties) + public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties) throws CrudException { try { @@ -165,18 +153,17 @@ public class OxmModelValidator { final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass); final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames"); - Set> payloadEntriesSet = properties.getAsJsonObject() - .entrySet(); + Set> payloadEntriesSet = properties.getAsJsonObject().entrySet(); - //loop through input to validate against schema + // loop through input to validate against schema for (Map.Entry entry : payloadEntriesSet) { String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey()); // check for valid field if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) { - if(reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null){ - throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST); - } + if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) { + throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST); + } } } @@ -198,31 +185,26 @@ public class OxmModelValidator { String keyName = field.getName().substring(0, field.getName().indexOf("/")); - if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) - && !defaultValue.isEmpty()) { - modelVertexBuilder.property(keyName, - CrudServiceUtil.validateFieldType(defaultValue, field.getType())); + if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) { + modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType())); } // if schema field is required and not set then reject - if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) - && defaultValue.isEmpty()) { + if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) { throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST); } // If invalid field then reject if (entriesMap.containsKey(keyName)) { - Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName) - .getAsString(), field.getType()); + Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType()); modelVertexBuilder.property(keyName, value); } // Set defaults if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) { - modelVertexBuilder.property(keyName, - CrudServiceUtil.validateFieldType(defaultValue, field.getType())); + modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType())); } } } - + // Handle reserved properties for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) { if (mapping.isAbstractDirectMapping()) { @@ -230,8 +212,7 @@ public class OxmModelValidator { String keyName = field.getName().substring(0, field.getName().indexOf("/")); if (entriesMap.containsKey(keyName)) { - Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName) - .getAsString(), field.getType()); + Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType()); modelVertexBuilder.property(keyName, value); } } @@ -243,9 +224,8 @@ public class OxmModelValidator { } } - public static Vertex validateIncomingPatchPayload(String id, String version, String type, - JsonElement properties, Vertex existingVertex) - throws CrudException { + public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties, + Vertex existingVertex) throws CrudException { try { type = resolveCollectionType(version, type); @@ -256,8 +236,7 @@ public class OxmModelValidator { final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass); final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames"); - Set> payloadEntriesSet = properties.getAsJsonObject() - .entrySet(); + Set> payloadEntriesSet = properties.getAsJsonObject().entrySet(); // Loop through the payload properties and merge with existing // vertex props @@ -267,41 +246,34 @@ public class OxmModelValidator { DatabaseField field = null; String defaultValue = null; - + if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) { field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField(); - defaultValue = modelObjectType.getDescriptor() - .getMappingForAttributeName(keyJavaName) - .getProperties().get("defaultValue") == null ? "" - : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) - .getProperties().get("defaultValue").toString(); - } - else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) { + defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties() + .get("defaultValue") == null ? "" + : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties() + .get("defaultValue").toString(); + } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) { field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField(); defaultValue = ""; } - + if (field == null) { throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST); } // check if mandatory field is not set to null - if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull - && !defaultValue.isEmpty()) { + if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) { existingVertex.getProperties().put(entry.getKey(), CrudServiceUtil.validateFieldType(defaultValue, field.getType())); - } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull - && defaultValue.isEmpty()) { - throw new CrudException("Mandatory field: " + entry.getKey() - + " can't be set to null", - Status.BAD_REQUEST); + } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) { + throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST); } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && existingVertex.getProperties().containsKey(entry.getKey())) { existingVertex.getProperties().remove(entry.getKey()); } else if (!(entry.getValue() instanceof JsonNull)) { // add/update the value if found in existing vertex - Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), - field.getType()); + Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType()); existingVertex.getProperties().put(entry.getKey(), value); } @@ -313,7 +285,7 @@ public class OxmModelValidator { } } - + private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) { for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) { int ix = field.getName().indexOf("/"); @@ -331,8 +303,7 @@ public class OxmModelValidator { public static Vertex validateOutgoingPayload(String version, Vertex vertex) { - Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()) - .id(vertex.getId().get()); + Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get()); try { DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version); @@ -357,5 +328,4 @@ public class OxmModelValidator { } - } diff --git a/src/main/java/org/openecomp/schema/RelationshipSchemaLoader.java b/src/main/java/org/openecomp/schema/RelationshipSchemaLoader.java index 89a9e58..cc6315c 100644 --- a/src/main/java/org/openecomp/schema/RelationshipSchemaLoader.java +++ b/src/main/java/org/openecomp/schema/RelationshipSchemaLoader.java @@ -66,9 +66,8 @@ public class RelationshipSchemaLoader { final static Pattern propsFilePattern = Pattern.compile(edgePropsFiles + "(.*)" + fileExt); final static Pattern versionPattern = Pattern.compile(".*(v\\d+)" + fileExt); - private static org.openecomp.cl.api.Logger logger = LoggerFactory.getInstance() - .getLogger(RelationshipSchemaLoader.class.getName()); + .getLogger(RelationshipSchemaLoader.class.getName()); public synchronized static void loadModels() throws CrudException { load(rulesFilePattern, propsFilePattern); @@ -112,7 +111,6 @@ public class RelationshipSchemaLoader { RelationshipSchemaLoader.versionContextMap = new ConcurrentHashMap<>(); } - private static void load(Pattern rulesPattern, Pattern edgePropsPattern) throws CrudException { ClassLoader cl = RelationshipSchemaLoader.class.getClassLoader(); ResourcePatternResolver rulesResolver = new PathMatchingResourcePatternResolver(cl); @@ -121,51 +119,66 @@ public class RelationshipSchemaLoader { try { // getResources method returns objects of type "Resource" - // 1. We are getting all the objects from the classpath which has "DbEdgeRules" in the name. - // 2. We run them through a filter and return only the objects which match the supplied pattern "p" - // 3. We then collect the objects in a list. At this point we have a list of the kind of files we require. + // 1. We are getting all the objects from the classpath which has + // "DbEdgeRules" in the name. + // 2. We run them through a filter and return only the objects which match + // the supplied pattern "p" + // 3. We then collect the objects in a list. At this point we have a list + // of the kind of files we require. rulesFiles = Arrays.stream(rulesResolver.getResources("classpath*:/dbedgerules/DbEdgeRules*" + fileExt)) - .filter(r -> !myMatcher(rulesPattern, r.getFilename()).isEmpty()) - .collect(Collectors.toList()); + .filter(r -> !myMatcher(rulesPattern, r.getFilename()).isEmpty()).collect(Collectors.toList()); - // This gets all the objects of type "File" from external directory (not on the classpath) - // 1. From an external directory (one not on the classpath) we get all the objects of type "File" - // 2. We only return the files whose names matched the supplied pattern "p2". - // 3. We then collect all the objects in a list and add the contents of this list - // to the previous collection (rulesFiles) - rulesFiles.addAll(Arrays.stream(new File(rulesDir).listFiles((d, name) -> - edgePropsPattern.matcher(name).matches())).collect(Collectors.toList())); + // This gets all the objects of type "File" from external directory (not + // on the classpath) + // 1. From an external directory (one not on the classpath) we get all the + // objects of type "File" + // 2. We only return the files whose names matched the supplied pattern + // "p2". + // 3. We then collect all the objects in a list and add the contents of + // this list + // to the previous collection (rulesFiles) + rulesFiles + .addAll(Arrays.stream(new File(rulesDir).listFiles((d, name) -> edgePropsPattern.matcher(name).matches())) + .collect(Collectors.toList())); if (rulesFiles.isEmpty()) { logger.error(CrudServiceMsgs.INVALID_OXM_DIR, rulesDir); throw new FileNotFoundException("DbEdgeRules and edge_properties files were not found."); } - // Sort and then group the files with their versions, convert them to the schema, and add them to versionContextMap - // 1. Sort the files. We need the DbEdgeRules files to be before the edgeProperties files. - // 2. Group the files with their versions. ie. v11 -> ["DbEdgeRule_v11.json", "edgeProperties_v11.json"]. - // The "group method" returns a HashMap whose key is the version and the value is a list of objects. - // 3. Go through each version and map the files into one schema using the "jsonFilesLoader" method. - // Also update the "versionContextMap" with the version and it's schema. + // Sort and then group the files with their versions, convert them to the + // schema, and add them to versionContextMap + // 1. Sort the files. We need the DbEdgeRules files to be before the + // edgeProperties files. + // 2. Group the files with their versions. ie. v11 -> + // ["DbEdgeRule_v11.json", "edgeProperties_v11.json"]. + // The "group method" returns a HashMap whose key is the version and the + // value is a list of objects. + // 3. Go through each version and map the files into one schema using the + // "jsonFilesLoader" method. + // Also update the "versionContextMap" with the version and it's schema. rulesFiles.stream().sorted(Comparator.comparing(RelationshipSchemaLoader::filename)) - .collect(Collectors.groupingBy(f -> myMatcher(versionPattern, filename(f)))) - .forEach((version, resourceAndFile) -> { - if (resourceAndFile.size() == 2 ) { - versionContextMap.put(version, jsonFilesLoader(version, resourceAndFile)); - } else { - String filenames = resourceAndFile.stream().map(f-> filename(f)).collect(Collectors.toList()).toString(); - String errorMsg = "Expecting a rules and a edge_properties files for " + version + ". Found: " + filenames; - logger.warn(CrudServiceMsgs.INVALID_OXM_FILE, errorMsg); - }}); - logger.info(CrudServiceMsgs.LOADED_OXM_FILE, "Relationship Schema and Properties files: " + rulesFiles.stream().map(f -> filename(f)).collect(Collectors.toList())); + .collect(Collectors.groupingBy(f -> myMatcher(versionPattern, filename(f)))) + .forEach((version, resourceAndFile) -> { + if (resourceAndFile.size() == 2) { + versionContextMap.put(version, jsonFilesLoader(version, resourceAndFile)); + } else { + String filenames = resourceAndFile.stream().map(f -> filename(f)).collect(Collectors.toList()).toString(); + String errorMsg = "Expecting a rules and a edge_properties files for " + version + ". Found: " + + filenames; + logger.warn(CrudServiceMsgs.INVALID_OXM_FILE, errorMsg); + } + }); + logger.info(CrudServiceMsgs.LOADED_OXM_FILE, "Relationship Schema and Properties files: " + + rulesFiles.stream().map(f -> filename(f)).collect(Collectors.toList())); } catch (IOException e) { logger.error(CrudServiceMsgs.INVALID_OXM_DIR, rulesDir); throw new CrudException("DbEdgeRules or edge_properties files were not found.", new FileNotFoundException()); } } - private static String filename (Object k) throws ClassCastException { - if (k instanceof UrlResource){ + private static String filename(Object k) throws ClassCastException { + if (k instanceof UrlResource) { return ((UrlResource) k).getFilename(); } else if (k instanceof File) { return ((File) k).getName(); @@ -174,7 +187,7 @@ public class RelationshipSchemaLoader { } } - private static RelationshipSchema jsonFilesLoader (String version, List files) { + private static RelationshipSchema jsonFilesLoader(String version, List files) { List fileContents = new ArrayList<>(); RelationshipSchema rsSchema = null; if (files.size() == 2) { @@ -188,29 +201,29 @@ public class RelationshipSchemaLoader { } catch (CrudException | IOException e) { e.printStackTrace(); logger.error(CrudServiceMsgs.INVALID_OXM_FILE, - files.stream().map(f -> filename(f)).collect(Collectors.toList()).toString(), e.getMessage()); + files.stream().map(f -> filename(f)).collect(Collectors.toList()).toString(), e.getMessage()); } return rsSchema; } return rsSchema; } - private synchronized static void updateVersionContext(String version, RelationshipSchema rs){ + private synchronized static void updateVersionContext(String version, RelationshipSchema rs) { versionContextMap.put(version, rs); } - private synchronized static String jsonToRelationSchema (String version, Object file) { + private synchronized static String jsonToRelationSchema(String version, Object file) { InputStream inputStream = null; String content = null; try { - if (file instanceof UrlResource) { + if (file instanceof UrlResource) { inputStream = ((UrlResource) file).getInputStream(); } else { inputStream = new FileInputStream((File) file); addtimer(version, file); } - content = IOUtils.toString(inputStream, "UTF-8"); + content = IOUtils.toString(inputStream, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } @@ -219,14 +232,14 @@ public class RelationshipSchemaLoader { private static void addtimer(String version, Object file) { TimerTask task = null; - task = new FileWatcher( - (File) file) { + task = new FileWatcher((File) file) { protected void onChange(File file) { // here we implement the onChange logger.info(CrudServiceMsgs.OXM_FILE_CHANGED, file.getName()); try { - // Cannot use the file object here because we also have to get the edge properties associated with that version. + // Cannot use the file object here because we also have to get the + // edge properties associated with that version. // The properties are stored in a different file. RelationshipSchemaLoader.loadModels(version); } catch (Exception e) { @@ -243,7 +256,7 @@ public class RelationshipSchemaLoader { } } - private static String myMatcher (Pattern p, String s) { + private static String myMatcher(Pattern p, String s) { Matcher m = p.matcher(s); return m.matches() ? m.group(1) : ""; } -- 2.16.6