5a8922004664651769150616276521c51bdebf92
[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.HashSet;
29 import java.util.List;
30 import java.util.Map;
31
32 import javax.ws.rs.core.HttpHeaders;
33 import javax.ws.rs.core.Response.Status;
34
35 import org.onap.crud.dao.GraphDao;
36 import org.onap.crud.entity.Edge;
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 abstract class AbstractGraphDataService {
47   protected GraphDao daoForGet;
48   protected GraphDao dao;
49   
50   public AbstractGraphDataService() throws CrudException {
51     CrudServiceUtil.loadModels();
52   }
53
54   public String getEdge(String version, String id, String type, Map<String, String> queryParams) throws CrudException {
55     RelationshipSchemaValidator.validateType(version, type);
56     Edge edge = daoForGet.getEdge(id, type, queryParams);
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 = daoForGet.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, Map<String, String> queryParams) throws CrudException {
68     type = OxmModelValidator.resolveCollectionType(version, type);
69     Vertex vertex = daoForGet.getVertex(id, type, version, queryParams);
70     List<Edge> edges = daoForGet.getVertexEdges(id, queryParams);
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, HashSet<String> properties) throws CrudException {
76     type = OxmModelValidator.resolveCollectionType(version, type);
77     List<Vertex> items = daoForGet.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, type, filter), properties, version);
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         // Patch vertex 
160         else if (opr.getValue().getAsString().equalsIgnoreCase("patch")) {
161           if ( (vertexPayload.getId() == null) || (vertexPayload.getType() == null) ) {
162             throw new CrudException("id and type must be specified for patch request", Status.BAD_REQUEST);
163           }
164           
165           vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(), 
166               headers, false));
167           
168           Vertex existingVertex = dao.getVertex(vertexPayload.getId(), OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), version, new HashMap<String, String>());
169           Vertex validatedVertex = OxmModelValidator.validateIncomingPatchPayload(vertexPayload.getId(), 
170               version, vertexPayload.getType(), vertexPayload.getProperties(), existingVertex);
171           Vertex persistedVertex = updateBulkVertex(validatedVertex, vertexPayload.getId(), version, txId);
172           Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
173           vertices.put(item.getKey(), outgoingVertex);
174         }
175       }
176
177       // Step 4: Handle edge add/modify 
178       for (JsonElement v : payload.getRelationships()) {
179         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
180             v.getAsJsonObject().entrySet());
181
182         if (entries.size() != 2) {
183           throw new CrudException("", Status.BAD_REQUEST);
184         }
185         Map.Entry<String, JsonElement> opr = entries.get(0);
186         Map.Entry<String, JsonElement> item = entries.get(1);
187         EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
188
189         // Add/Update edge
190         if (opr.getValue().getAsString().equalsIgnoreCase("add")
191             || opr.getValue().getAsString().equalsIgnoreCase("modify") 
192             || opr.getValue().getAsString().equalsIgnoreCase("patch")) {
193           Edge validatedEdge;
194           Edge persistedEdge;
195           if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
196             // Fix the source/destination
197             if (edgePayload.getSource().startsWith("$")) {
198               Vertex source = vertices.get(edgePayload.getSource().substring(1));
199               if (source == null) {
200                 throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1),
201                     Status.INTERNAL_SERVER_ERROR);
202               }
203               edgePayload
204                   .setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get());
205             }
206             if (edgePayload.getTarget().startsWith("$")) {
207               Vertex target = vertices.get(edgePayload.getTarget().substring(1));
208               if (target == null) {
209                 throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1),
210                     Status.INTERNAL_SERVER_ERROR);
211               }
212               edgePayload
213                   .setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get());
214             }
215             validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(),
216                 edgePayload);
217             persistedEdge = addBulkEdge(validatedEdge, version, txId);
218           } else if (opr.getValue().getAsString().equalsIgnoreCase("modify")) {
219             Edge edge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId);
220             validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload);
221             persistedEdge = updateBulkEdge(validatedEdge, version, txId);
222           } else {
223             if ( (edgePayload.getId() == null) || (edgePayload.getType() == null) ) {
224               throw new CrudException("id and type must be specified for patch request", Status.BAD_REQUEST);
225             }
226             Edge existingEdge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId);
227             Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(existingEdge, version, edgePayload);
228             persistedEdge = updateBulkEdge(patchedEdge, version, txId);
229           }
230           
231
232           Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge);
233           edges.put(item.getKey(), outgoingEdge);
234         } 
235       } 
236       
237       // commit transaction
238       dao.commitTransaction(txId);
239     } catch (CrudException ex) {
240       dao.rollbackTransaction(txId);
241       throw ex;
242     } catch (Exception ex) {
243       dao.rollbackTransaction(txId);
244       throw ex;
245     } finally {
246       if (dao.transactionExists(txId)) {
247         dao.rollbackTransaction(txId);
248       }
249     }
250     
251     return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload);
252   }
253
254
255   public abstract String addVertex(String version, String type, VertexPayload payload) throws CrudException;
256   public abstract String updateVertex(String version, String id, String type, VertexPayload payload) throws CrudException;
257   public abstract String patchVertex(String version, String id, String type, VertexPayload payload) throws CrudException;
258   public abstract String deleteVertex(String version, String id, String type) throws CrudException;
259   public abstract String addEdge(String version, String type, EdgePayload payload) throws CrudException;
260   public abstract String deleteEdge(String version, String id, String type) throws CrudException;
261   public abstract String updateEdge(String version, String id, String type, EdgePayload payload) throws CrudException;
262   public abstract String patchEdge(String version, String id, String type, EdgePayload payload) throws CrudException;
263   
264   protected abstract Vertex addBulkVertex(Vertex vertex, String version, String dbTransId) throws CrudException;
265   protected abstract Vertex updateBulkVertex(Vertex vertex, String id, String version, String dbTransId) throws CrudException;
266   protected abstract void deleteBulkVertex(String id, String version, String type, String dbTransId) throws CrudException;
267   
268   protected abstract Edge addBulkEdge(Edge edge, String version, String dbTransId) throws CrudException;
269   protected abstract Edge updateBulkEdge(Edge edge, String version, String dbTransId) throws CrudException;
270   protected abstract void deleteBulkEdge(String id, String version, String type, String dbTransId) throws CrudException;
271   
272 }