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