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