Port async pipeline for gizmo
[aai/gizmo.git] / src / main / java / org / onap / crud / service / CrudGraphDataService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Gizmo
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *    http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  *
22  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23  */
24 package org.onap.crud.service;
25
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.ws.rs.core.Response.Status;
32
33 import org.onap.crud.dao.GraphDao;
34 import org.onap.crud.entity.Edge;
35
36 import org.onap.crud.entity.Vertex;
37 import org.onap.crud.exception.CrudException;
38 import org.onap.crud.parser.CrudResponseBuilder;
39 import org.onap.crud.util.CrudServiceUtil;
40 import org.onap.schema.OxmModelValidator;
41 import org.onap.schema.RelationshipSchemaValidator;
42
43 import com.google.gson.JsonElement;
44
45 public class CrudGraphDataService {
46
47   private GraphDao dao;
48
49   public CrudGraphDataService(GraphDao dao) throws CrudException {
50     this.dao = dao;
51
52     CrudServiceUtil.loadModels();
53   }
54
55
56
57   public String addVertex(String version, String type, VertexPayload payload) throws CrudException {
58     Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, type, payload.getProperties());
59     return addVertex(version, vertex);
60   }
61
62   public String addBulk(String version, BulkPayload payload) throws CrudException {
63     HashMap<String, Vertex> vertices = new HashMap<String, Vertex>();
64     HashMap<String, Edge> edges = new HashMap<String, Edge>();
65     String txId = dao.openTransaction();
66     try {
67       // Handle vertices
68       for (JsonElement v : payload.getObjects()) {
69         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
70             v.getAsJsonObject().entrySet());
71
72         if (entries.size() != 2) {
73           throw new CrudException("", Status.BAD_REQUEST);
74         }
75         Map.Entry<String, JsonElement> opr = entries.get(0);
76         Map.Entry<String, JsonElement> item = entries.get(1);
77
78         VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString());
79
80         if (opr.getValue().getAsString().equalsIgnoreCase("add")
81             || opr.getValue().getAsString().equalsIgnoreCase("modify")) {
82           Vertex validatedVertex;
83           Vertex persistedVertex;
84           if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
85             validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, vertexPayload.getType(),
86                 vertexPayload.getProperties());
87             // Call champDAO to add the vertex
88             persistedVertex = dao.addVertex(validatedVertex.getType(), validatedVertex.getProperties(), txId);
89           } else {
90             validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(vertexPayload.getId(), version,
91                 vertexPayload.getType(), vertexPayload.getProperties());
92             // Call champDAO to update the vertex
93             persistedVertex = dao.updateVertex(vertexPayload.getId(), validatedVertex.getType(),
94                 validatedVertex.getProperties(), txId);
95           }
96
97           Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
98
99           vertices.put(item.getKey(), outgoingVertex);
100
101         } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
102           dao.deleteVertex(vertexPayload.getId(),
103               OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), txId);
104         }
105
106       }
107       // Handle Edges
108       for (JsonElement v : payload.getRelationships()) {
109         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
110             v.getAsJsonObject().entrySet());
111
112         if (entries.size() != 2) {
113           throw new CrudException("", Status.BAD_REQUEST);
114         }
115         Map.Entry<String, JsonElement> opr = entries.get(0);
116         Map.Entry<String, JsonElement> item = entries.get(1);
117
118         EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
119
120         if (opr.getValue().getAsString().equalsIgnoreCase("add")
121             || opr.getValue().getAsString().equalsIgnoreCase("modify")) {
122           Edge validatedEdge;
123           Edge persistedEdge;
124           if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
125             // Fix the source/detination
126             if (edgePayload.getSource().startsWith("$")) {
127               Vertex source = vertices.get(edgePayload.getSource().substring(1));
128               if (source == null) {
129                 throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1),
130                     Status.INTERNAL_SERVER_ERROR);
131               }
132               edgePayload
133                   .setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get());
134             }
135             if (edgePayload.getTarget().startsWith("$")) {
136               Vertex target = vertices.get(edgePayload.getTarget().substring(1));
137               if (target == null) {
138                 throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1),
139                     Status.INTERNAL_SERVER_ERROR);
140               }
141               edgePayload
142                   .setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get());
143             }
144             validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(),
145                 edgePayload);
146             persistedEdge = dao.addEdge(validatedEdge.getType(), validatedEdge.getSource(), validatedEdge.getTarget(),
147                 validatedEdge.getProperties(), txId);
148           } else {
149             Edge edge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId);
150             validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload);
151             persistedEdge = dao.updateEdge(edge, txId);
152           }
153
154           Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge);
155
156           edges.put(item.getKey(), outgoingEdge);
157
158         } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
159           RelationshipSchemaValidator.validateType(version, edgePayload.getType());
160           dao.deleteEdge(edgePayload.getId(), edgePayload.getType(), txId);
161         }
162
163       }
164       // close champ TX
165       dao.commitTransaction(txId);
166     } catch (CrudException ex) {
167       dao.rollbackTransaction(txId);
168       throw ex;
169     } catch (Exception ex) {
170       dao.rollbackTransaction(txId);
171       throw ex;
172     } finally {
173       if (dao.transactionExists(txId)) {
174         dao.rollbackTransaction(txId);
175       }
176     }
177
178     return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload);
179   }
180
181   private String addVertex(String version, Vertex vertex) throws CrudException {
182     Vertex addedVertex = dao.addVertex(vertex.getType(), vertex.getProperties());
183     return CrudResponseBuilder
184         .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, addedVertex), version);
185   }
186
187   public String addEdge(String version, String type, EdgePayload payload) throws CrudException {
188     Edge edge = RelationshipSchemaValidator.validateIncomingAddPayload(version, type, payload);
189     return addEdge(version, edge);
190   }
191
192   private String addEdge(String version, Edge edge) throws CrudException {
193     Edge addedEdge = dao.addEdge(edge.getType(), edge.getSource(), edge.getTarget(), edge.getProperties());
194     return CrudResponseBuilder
195         .buildUpsertEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, addedEdge), version);
196   }
197
198   public String getEdge(String version, String id, String type) throws CrudException {
199     RelationshipSchemaValidator.validateType(version, type);
200     Edge edge = dao.getEdge(id, type);
201
202     return CrudResponseBuilder.buildGetEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, edge),
203         version);
204   }
205
206   public String getEdges(String version, String type, Map<String, String> filter) throws CrudException {
207     RelationshipSchemaValidator.validateType(version, type);
208     List<Edge> items = dao.getEdges(type, RelationshipSchemaValidator.resolveCollectionfilter(version, type, filter));
209     return CrudResponseBuilder.buildGetEdgesResponse(items, version);
210   }
211
212   public String updateVertex(String version, String id, String type, VertexPayload payload) throws CrudException {
213     Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(id, version, type, payload.getProperties());
214     return updateVertex(version, vertex);
215
216   }
217
218   private String updateVertex(String version, Vertex vertex) throws CrudException {
219     Vertex updatedVertex = dao.updateVertex(vertex.getId().get(), vertex.getType(), vertex.getProperties());
220     return CrudResponseBuilder
221         .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, updatedVertex), version);
222   }
223
224   public String patchVertex(String version, String id, String type, VertexPayload payload) throws CrudException {
225     Vertex existingVertex = dao.getVertex(id, OxmModelValidator.resolveCollectionType(version, type));
226     Vertex vertex = OxmModelValidator.validateIncomingPatchPayload(id, version, type, payload.getProperties(),
227         existingVertex);
228     return updateVertex(version, vertex);
229
230   }
231
232   public String deleteVertex(String version, String id, String type) throws CrudException {
233     type = OxmModelValidator.resolveCollectionType(version, type);
234     dao.deleteVertex(id, type);
235     return "";
236
237   }
238
239   public String deleteEdge(String version, String id, String type) throws CrudException {
240     RelationshipSchemaValidator.validateType(version, type);
241     dao.deleteEdge(id, type);
242     return "";
243
244   }
245
246   public String updateEdge(String version, String id, String type, EdgePayload payload) throws CrudException {
247     Edge edge = dao.getEdge(id, type);
248     Edge validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, payload);
249     return updateEdge(version, validatedEdge);
250
251   }
252
253   private String updateEdge(String version, Edge edge) throws CrudException {
254     Edge updatedEdge = dao.updateEdge(edge);
255     return CrudResponseBuilder
256         .buildUpsertEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, updatedEdge), version);
257   }
258
259   public String patchEdge(String version, String id, String type, EdgePayload payload) throws CrudException {
260     Edge edge = dao.getEdge(id, type);
261     Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(edge, version, payload);
262     return updateEdge(version, patchedEdge);
263
264   }
265
266   public Vertex getVertex(String id) throws CrudException {
267     return dao.getVertex(id);
268   }
269
270   public String getVertex(String version, String id, String type) throws CrudException {
271     type = OxmModelValidator.resolveCollectionType(version, type);
272     Vertex vertex = dao.getVertex(id, type);
273     List<Edge> edges = dao.getVertexEdges(id);
274     return CrudResponseBuilder.buildGetVertexResponse(OxmModelValidator.validateOutgoingPayload(version, vertex), edges,
275         version);
276   }
277
278   public String getVertices(String version, String type, Map<String, String> filter) throws CrudException {
279     type = OxmModelValidator.resolveCollectionType(version, type);
280     List<Vertex> items = dao.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, type, filter));
281     return CrudResponseBuilder.buildGetVerticesResponse(items, version);
282   }
283
284 }