2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.crud.service;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonElement;
26 import com.google.gson.reflect.TypeToken;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
32 import javax.ws.rs.core.EntityTag;
33 import javax.ws.rs.core.HttpHeaders;
34 import javax.ws.rs.core.Response.Status;
35 import net.dongliu.gson.GsonJava8TypeAdapterFactory;
36 import org.apache.commons.lang3.tuple.ImmutablePair;
37 import org.onap.aai.restclient.client.OperationResult;
38 import org.onap.crud.dao.GraphDao;
39 import org.onap.crud.dao.champ.ChampEdgeSerializer;
40 import org.onap.crud.dao.champ.ChampVertexSerializer;
41 import org.onap.crud.entity.Edge;
42 import org.onap.crud.entity.Vertex;
43 import org.onap.crud.exception.CrudException;
44 import org.onap.crud.parser.CrudResponseBuilder;
45 import org.onap.crud.util.CrudServiceUtil;
46 import org.onap.schema.OxmModelValidator;
47 import org.onap.schema.RelationshipSchemaValidator;
49 public abstract class AbstractGraphDataService {
50 protected GraphDao daoForGet;
51 protected GraphDao dao;
53 public AbstractGraphDataService() throws CrudException {
56 public ImmutablePair<EntityTag, String> getEdge(String version, String id, String type, Map<String, String> queryParams) throws CrudException {
57 RelationshipSchemaValidator.validateType(version, type);
58 OperationResult operationResult = daoForGet.getEdge(id, type, queryParams);
59 EntityTag entityTag = CrudServiceUtil.getETagFromHeader(operationResult.getHeaders());
60 Edge edge = Edge.fromJson(operationResult.getResult());
61 return new ImmutablePair<>(entityTag, CrudResponseBuilder.buildGetEdgeResponse(RelationshipSchemaValidator.validateOutgoingPayload(version, edge), version));
64 public ImmutablePair<EntityTag, String> getEdges(String version, String type, Map<String, String> filter) throws CrudException {
65 Gson champGson = new GsonBuilder()
66 .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory())
67 .registerTypeAdapter(Vertex.class, new ChampVertexSerializer())
68 .registerTypeAdapter(Edge.class, new ChampEdgeSerializer()).create();
69 RelationshipSchemaValidator.validateType(version, type);
70 OperationResult operationResult = daoForGet.getEdges(type, RelationshipSchemaValidator.resolveCollectionfilter(version, type, filter));
71 List<Edge> items = champGson.fromJson(operationResult.getResult(), new TypeToken<List<Edge>>() {
73 EntityTag entityTag = CrudServiceUtil.getETagFromHeader(operationResult.getHeaders());
74 return new ImmutablePair<>(entityTag, CrudResponseBuilder.buildGetEdgesResponse(items, version));
77 public ImmutablePair<EntityTag, String> getVertex(String version, String id, String type, Map<String, String> queryParams) throws CrudException {
78 type = OxmModelValidator.resolveCollectionType(version, type);
79 OperationResult vertexOpResult = daoForGet.getVertex(id, type, version, queryParams);
80 Vertex vertex = Vertex.fromJson(vertexOpResult.getResult(), version);
81 List<Edge> edges = daoForGet.getVertexEdges(id, queryParams, null);
82 EntityTag entityTag = CrudServiceUtil.getETagFromHeader(vertexOpResult.getHeaders());
83 return new ImmutablePair<>(entityTag, CrudResponseBuilder.buildGetVertexResponse(OxmModelValidator.validateOutgoingPayload(version, vertex), edges,
87 public ImmutablePair<EntityTag, String> getVertices(String version, String type, Map<String, String> filter, Set<String> properties) throws CrudException {
88 type = OxmModelValidator.resolveCollectionType(version, type);
89 OperationResult operationResult = daoForGet.getVertices(type, OxmModelValidator.resolveCollectionfilter(version, type, filter), properties, version);
90 List<Vertex> vertices = Vertex.collectionFromJson(operationResult.getResult(), version);
91 EntityTag entityTag = CrudServiceUtil.getETagFromHeader(operationResult.getHeaders());
92 return new ImmutablePair<>(entityTag, CrudResponseBuilder.buildGetVerticesResponse(vertices, version));
95 public String addBulk(String version, BulkPayload payload, HttpHeaders headers) throws CrudException {
96 HashMap<String, Vertex> vertices = new HashMap<>();
97 HashMap<String, Edge> edges = new HashMap<>();
99 String txId = dao.openTransaction();
102 // Step 1. Handle edge deletes (must happen before vertex deletes)
103 for (JsonElement v : payload.getRelationships()) {
104 List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
105 v.getAsJsonObject().entrySet());
107 if (entries.size() != 2) {
108 throw new CrudException("", Status.BAD_REQUEST);
110 Map.Entry<String, JsonElement> opr = entries.get(0);
111 Map.Entry<String, JsonElement> item = entries.get(1);
112 EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
114 if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
115 deleteBulkEdge(edgePayload.getId(), version, txId);
119 // Step 2: Handle vertex deletes
120 for (JsonElement v : payload.getObjects()) {
121 List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
122 v.getAsJsonObject().entrySet());
124 if (entries.size() != 2) {
125 throw new CrudException("", Status.BAD_REQUEST);
128 Map.Entry<String, JsonElement> opr = entries.get(0);
129 Map.Entry<String, JsonElement> item = entries.get(1);
130 VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString());
132 if (opr.getValue().getAsString().equalsIgnoreCase("delete")) {
133 String type = OxmModelValidator.resolveCollectionType(version, vertexPayload.getType());
134 deleteBulkVertex(vertexPayload.getId(), version, type, txId);
138 // Step 3: Handle vertex add/modify (must happen before edge adds)
139 for (JsonElement v : payload.getObjects()) {
140 List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
141 v.getAsJsonObject().entrySet());
143 if (entries.size() != 2) {
144 throw new CrudException("", Status.BAD_REQUEST);
146 Map.Entry<String, JsonElement> opr = entries.get(0);
147 Map.Entry<String, JsonElement> item = entries.get(1);
148 VertexPayload vertexPayload = VertexPayload.fromJson(item.getValue().getAsJsonObject().toString());
151 if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
152 vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(),
154 Vertex validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(null, version, vertexPayload.getType(),
155 vertexPayload.getProperties());
156 Vertex persistedVertex = addBulkVertex(validatedVertex, version, txId);
157 Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
158 vertices.put(item.getKey(), outgoingVertex);
162 else if (opr.getValue().getAsString().equalsIgnoreCase("modify")) {
163 vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(),
165 Vertex validatedVertex = OxmModelValidator.validateIncomingUpsertPayload(vertexPayload.getId(), version,
166 vertexPayload.getType(), vertexPayload.getProperties());
167 Vertex persistedVertex = updateBulkVertex(validatedVertex, vertexPayload.getId(), version, txId);
168 Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
169 vertices.put(item.getKey(), outgoingVertex);
173 else if (opr.getValue().getAsString().equalsIgnoreCase("patch")) {
174 if ( (vertexPayload.getId() == null) || (vertexPayload.getType() == null) ) {
175 throw new CrudException("id and type must be specified for patch request", Status.BAD_REQUEST);
178 vertexPayload.setProperties(CrudServiceUtil.mergeHeaderInFoToPayload(vertexPayload.getProperties(),
181 OperationResult existingVertexOpResult = dao.getVertex(vertexPayload.getId(), OxmModelValidator.resolveCollectionType(version, vertexPayload.getType()), version, new HashMap<String, String>());
182 Vertex existingVertex = Vertex.fromJson(existingVertexOpResult.getResult(), version);
183 Vertex validatedVertex = OxmModelValidator.validateIncomingPatchPayload(vertexPayload.getId(),
184 version, vertexPayload.getType(), vertexPayload.getProperties(), existingVertex);
185 Vertex persistedVertex = updateBulkVertex(validatedVertex, vertexPayload.getId(), version, txId);
186 Vertex outgoingVertex = OxmModelValidator.validateOutgoingPayload(version, persistedVertex);
187 vertices.put(item.getKey(), outgoingVertex);
191 // Step 4: Handle edge add/modify
192 for (JsonElement v : payload.getRelationships()) {
193 List<Map.Entry<String, JsonElement>> entries = new ArrayList<Map.Entry<String, JsonElement>>(
194 v.getAsJsonObject().entrySet());
196 if (entries.size() != 2) {
197 throw new CrudException("", Status.BAD_REQUEST);
199 Map.Entry<String, JsonElement> opr = entries.get(0);
200 Map.Entry<String, JsonElement> item = entries.get(1);
201 EdgePayload edgePayload = EdgePayload.fromJson(item.getValue().getAsJsonObject().toString());
204 if (opr.getValue().getAsString().equalsIgnoreCase("add")
205 || opr.getValue().getAsString().equalsIgnoreCase("modify")
206 || opr.getValue().getAsString().equalsIgnoreCase("patch")) {
209 if (opr.getValue().getAsString().equalsIgnoreCase("add")) {
210 // Fix the source/destination
211 if (edgePayload.getSource().startsWith("$")) {
212 Vertex source = vertices.get(edgePayload.getSource().substring(1));
213 if (source == null) {
214 throw new CrudException("Not able to find vertex: " + edgePayload.getSource().substring(1),
215 Status.INTERNAL_SERVER_ERROR);
218 .setSource("services/inventory/" + version + "/" + source.getType() + "/" + source.getId().get());
220 if (edgePayload.getTarget().startsWith("$")) {
221 Vertex target = vertices.get(edgePayload.getTarget().substring(1));
222 if (target == null) {
223 throw new CrudException("Not able to find vertex: " + edgePayload.getTarget().substring(1),
224 Status.INTERNAL_SERVER_ERROR);
227 .setTarget("services/inventory/" + version + "/" + target.getType() + "/" + target.getId().get());
230 // If the type isn't set, resolve it based on on the sourece and target vertex types
231 if (edgePayload.getType() == null || edgePayload.getType().isEmpty()) {
232 edgePayload.setType(CrudServiceUtil.determineEdgeType(edgePayload, version));
235 validatedEdge = RelationshipSchemaValidator.validateIncomingAddPayload(version, edgePayload.getType(),edgePayload);
237 persistedEdge = addBulkEdge(validatedEdge, version, txId);
238 } else if (opr.getValue().getAsString().equalsIgnoreCase("modify")) {
239 Edge edge = dao.getEdge(edgePayload.getId(), txId);
241 // If the type isn't set, resolve it based on on the sourece and target vertex types
242 if (edgePayload.getType() == null || edgePayload.getType().isEmpty()) {
243 edgePayload.setType(edge.getType());
246 validatedEdge = RelationshipSchemaValidator.validateIncomingUpdatePayload(edge, version, edgePayload);
248 persistedEdge = updateBulkEdge(validatedEdge, version, txId);
250 if (edgePayload.getId() == null) {
251 throw new CrudException("id must be specified for patch request", Status.BAD_REQUEST);
253 Edge existingEdge = dao.getEdge(edgePayload.getId(), txId);
255 // If the type isn't set, resolve it based on on the sourece and target vertex types
256 if (edgePayload.getType() == null || edgePayload.getType().isEmpty()) {
257 edgePayload.setType(existingEdge.getType());
260 Edge patchedEdge = RelationshipSchemaValidator.validateIncomingPatchPayload(existingEdge, version, edgePayload);
261 persistedEdge = updateBulkEdge(patchedEdge, version, txId);
265 Edge outgoingEdge = RelationshipSchemaValidator.validateOutgoingPayload(version, persistedEdge);
266 edges.put(item.getKey(), outgoingEdge);
270 // commit transaction
271 dao.commitTransaction(txId);
272 } catch (CrudException ex) {
273 dao.rollbackTransaction(txId);
275 } catch (Exception ex) {
276 dao.rollbackTransaction(txId);
279 if (dao.transactionExists(txId)) {
280 dao.rollbackTransaction(txId);
284 return CrudResponseBuilder.buildUpsertBulkResponse(vertices, edges, version, payload);
288 public abstract ImmutablePair<EntityTag, String> addVertex(String version, String type, VertexPayload payload)
289 throws CrudException;
290 public abstract ImmutablePair<EntityTag, String> updateVertex(String version, String id, String type,
291 VertexPayload payload) throws CrudException;
292 public abstract ImmutablePair<EntityTag, String> patchVertex(String version, String id, String type,
293 VertexPayload payload) throws CrudException;
294 public abstract String deleteVertex(String version, String id, String type) throws CrudException;
295 public abstract ImmutablePair<EntityTag, String> addEdge(String version, String type, EdgePayload payload)
296 throws CrudException;
297 public abstract String deleteEdge(String version, String id, String type) throws CrudException;
298 public abstract ImmutablePair<EntityTag, String> updateEdge(String version, String id, String type,
299 EdgePayload payload) throws CrudException;
300 public abstract ImmutablePair<EntityTag, String> patchEdge(String version, String id, String type,
301 EdgePayload payload) throws CrudException;
303 protected abstract Vertex addBulkVertex(Vertex vertex, String version, String dbTransId) throws CrudException;
304 protected abstract Vertex updateBulkVertex(Vertex vertex, String id, String version, String dbTransId) throws CrudException;
305 protected abstract void deleteBulkVertex(String id, String version, String type, String dbTransId) throws CrudException;
307 protected abstract Edge addBulkEdge(Edge edge, String version, String dbTransId) throws CrudException;
308 protected abstract Edge updateBulkEdge(Edge edge, String version, String dbTransId) throws CrudException;
309 protected abstract void deleteBulkEdge(String id, String version, String dbTransId) throws CrudException;