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