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