Update license date and text
[aai/gizmo.git] / src / main / java / org / onap / crud / service / AbstractGraphDataService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.crud.service;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.ws.rs.core.HttpHeaders;
30 import javax.ws.rs.core.Response.Status;
31
32 import org.onap.crud.dao.GraphDao;
33 import org.onap.crud.entity.Edge;
34 import org.onap.crud.entity.Vertex;
35 import org.onap.crud.exception.CrudException;
36 import org.onap.crud.parser.CrudResponseBuilder;
37 import org.onap.crud.util.CrudServiceUtil;
38 import org.onap.schema.OxmModelValidator;
39 import org.onap.schema.RelationshipSchemaValidator;
40
41 import com.google.gson.JsonElement;
42
43 public abstract class AbstractGraphDataService {
44   protected GraphDao daoForGet;
45   protected GraphDao dao;
46   
47   public AbstractGraphDataService() throws CrudException {
48     CrudServiceUtil.loadModels();
49   }
50
51   public String getEdge(String version, String id, String type, Map<String, String> queryParams) throws CrudException {
52     RelationshipSchemaValidator.validateType(version, type);
53     Edge edge = daoForGet.getEdge(id, type, queryParams);
54
55     return CrudResponseBuilder.buildGetEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, edge), version);
56   }
57   
58   public String getEdges(String version, String type, Map<String, String> filter) throws CrudException {
59     RelationshipSchemaValidator.validateType(version, type);
60     List<Edge> items = daoForGet.getEdges(type, RelationshipSchemaValidator.resolveCollectionfilter(version, type, filter));
61     return CrudResponseBuilder.buildGetEdgesResponse(items, version);
62   }
63   
64   public String getVertex(String version, String id, String type, Map<String, String> queryParams) throws CrudException {
65     type = OxmModelValidator.resolveCollectionType(version, type);
66     Vertex vertex = daoForGet.getVertex(id, type, version, queryParams);
67     List<Edge> edges = daoForGet.getVertexEdges(id, queryParams);
68     return CrudResponseBuilder.buildGetVertexResponse(OxmModelValidator.validateOutgoingPayload(version, vertex), edges,
69         version);
70   }
71
72   public String getVertices(String version, String type, Map<String, String> filter, HashSet<String> properties) throws CrudException {
73     type = OxmModelValidator.resolveCollectionType(version, type);
74     List<Vertex> items = daoForGet.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, type, filter), properties, version);
75     return CrudResponseBuilder.buildGetVerticesResponse(items, version);
76   }
77   
78   public String addBulk(String version, BulkPayload payload, HttpHeaders headers) throws CrudException {
79     HashMap<String, Vertex> vertices = new HashMap<String, Vertex>();
80     HashMap<String, Edge> edges = new HashMap<String, Edge>();
81     
82     String txId = dao.openTransaction();   
83      
84     try {
85       // Step 1. Handle edge deletes (must happen before vertex deletes)
86       for (JsonElement v : payload.getRelationships()) {
87         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
88             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         EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
96
97         if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
98           RelationshipSchemaValidator.validateType(version, edgePayload.getType());
99           deleteBulkEdge(edgePayload.getId(), version, edgePayload.getType(), txId);
100         }
101       } 
102       
103       // Step 2: Handle vertex deletes
104       for (JsonElement v : payload.getObjects()) {
105         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
106             v.getAsJsonObject().entrySet());
107
108         if (entries.size() != 2) {
109           throw new CrudException("", Status.BAD_REQUEST);
110         }
111
112         Map.Entry<String, JsonElement> opr = entries.get(0);
113         Map.Entry<String, JsonElement> item = entries.get(1);
114         VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString());
115
116         if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
117           String type = OxmModelValidator.resolveCollectionType(version, vertexPayload.getType());
118           deleteBulkVertex(vertexPayload.getId(), version, type, txId);
119         }
120       }
121       
122       // Step 3: Handle vertex add/modify (must happen before edge adds)
123       for (JsonElement v : payload.getObjects()) {
124         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
125             v.getAsJsonObject().entrySet());
126
127         if (entries.size() != 2) {
128           throw new CrudException("", Status.BAD_REQUEST);
129         }
130         Map.Entry<String, JsonElement> opr = entries.get(0);
131         Map.Entry<String, JsonElement> item = entries.get(1);
132         VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString());
133         
134         // Add vertex
135         if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
136           vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(), 
137               headers, true));  
138           Vertex validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, vertexPayload.getType(),
139               vertexPayload.getProperties());
140           Vertex persistedVertex = addBulkVertex(validatedVertex, version, txId);
141           Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
142           vertices.put(item.getKey(), outgoingVertex);
143         }
144         
145         // Update vertex 
146         else if (opr.getValue().getAsString().equalsIgnoreCase("modify")) {
147           vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(), 
148               headers, false));
149           Vertex validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(vertexPayload.getId(), version,
150               vertexPayload.getType(), vertexPayload.getProperties());
151           Vertex persistedVertex = updateBulkVertex(validatedVertex, vertexPayload.getId(), version, txId);
152           Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
153           vertices.put(item.getKey(), outgoingVertex);
154         }
155         
156         // Patch vertex 
157         else if (opr.getValue().getAsString().equalsIgnoreCase("patch")) {
158           if ( (vertexPayload.getId() == null) || (vertexPayload.getType() == null) ) {
159             throw new CrudException("id and type must be specified for patch request", Status.BAD_REQUEST);
160           }
161           
162           vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(), 
163               headers, false));
164           
165           Vertex existingVertex = dao.getVertex(vertexPayload.getId(), OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), version, new HashMap<String, String>());
166           Vertex validatedVertex = OxmModelValidator.validateIncomingPatchPayload(vertexPayload.getId(), 
167               version, vertexPayload.getType(), vertexPayload.getProperties(), existingVertex);
168           Vertex persistedVertex = updateBulkVertex(validatedVertex, vertexPayload.getId(), version, txId);
169           Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
170           vertices.put(item.getKey(), outgoingVertex);
171         }
172       }
173
174       // Step 4: Handle edge add/modify 
175       for (JsonElement v : payload.getRelationships()) {
176         List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
177             v.getAsJsonObject().entrySet());
178
179         if (entries.size() != 2) {
180           throw new CrudException("", Status.BAD_REQUEST);
181         }
182         Map.Entry<String, JsonElement> opr = entries.get(0);
183         Map.Entry<String, JsonElement> item = entries.get(1);
184         EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
185
186         // Add/Update edge
187         if (opr.getValue().getAsString().equalsIgnoreCase("add")
188             || opr.getValue().getAsString().equalsIgnoreCase("modify") 
189             || opr.getValue().getAsString().equalsIgnoreCase("patch")) {
190           Edge validatedEdge;
191           Edge persistedEdge;
192           if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
193             // Fix the source/destination
194             if (edgePayload.getSource().startsWith("$")) {
195               Vertex source = vertices.get(edgePayload.getSource().substring(1));
196               if (source == null) {
197                 throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1),
198                     Status.INTERNAL_SERVER_ERROR);
199               }
200               edgePayload
201                   .setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get());
202             }
203             if (edgePayload.getTarget().startsWith("$")) {
204               Vertex target = vertices.get(edgePayload.getTarget().substring(1));
205               if (target == null) {
206                 throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1),
207                     Status.INTERNAL_SERVER_ERROR);
208               }
209               edgePayload
210                   .setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get());
211             }
212             validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(),
213                 edgePayload);
214             persistedEdge = addBulkEdge(validatedEdge, version, txId);
215           } else if (opr.getValue().getAsString().equalsIgnoreCase("modify")) {
216             Edge edge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId);
217             validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload);
218             persistedEdge = updateBulkEdge(validatedEdge, version, txId);
219           } else {
220             if ( (edgePayload.getId() == null) || (edgePayload.getType() == null) ) {
221               throw new CrudException("id and type must be specified for patch request", Status.BAD_REQUEST);
222             }
223             Edge existingEdge = dao.getEdge(edgePayload.getId(), edgePayload.getType(), txId);
224             Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(existingEdge, version, edgePayload);
225             persistedEdge = updateBulkEdge(patchedEdge, version, txId);
226           }
227           
228
229           Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge);
230           edges.put(item.getKey(), outgoingEdge);
231         } 
232       } 
233       
234       // commit transaction
235       dao.commitTransaction(txId);
236     } catch (CrudException ex) {
237       dao.rollbackTransaction(txId);
238       throw ex;
239     } catch (Exception ex) {
240       dao.rollbackTransaction(txId);
241       throw ex;
242     } finally {
243       if (dao.transactionExists(txId)) {
244         dao.rollbackTransaction(txId);
245       }
246     }
247     
248     return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload);
249   }
250
251
252   public abstract String addVertex(String version, String type, VertexPayload payload) throws CrudException;
253   public abstract String updateVertex(String version, String id, String type, VertexPayload payload) throws CrudException;
254   public abstract String patchVertex(String version, String id, String type, VertexPayload payload) throws CrudException;
255   public abstract String deleteVertex(String version, String id, String type) throws CrudException;
256   public abstract String addEdge(String version, String type, EdgePayload payload) throws CrudException;
257   public abstract String deleteEdge(String version, String id, String type) throws CrudException;
258   public abstract String updateEdge(String version, String id, String type, EdgePayload payload) throws CrudException;
259   public abstract String patchEdge(String version, String id, String type, EdgePayload payload) throws CrudException;
260   
261   protected abstract Vertex addBulkVertex(Vertex vertex, String version, String dbTransId) throws CrudException;
262   protected abstract Vertex updateBulkVertex(Vertex vertex, String id, String version, String dbTransId) throws CrudException;
263   protected abstract void deleteBulkVertex(String id, String version, String type, String dbTransId) throws CrudException;
264   
265   protected abstract Edge addBulkEdge(Edge edge, String version, String dbTransId) throws CrudException;
266   protected abstract Edge updateBulkEdge(Edge edge, String version, String dbTransId) throws CrudException;
267   protected abstract void deleteBulkEdge(String id, String version, String type, String dbTransId) throws CrudException;
268   
269 }