Gizmo uses Champ the microservice
[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.aaiutils.oxm.OxmModelLoader;
34 import org.onap.crud.dao.GraphDao;
35 import org.onap.crud.entity.Edge;
36
37 import org.onap.crud.entity.Vertex;
38 import org.onap.crud.exception.CrudException;
39 import org.onap.crud.parser.CrudResponseBuilder;
40 import org.onap.schema.OxmModelValidator;
41 import org.onap.schema.RelationshipSchemaLoader;
42 import org.onap.schema.RelationshipSchemaValidator;
43
44 import com.google.gson.JsonElement;
45
46 public class CrudGraphDataService {
47
48   private GraphDao dao;
49
50   public CrudGraphDataService(GraphDao dao) throws CrudException {
51     this.dao = dao;
52
53     loadModels();
54   }
55
56   private void loadModels() throws CrudException {
57     // load the schemas
58     try {
59       OxmModelLoader.loadModels();
60     } catch (Exception e) {
61       throw new CrudException(e);
62     }
63     RelationshipSchemaLoader.loadModels();
64   }
65
66   public String addVertex(String version, String type, VertexPayload payload) throws CrudException {
67     Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, type, payload.getProperties());
68     return addVertex(version, vertex);
69   }
70
71   public String addBulk(String version, BulkPayload payload) throws CrudException {
72     HashMap<String, Vertex> vertices = new HashMap<String, Vertex>();
73     HashMap<String, Edge> edges = new HashMap<String, Edge>();
74     String txId = dao.openTransaction();
75     try {
76       // Handle vertices
77       for (JsonElement v : payload.getObjects()) {
78         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
79             v.getAsJsonObject().entrySet());
80
81         if (entries.size() != 2) {
82           throw new CrudException("", Status.BAD_REQUEST);
83         }
84         Map.Entry<String, JsonElement> opr = entries.get(0);
85         Map.Entry<String, JsonElement> item = entries.get(1);
86
87         VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString());
88
89         if (opr.getValue().getAsString().equalsIgnoreCase("add")
90             || opr.getValue().getAsString().equalsIgnoreCase("modify")) {
91           Vertex validatedVertex;
92           Vertex persistedVertex;
93           if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
94             validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, vertexPayload.getType(),
95                 vertexPayload.getProperties());
96             // Call champDAO to add the vertex
97             persistedVertex = dao.addVertex(validatedVertex.getType(), validatedVertex.getProperties(), txId);
98           } else {
99             validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(vertexPayload.getId(), version,
100                 vertexPayload.getType(), vertexPayload.getProperties());
101             // Call champDAO to update the vertex
102             persistedVertex = dao.updateVertex(vertexPayload.getId(), validatedVertex.getType(),
103                 validatedVertex.getProperties(), txId);
104           }
105
106           Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
107
108           vertices.put(item.getKey(), outgoingVertex);
109
110         } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
111           dao.deleteVertex(vertexPayload.getId(),
112               OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), txId);
113         }
114
115       }
116       // Handle Edges
117       for (JsonElement v : payload.getRelationships()) {
118         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
119             v.getAsJsonObject().entrySet());
120
121         if (entries.size() != 2) {
122           throw new CrudException("", Status.BAD_REQUEST);
123         }
124         Map.Entry<String, JsonElement> opr = entries.get(0);
125         Map.Entry<String, JsonElement> item = entries.get(1);
126
127         EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
128
129         if (opr.getValue().getAsString().equalsIgnoreCase("add")
130             || opr.getValue().getAsString().equalsIgnoreCase("modify")) {
131           Edge validatedEdge;
132           Edge persistedEdge;
133           if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
134             // Fix the source/detination
135             if (edgePayload.getSource().startsWith("$")) {
136               Vertex source = vertices.get(edgePayload.getSource().substring(1));
137               if (source == null) {
138                 throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1),
139                     Status.INTERNAL_SERVER_ERROR);
140               }
141               edgePayload
142                   .setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get());
143             }
144             if (edgePayload.getTarget().startsWith("$")) {
145               Vertex target = vertices.get(edgePayload.getTarget().substring(1));
146               if (target == null) {
147                 throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1),
148                     Status.INTERNAL_SERVER_ERROR);
149               }
150               edgePayload
151                   .setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get());
152             }
153             validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(),
154                 edgePayload);
155             persistedEdge = dao.addEdge(validatedEdge.getType(), validatedEdge.getSource(), validatedEdge.getTarget(),
156                 validatedEdge.getProperties(), txId);
157           } else {
158             Edge edge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId);
159             validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload);
160             persistedEdge = dao.updateEdge(edge, txId);
161           }
162
163           Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge);
164
165           edges.put(item.getKey(), outgoingEdge);
166
167         } else if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
168           RelationshipSchemaValidator.validateType(version, edgePayload.getType());
169           dao.deleteEdge(edgePayload.getId(), edgePayload.getType(), txId);
170         }
171
172       }
173       // close champ TX
174       dao.commitTransaction(txId);
175     } catch (CrudException ex) {
176       dao.rollbackTransaction(txId);
177       throw ex;
178     } catch (Exception ex) {
179       dao.rollbackTransaction(txId);
180       throw ex;
181     } finally {
182       if (dao.transactionExists(txId)) {
183         dao.rollbackTransaction(txId);
184       }
185     }
186
187     return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload);
188   }
189
190   private String addVertex(String version, Vertex vertex) throws CrudException {
191     Vertex addedVertex = dao.addVertex(vertex.getType(), vertex.getProperties());
192     return CrudResponseBuilder
193         .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, addedVertex), version);
194   }
195
196   public String addEdge(String version, String type, EdgePayload payload) throws CrudException {
197     Edge edge = RelationshipSchemaValidator.validateIncomingAddPayload(version, type, payload);
198     return addEdge(version, edge);
199   }
200
201   private String addEdge(String version, Edge edge) throws CrudException {
202     Edge addedEdge = dao.addEdge(edge.getType(), edge.getSource(), edge.getTarget(), edge.getProperties());
203     return CrudResponseBuilder
204         .buildUpsertEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, addedEdge), version);
205   }
206
207   public String getEdge(String version, String id, String type) throws CrudException {
208     RelationshipSchemaValidator.validateType(version, type);
209     Edge edge = dao.getEdge(id, type);
210
211     return CrudResponseBuilder.buildGetEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, edge),
212         version);
213   }
214
215   public String getEdges(String version, String type, Map<String, String> filter) throws CrudException {
216     RelationshipSchemaValidator.validateType(version, type);
217     List<Edge> items = dao.getEdges(type, RelationshipSchemaValidator.resolveCollectionfilter(version, type, filter));
218     return CrudResponseBuilder.buildGetEdgesResponse(items, version);
219   }
220
221   public String updateVertex(String version, String id, String type, VertexPayload payload) throws CrudException {
222     Vertex vertex = OxmModelValidator.validateIncomingUpsertPayload(id, version, type, payload.getProperties());
223     return updateVertex(version, vertex);
224
225   }
226
227   private String updateVertex(String version, Vertex vertex) throws CrudException {
228     Vertex updatedVertex = dao.updateVertex(vertex.getId().get(), vertex.getType(), vertex.getProperties());
229     return CrudResponseBuilder
230         .buildUpsertVertexResponse(OxmModelValidator.validateOutgoingPayload(version, updatedVertex), version);
231   }
232
233   public String patchVertex(String version, String id, String type, VertexPayload payload) throws CrudException {
234     Vertex existingVertex = dao.getVertex(id, OxmModelValidator.resolveCollectionType(version, type));
235     Vertex vertex = OxmModelValidator.validateIncomingPatchPayload(id, version, type, payload.getProperties(),
236         existingVertex);
237     return updateVertex(version, vertex);
238
239   }
240
241   public String deleteVertex(String version, String id, String type) throws CrudException {
242     type = OxmModelValidator.resolveCollectionType(version, type);
243     dao.deleteVertex(id, type);
244     return "";
245
246   }
247
248   public String deleteEdge(String version, String id, String type) throws CrudException {
249     RelationshipSchemaValidator.validateType(version, type);
250     dao.deleteEdge(id, type);
251     return "";
252
253   }
254
255   public String updateEdge(String version, String id, String type, EdgePayload payload) throws CrudException {
256     Edge edge = dao.getEdge(id, type);
257     Edge validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, payload);
258     return updateEdge(version, validatedEdge);
259
260   }
261
262   private String updateEdge(String version, Edge edge) throws CrudException {
263     Edge updatedEdge = dao.updateEdge(edge);
264     return CrudResponseBuilder
265         .buildUpsertEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, updatedEdge), version);
266   }
267
268   public String patchEdge(String version, String id, String type, EdgePayload payload) throws CrudException {
269     Edge edge = dao.getEdge(id, type);
270     Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(edge, version, payload);
271     return updateEdge(version, patchedEdge);
272
273   }
274
275   public Vertex getVertex(String id) throws CrudException {
276     return dao.getVertex(id);
277   }
278
279   public String getVertex(String version, String id, String type) throws CrudException {
280     type = OxmModelValidator.resolveCollectionType(version, type);
281     Vertex vertex = dao.getVertex(id, type);
282     List<Edge> edges = dao.getVertexEdges(id);
283     return CrudResponseBuilder.buildGetVertexResponse(OxmModelValidator.validateOutgoingPayload(version, vertex), edges,
284         version);
285   }
286
287   public String getVertices(String version, String type, Map<String, String> filter) throws CrudException {
288     type = OxmModelValidator.resolveCollectionType(version, type);
289     List<Vertex> items = dao.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, type, filter));
290     return CrudResponseBuilder.buildGetVerticesResponse(items, version);
291   }
292
293 }