2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 package org.onap.crud.dao.champ;
26 import net.dongliu.gson.GsonJava8TypeAdapterFactory;
28 import com.google.gson.Gson;
29 import com.google.gson.GsonBuilder;
30 import com.google.gson.reflect.TypeToken;
32 import org.apache.http.NameValuePair;
33 import org.apache.http.client.utils.URLEncodedUtils;
34 import org.apache.http.message.BasicNameValuePair;
35 import org.eclipse.jetty.util.security.Password;
36 import org.onap.aai.logging.LoggingContext;
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.crud.dao.GraphDao;
40 import org.onap.crud.entity.Edge;
41 import org.onap.crud.entity.Vertex;
42 import org.onap.crud.exception.CrudException;
43 import org.onap.crud.util.CrudServiceConstants;
44 import org.onap.aai.restclient.client.OperationResult;
45 import org.onap.aai.restclient.client.RestClient;
46 import org.onap.aai.restclient.enums.RestAuthenticationMode;
49 import java.nio.charset.Charset;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.HashMap;
53 import java.util.HashSet;
54 import java.util.List;
56 import javax.ws.rs.core.MediaType;
57 import javax.ws.rs.core.Response;
59 public class ChampDao implements GraphDao {
60 private RestClient client;
61 private String baseObjectUrl;
62 private String baseRelationshipUrl;
63 private String baseTransactionUrl;
65 private static final String HEADER_FROM_APP = "X-FromAppId";
66 private static final String HEADER_TRANS_ID = "X-TransactionId";
67 private static final String FROM_APP_NAME = "Gizmo";
68 private static final String OBJECT_SUB_URL = "objects";
69 private static final String RELATIONSHIP_SUB_URL = "relationships";
70 private static final String TRANSACTION_SUB_URL = "transaction";
72 private Logger logger = LoggerFactory.getInstance().getLogger(ChampDao.class.getName());
74 // We use a custom vertex serializer for champ because it expects "key"
76 private static final Gson champGson = new GsonBuilder()
77 .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory())
78 .registerTypeAdapter(Vertex.class, new ChampVertexSerializer())
79 .registerTypeAdapter(Edge.class, new ChampEdgeSerializer()).create();
81 public ChampDao(String champUrl, String certPassword) {
83 client = new RestClient().authenticationMode(RestAuthenticationMode.SSL_CERT).validateServerHostname(false)
84 .validateServerCertChain(false).clientCertFile(CrudServiceConstants.CRD_CHAMP_AUTH_FILE)
85 .clientCertPassword(Password.deobfuscate(certPassword));
87 baseObjectUrl = champUrl + OBJECT_SUB_URL;
88 baseRelationshipUrl = champUrl + RELATIONSHIP_SUB_URL;
89 baseTransactionUrl = champUrl + TRANSACTION_SUB_URL;
90 } catch (Exception e) {
91 System.out.println("Error setting up Champ configuration");
98 public Vertex getVertex(String id) throws CrudException {
99 String url = baseObjectUrl + "/" + id;
100 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
102 if (getResult.getResultCode() == 200) {
103 return Vertex.fromJson(getResult.getResult());
105 // We didn't find a vertex with the supplied id, so just throw an
107 throw new CrudException("No vertex with id " + id + " found in graph",
108 javax.ws.rs.core.Response.Status.NOT_FOUND);
113 public Vertex getVertex(String id, String type) throws CrudException {
114 String url = baseObjectUrl + "/" + id;
115 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
117 if (getResult.getResultCode() == 200) {
118 Vertex vert = Vertex.fromJson(getResult.getResult());
120 if (!vert.getType().equalsIgnoreCase(type)) {
121 // We didn't find a vertex with the supplied type, so just throw an
123 throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph",
124 javax.ws.rs.core.Response.Status.NOT_FOUND);
128 // We didn't find a vertex with the supplied id, so just throw an
130 throw new CrudException("No vertex with id " + id + " found in graph",
131 javax.ws.rs.core.Response.Status.NOT_FOUND);
136 public List<Edge> getVertexEdges(String id) throws CrudException {
137 String url = baseObjectUrl + "/relationships/" + id;
139 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
141 if (getResult.getResultCode() == 200) {
142 return champGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() {
145 // We didn't find a vertex with the supplied id, so just throw an
147 throw new CrudException("No vertex with id " + id + " found in graph",
148 javax.ws.rs.core.Response.Status.NOT_FOUND);
153 public List<Vertex> getVertices(String type, Map<String, Object> filter) throws CrudException {
154 return getVertices(type, filter, new HashSet<String>());
158 public List<Vertex> getVertices(String type, Map<String, Object> filter, HashSet<String> properties) throws CrudException {
159 filter.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
161 List<NameValuePair> queryParams = convertToNameValuePair(filter);
162 queryParams.addAll(convertToNameValuePair("properties", properties));
163 String url = baseObjectUrl + "/filter" + "?"
164 + URLEncodedUtils.format(queryParams, Charset.defaultCharset());
166 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
168 if (getResult.getResultCode() == 200) {
169 return champGson.fromJson(getResult.getResult(), new TypeToken<List<Vertex>>() {
172 // We didn't find a vertex with the supplied id, so just throw an
174 throw new CrudException("No vertices found in graph for given filters",
175 javax.ws.rs.core.Response.Status.NOT_FOUND);
180 public Edge getEdge(String id, String type) throws CrudException {
181 String url = baseRelationshipUrl + "/" + id;
182 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
184 if (getResult.getResultCode() == 200) {
185 Edge edge = Edge.fromJson(getResult.getResult());
187 if (!edge.getType().equalsIgnoreCase(type)) {
188 // We didn't find an edge with the supplied type, so just throw an
190 throw new CrudException("No edge with id " + id + "and type " + type + " found in graph",
191 javax.ws.rs.core.Response.Status.NOT_FOUND);
195 // We didn't find a edge with the supplied type, so just throw an
197 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
202 public List<Edge> getEdges(String type, Map<String, Object> filter) throws CrudException {
203 String url = baseRelationshipUrl + "/filter" + "?"
204 + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset());
206 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
208 if (getResult.getResultCode() == 200) {
209 return champGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() {
212 // We didn't find a vertex with the supplied id, so just throw an
214 throw new CrudException("No edges found in graph for given filters", javax.ws.rs.core.Response.Status.NOT_FOUND);
219 public Vertex addVertex(String type, Map<String, Object> properties) throws CrudException {
220 String url = baseObjectUrl;
222 // Add the aai_node_type so that AAI can read the data created by gizmo
223 // TODO: This probably shouldn't be here
224 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
226 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
227 properties.forEach(insertVertexBuilder::property);
228 Vertex insertVertex = insertVertexBuilder.build();
230 OperationResult getResult = client.post(url, insertVertex.toJson(), createHeader(), MediaType.APPLICATION_JSON_TYPE,
231 MediaType.APPLICATION_JSON_TYPE);
233 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
234 return Vertex.fromJson(getResult.getResult());
236 // We didn't create a vertex with the supplied type, so just throw an
238 throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
243 public Vertex updateVertex(String id, String type, Map<String, Object> properties) throws CrudException {
244 String url = baseObjectUrl + "/" + id;
246 // Add the aai_node_type so that AAI can read the data created by gizmo
247 // TODO: This probably shouldn't be here
248 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
250 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
251 insertVertexBuilder.id(id);
252 properties.forEach(insertVertexBuilder::property);
253 Vertex insertVertex = insertVertexBuilder.build();
255 String payload = insertVertex.toJson(champGson);
256 OperationResult getResult = client.put(url, payload, createHeader(), MediaType.APPLICATION_JSON_TYPE,
257 MediaType.APPLICATION_JSON_TYPE);
259 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
260 return Vertex.fromJson(getResult.getResult());
262 // We didn't create a vertex with the supplied type, so just throw an
264 throw new CrudException("Failed to update vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
269 public void deleteVertex(String id, String type) throws CrudException {
270 String url = baseObjectUrl + "/" + id;
271 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
273 if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) {
274 // We didn't delete a vertex with the supplied id, so just throw an
276 throw new CrudException("Failed to delete vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
281 public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties) throws CrudException {
282 String url = baseRelationshipUrl;
284 // Try requests to ensure source and target exist in Champ
285 Vertex dbSource = getVertex(source.getId().get(), source.getType());
286 Vertex dbTarget = getVertex(target.getId().get(), target.getType());
288 Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget);
289 properties.forEach(insertEdgeBuilder::property);
290 Edge insertEdge = insertEdgeBuilder.build();
292 String edgeJson = insertEdge.toJson(champGson);
293 OperationResult getResult = client.post(url, edgeJson, createHeader(), MediaType.APPLICATION_JSON_TYPE,
294 MediaType.APPLICATION_JSON_TYPE);
296 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
297 return Edge.fromJson(getResult.getResult());
299 // We didn't create an edge with the supplied type, so just throw an
301 throw new CrudException("Failed to create edge", Response.Status.fromStatusCode(getResult.getResultCode()));
306 public Edge updateEdge(Edge edge) throws CrudException {
307 if (!edge.getId().isPresent()) {
308 throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST);
310 String url = baseRelationshipUrl + "/" + edge.getId().get();
312 String edgeJson = edge.toJson(champGson);
313 OperationResult getResult = client.put(url, edgeJson, createHeader(), MediaType.APPLICATION_JSON_TYPE,
314 MediaType.APPLICATION_JSON_TYPE);
316 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
317 return Edge.fromJson(getResult.getResult());
319 // We didn't create an edge with the supplied type, so just throw an
321 throw new CrudException("Failed to update edge", Response.Status.fromStatusCode(getResult.getResultCode()));
326 public void deleteEdge(String id, String type) throws CrudException {
327 String url = baseRelationshipUrl + "/" + id;
328 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
330 if (getResult.getResultCode() != 200) {
331 // We didn't find an edge with the supplied type, so just throw an
333 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
338 public String openTransaction() {
339 String url = baseTransactionUrl;
341 OperationResult getResult = client.post(url, "", createHeader(), MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_PLAIN_TYPE);
343 if (getResult.getResultCode() == 200) {
344 return getResult.getResult();
351 public void commitTransaction(String id) throws CrudException {
352 String url = baseTransactionUrl + "/" + id;
354 OperationResult getResult = client.put(url, "{\"method\": \"commit\"}", createHeader(), MediaType.APPLICATION_JSON_TYPE,
355 MediaType.TEXT_PLAIN_TYPE);
357 if (getResult.getResultCode() != 200) {
358 throw new CrudException("Unable to commit transaction",
359 Response.Status.fromStatusCode(getResult.getResultCode()));
364 public void rollbackTransaction(String id) throws CrudException {
365 String url = baseTransactionUrl + "/" + id;
367 OperationResult getResult = client.put(url, "{\"method\": \"rollback\"}", createHeader(), MediaType.APPLICATION_JSON_TYPE,
368 MediaType.TEXT_PLAIN_TYPE);
370 if (getResult.getResultCode() != 200) {
371 throw new CrudException("Unable to rollback transaction",
372 Response.Status.fromStatusCode(getResult.getResultCode()));
377 public boolean transactionExists(String id) throws CrudException {
378 String url = baseTransactionUrl + "/" + id;
379 Map<String, List<String>> headers = new HashMap<>();
380 headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo"));
381 headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString())));
383 OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE);
385 return getResult.getResultCode() == 200;
389 public Vertex addVertex(String type, Map<String, Object> properties, String txId) throws CrudException {
390 String url = baseObjectUrl + "?transactionId=" + txId;
392 // Add the aai_node_type so that AAI can read the data created by gizmo
393 // TODO: This probably shouldn't be here
394 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
396 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
397 properties.forEach(insertVertexBuilder::property);
398 Vertex insertVertex = insertVertexBuilder.build();
400 OperationResult getResult = client.post(url, insertVertex.toJson(), createHeader(), MediaType.APPLICATION_JSON_TYPE,
401 MediaType.APPLICATION_JSON_TYPE);
403 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
404 return Vertex.fromJson(getResult.getResult());
406 // We didn't create a vertex with the supplied type, so just throw an
408 throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
413 public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties, String txId)
414 throws CrudException {
415 String url = baseRelationshipUrl + "?transactionId=" + txId;
417 // Try requests to ensure source and target exist in Champ
418 Vertex dbSource = getVertex(source.getId().get(), source.getType(), txId);
419 Vertex dbTarget = getVertex(target.getId().get(), target.getType(), txId);
421 Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget);
422 properties.forEach(insertEdgeBuilder::property);
423 Edge insertEdge = insertEdgeBuilder.build();
425 OperationResult getResult = client.post(url, insertEdge.toJson(champGson), createHeader(),
426 MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
428 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
429 return Edge.fromJson(getResult.getResult());
431 // We didn't create an edge with the supplied type, so just throw an
433 throw new CrudException("Failed to create edge", Response.Status.fromStatusCode(getResult.getResultCode()));
438 public Vertex updateVertex(String id, String type, Map<String, Object> properties, String txId) throws CrudException {
439 String url = baseObjectUrl + "/" + id + "?transactionId=" + txId;
441 // Add the aai_node_type so that AAI can read the data created by gizmo
442 // TODO: This probably shouldn't be here
443 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
445 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
446 insertVertexBuilder.id(id);
447 properties.forEach(insertVertexBuilder::property);
448 Vertex insertVertex = insertVertexBuilder.build();
450 String payload = insertVertex.toJson(champGson);
451 OperationResult getResult = client.put(url, payload, createHeader(), MediaType.APPLICATION_JSON_TYPE,
452 MediaType.APPLICATION_JSON_TYPE);
454 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
455 return Vertex.fromJson(getResult.getResult());
457 // We didn't create a vertex with the supplied type, so just throw an
459 throw new CrudException("Failed to update vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
464 public void deleteVertex(String id, String type, String txId) throws CrudException {
465 String url = baseObjectUrl + "/" + id + "?transactionId=" + txId;
466 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
468 if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) {
469 // We didn't delete a vertex with the supplied id, so just throw an
471 throw new CrudException("Failed to delete vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
476 public Edge updateEdge(Edge edge, String txId) throws CrudException {
477 if (!edge.getId().isPresent()) {
478 throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST);
480 String url = baseRelationshipUrl + "/" + edge.getId().get() + "?transactionId=" + txId;
481 OperationResult getResult = client.put(url, edge.toJson(champGson), createHeader(), MediaType.APPLICATION_JSON_TYPE,
482 MediaType.APPLICATION_JSON_TYPE);
484 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
485 return Edge.fromJson(getResult.getResult());
487 // We didn't create an edge with the supplied type, so just throw an
489 throw new CrudException("Failed to update edge: " + getResult.getFailureCause(),
490 Response.Status.fromStatusCode(getResult.getResultCode()));
495 public void deleteEdge(String id, String type, String txId) throws CrudException {
496 String url = baseRelationshipUrl + "/" + id + "?transactionId=" + txId;
497 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
499 if (getResult.getResultCode() != 200) {
500 // We didn't find an edge with the supplied type, so just throw an
502 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
507 public Edge getEdge(String id, String type, String txId) throws CrudException {
508 String url = baseRelationshipUrl + "/" + id + "?transactionId=" + txId;
509 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
511 if (getResult.getResultCode() == 200) {
512 Edge edge = Edge.fromJson(getResult.getResult());
514 if (!edge.getType().equalsIgnoreCase(type)) {
515 // We didn't find an edge with the supplied type, so just throw an
517 throw new CrudException("No edge with id " + id + "and type " + type + " found in graph",
518 javax.ws.rs.core.Response.Status.NOT_FOUND);
522 // We didn't find an edge with the supplied id, so just throw an
524 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
528 public Vertex getVertex(String id, String type, String txId) throws CrudException {
529 String url = baseObjectUrl + "/" + id + "?transactionId=" + txId;
530 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
532 if (getResult.getResultCode() == 200) {
533 Vertex vert = Vertex.fromJson(getResult.getResult());
535 if (!vert.getType().equalsIgnoreCase(type)) {
536 // We didn't find a vertex with the supplied type, so just throw an
538 throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph",
539 javax.ws.rs.core.Response.Status.NOT_FOUND);
543 // We didn't find a vertex with the supplied id, so just throw an
545 throw new CrudException("No vertex with id " + id + " found in graph",
546 javax.ws.rs.core.Response.Status.NOT_FOUND);
550 // https://stackoverflow.com/questions/26942330/convert-mapstring-string-to-listnamevaluepair-is-this-the-most-efficient
551 private List<NameValuePair> convertToNameValuePair(Map<String, Object> pairs) {
552 List<NameValuePair> nvpList = new ArrayList<>(pairs.size());
554 pairs.forEach((key, value) -> nvpList.add(new BasicNameValuePair(key, value.toString())));
559 // https://stackoverflow.com/questions/26942330/convert-mapstring-string-to-listnamevaluepair-is-this-the-most-efficient
560 private List<NameValuePair> convertToNameValuePair(String key, HashSet<String> values) {
561 List<NameValuePair> nvpList = new ArrayList<>(values.size());
563 values.forEach((value) -> nvpList.add(new BasicNameValuePair(key, value)));
568 private Map<String, List<String>> createHeader() {
569 Map<String, List<String>> headers = new HashMap<>();
570 headers.put(HEADER_FROM_APP, Arrays.asList(FROM_APP_NAME));
571 headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString())));