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