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 protected RestClient client;
61 protected String baseObjectUrl;
62 protected String baseRelationshipUrl;
63 protected String baseTransactionUrl;
65 protected static final String HEADER_FROM_APP = "X-FromAppId";
66 protected static final String HEADER_TRANS_ID = "X-TransactionId";
67 protected static final String FROM_APP_NAME = "Gizmo";
68 protected static final String OBJECT_SUB_URL = "objects";
69 protected static final String RELATIONSHIP_SUB_URL = "relationships";
70 protected 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 protected static final Gson champGson = new GsonBuilder()
77 .registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory())
78 .registerTypeAdapter(Vertex.class, new ChampVertexSerializer())
79 .registerTypeAdapter(Edge.class, new ChampEdgeSerializer()).create();
84 public ChampDao(String champUrl, String certPassword) {
86 client = new RestClient().authenticationMode(RestAuthenticationMode.SSL_CERT).validateServerHostname(false)
87 .validateServerCertChain(false).clientCertFile(CrudServiceConstants.CRD_CHAMP_AUTH_FILE)
88 .clientCertPassword(Password.deobfuscate(certPassword));
90 baseObjectUrl = champUrl + OBJECT_SUB_URL;
91 baseRelationshipUrl = champUrl + RELATIONSHIP_SUB_URL;
92 baseTransactionUrl = champUrl + TRANSACTION_SUB_URL;
93 } catch (Exception e) {
94 System.out.println("Error setting up Champ configuration");
100 public ChampDao(RestClient client, String baseObjectUrl, String baseRelationshipUrl, String baseTransactionUrl) {
101 this.client = client;
102 this.baseObjectUrl = baseObjectUrl;
103 this.baseRelationshipUrl = baseRelationshipUrl;
104 this.baseTransactionUrl = baseTransactionUrl;
108 public Vertex getVertex(String id, String version) throws CrudException {
109 String url = baseObjectUrl + "/" + id;
110 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
112 if (getResult.getResultCode() == 200) {
113 return Vertex.fromJson(getResult.getResult(), version);
115 // We didn't find a vertex with the supplied id, so just throw an
117 throw new CrudException("No vertex with id " + id + " found in graph",
118 javax.ws.rs.core.Response.Status.NOT_FOUND);
123 public Vertex getVertex(String id, String type, String version) throws CrudException {
124 String url = baseObjectUrl + "/" + id;
125 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
127 if (getResult.getResultCode() == 200) {
128 Vertex vert = Vertex.fromJson(getResult.getResult(), version);
130 if (!vert.getType().equalsIgnoreCase(type)) {
131 // We didn't find a vertex with the supplied type, so just throw an
133 throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph",
134 javax.ws.rs.core.Response.Status.NOT_FOUND);
138 // We didn't find a vertex with the supplied id, so just throw an
140 throw new CrudException("No vertex with id " + id + " found in graph",
141 javax.ws.rs.core.Response.Status.NOT_FOUND);
146 public List<Edge> getVertexEdges(String id) throws CrudException {
147 String url = baseObjectUrl + "/relationships/" + id;
149 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
151 if (getResult.getResultCode() == 200) {
152 return champGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() {
155 // We didn't find a vertex with the supplied id, so just throw an
157 throw new CrudException("No vertex with id " + id + " found in graph",
158 javax.ws.rs.core.Response.Status.NOT_FOUND);
163 public List<Vertex> getVertices(String type, Map<String, Object> filter) throws CrudException {
164 return getVertices(type, filter, new HashSet<String>());
168 public List<Vertex> getVertices(String type, Map<String, Object> filter, HashSet<String> properties) throws CrudException {
169 filter.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
171 List<NameValuePair> queryParams = convertToNameValuePair(filter);
172 queryParams.addAll(convertToNameValuePair("properties", properties));
173 String url = baseObjectUrl + "/filter" + "?"
174 + URLEncodedUtils.format(queryParams, Charset.defaultCharset());
176 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
178 if (getResult.getResultCode() == 200) {
179 return champGson.fromJson(getResult.getResult(), new TypeToken<List<Vertex>>() {
182 // We didn't find a vertex with the supplied id, so just throw an
184 throw new CrudException("No vertices found in graph for given filters",
185 javax.ws.rs.core.Response.Status.NOT_FOUND);
190 public Edge getEdge(String id, String type) throws CrudException {
191 String url = baseRelationshipUrl + "/" + id;
192 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
194 if (getResult.getResultCode() == 200) {
195 Edge edge = Edge.fromJson(getResult.getResult());
197 if (!edge.getType().equalsIgnoreCase(type)) {
198 // We didn't find an edge with the supplied type, so just throw an
200 throw new CrudException("No edge with id " + id + "and type " + type + " found in graph",
201 javax.ws.rs.core.Response.Status.NOT_FOUND);
205 // We didn't find a edge with the supplied type, so just throw an
207 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
212 public List<Edge> getEdges(String type, Map<String, Object> filter) throws CrudException {
213 String url = baseRelationshipUrl + "/filter" + "?"
214 + URLEncodedUtils.format(convertToNameValuePair(filter), Charset.defaultCharset());
216 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
218 if (getResult.getResultCode() == 200) {
219 return champGson.fromJson(getResult.getResult(), new TypeToken<List<Edge>>() {
222 // We didn't find a vertex with the supplied id, so just throw an
224 throw new CrudException("No edges found in graph for given filters", javax.ws.rs.core.Response.Status.NOT_FOUND);
229 public Vertex addVertex(String type, Map<String, Object> properties, String version) throws CrudException {
230 String url = baseObjectUrl;
232 // Add the aai_node_type so that AAI can read the data created by gizmo
233 // TODO: This probably shouldn't be here
234 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
236 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
237 properties.forEach(insertVertexBuilder::property);
238 Vertex insertVertex = insertVertexBuilder.build();
240 OperationResult getResult = client.post(url, insertVertex.toJson(), createHeader(), MediaType.APPLICATION_JSON_TYPE,
241 MediaType.APPLICATION_JSON_TYPE);
243 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
244 return Vertex.fromJson(getResult.getResult(), version);
246 // We didn't create a vertex with the supplied type, so just throw an
248 throw new CrudException("Failed to create vertex", Response.Status.fromStatusCode(getResult.getResultCode()));
253 public Vertex updateVertex(String id, String type, Map<String, Object> properties, String version) throws CrudException {
254 String url = baseObjectUrl + "/" + id;
256 // Add the aai_node_type so that AAI can read the data created by gizmo
257 // TODO: This probably shouldn't be here
258 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
260 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
261 insertVertexBuilder.id(id);
262 properties.forEach(insertVertexBuilder::property);
263 Vertex insertVertex = insertVertexBuilder.build();
265 String payload = insertVertex.toJson(champGson);
266 OperationResult getResult = client.put(url, payload, createHeader(), MediaType.APPLICATION_JSON_TYPE,
267 MediaType.APPLICATION_JSON_TYPE);
269 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
270 return Vertex.fromJson(getResult.getResult(), version);
272 // We didn't create a vertex with the supplied type, so just throw an
274 throw new CrudException("Failed to update vertex: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
279 public void deleteVertex(String id, String type) throws CrudException {
280 String url = baseObjectUrl + "/" + id;
281 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
283 if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) {
284 // We didn't delete a vertex with the supplied id, so just throw an
286 throw new CrudException("Failed to delete vertex: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
291 public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties, String version) throws CrudException {
292 String url = baseRelationshipUrl;
294 // Try requests to ensure source and target exist in Champ
295 Vertex dbSource = getVertex(source.getId().get(), source.getType(), version);
296 Vertex dbTarget = getVertex(target.getId().get(), target.getType(), version);
298 Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget);
299 properties.forEach(insertEdgeBuilder::property);
300 Edge insertEdge = insertEdgeBuilder.build();
302 String edgeJson = insertEdge.toJson(champGson);
303 OperationResult getResult = client.post(url, edgeJson, createHeader(), MediaType.APPLICATION_JSON_TYPE,
304 MediaType.APPLICATION_JSON_TYPE);
306 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
307 return Edge.fromJson(getResult.getResult());
309 // We didn't create an edge with the supplied type, so just throw an
311 throw new CrudException("Failed to create edge: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
316 public Edge updateEdge(Edge edge) throws CrudException {
317 if (!edge.getId().isPresent()) {
318 throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST);
320 String url = baseRelationshipUrl + "/" + edge.getId().get();
322 String edgeJson = edge.toJson(champGson);
323 OperationResult getResult = client.put(url, edgeJson, createHeader(), MediaType.APPLICATION_JSON_TYPE,
324 MediaType.APPLICATION_JSON_TYPE);
326 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
327 return Edge.fromJson(getResult.getResult());
329 // We didn't create an edge with the supplied type, so just throw an
331 throw new CrudException("Failed to update edge: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
336 public void deleteEdge(String id, String type) throws CrudException {
337 String url = baseRelationshipUrl + "/" + id;
338 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
340 if (getResult.getResultCode() != 200) {
341 // We didn't find an edge with the supplied type, so just throw an
343 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
348 public String openTransaction() {
349 String url = baseTransactionUrl;
351 OperationResult getResult = client.post(url, "", createHeader(), MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_PLAIN_TYPE);
353 if (getResult.getResultCode() == 200) {
354 return getResult.getResult();
361 public void commitTransaction(String id) throws CrudException {
362 String url = baseTransactionUrl + "/" + id;
364 OperationResult getResult = client.put(url, "{\"method\": \"commit\"}", createHeader(), MediaType.APPLICATION_JSON_TYPE,
365 MediaType.TEXT_PLAIN_TYPE);
367 if (getResult.getResultCode() != 200) {
368 throw new CrudException("Unable to commit transaction",
369 Response.Status.fromStatusCode(getResult.getResultCode()));
374 public void rollbackTransaction(String id) throws CrudException {
375 String url = baseTransactionUrl + "/" + id;
377 OperationResult getResult = client.put(url, "{\"method\": \"rollback\"}", createHeader(), MediaType.APPLICATION_JSON_TYPE,
378 MediaType.TEXT_PLAIN_TYPE);
380 if (getResult.getResultCode() != 200) {
381 throw new CrudException("Unable to rollback transaction",
382 Response.Status.fromStatusCode(getResult.getResultCode()));
387 public boolean transactionExists(String id) throws CrudException {
388 String url = baseTransactionUrl + "/" + id;
389 Map<String, List<String>> headers = new HashMap<>();
390 headers.put(HEADER_FROM_APP, Arrays.asList("Gizmo"));
391 headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString())));
393 OperationResult getResult = client.get(url, headers, MediaType.APPLICATION_JSON_TYPE);
395 return getResult.getResultCode() == 200;
399 public Vertex addVertex(String type, Map<String, Object> properties, String version, String txId) throws CrudException {
400 String url = baseObjectUrl + "?transactionId=" + txId;
402 // Add the aai_node_type so that AAI can read the data created by gizmo
403 // TODO: This probably shouldn't be here
404 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
406 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
407 properties.forEach(insertVertexBuilder::property);
408 Vertex insertVertex = insertVertexBuilder.build();
410 OperationResult getResult = client.post(url, insertVertex.toJson(), createHeader(), MediaType.APPLICATION_JSON_TYPE,
411 MediaType.APPLICATION_JSON_TYPE);
413 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
414 return Vertex.fromJson(getResult.getResult(), version);
416 // We didn't create a vertex with the supplied type, so just throw an
418 throw new CrudException("Failed to create vertex: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
423 public Edge addEdge(String type, Vertex source, Vertex target, Map<String, Object> properties, String version, String txId)
424 throws CrudException {
425 String url = baseRelationshipUrl + "?transactionId=" + txId;
427 // Try requests to ensure source and target exist in Champ
428 Vertex dbSource = getVertex(source.getId().get(), source.getType(), version, txId);
429 Vertex dbTarget = getVertex(target.getId().get(), target.getType(), version, txId);
431 Edge.Builder insertEdgeBuilder = new Edge.Builder(type).source(dbSource).target(dbTarget);
432 properties.forEach(insertEdgeBuilder::property);
433 Edge insertEdge = insertEdgeBuilder.build();
435 OperationResult getResult = client.post(url, insertEdge.toJson(champGson), createHeader(),
436 MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
438 if (getResult.getResultCode() == Response.Status.CREATED.getStatusCode()) {
439 return Edge.fromJson(getResult.getResult());
441 // We didn't create an edge with the supplied type, so just throw an
443 throw new CrudException("Failed to create edge: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
448 public Vertex updateVertex(String id, String type, Map<String, Object> properties, String version, String txId) throws CrudException {
449 String url = baseObjectUrl + "/" + id + "?transactionId=" + txId;
451 // Add the aai_node_type so that AAI can read the data created by gizmo
452 // TODO: This probably shouldn't be here
453 properties.put(org.onap.schema.OxmModelValidator.Metadata.NODE_TYPE.propertyName(), type);
455 Vertex.Builder insertVertexBuilder = new Vertex.Builder(type);
456 insertVertexBuilder.id(id);
457 properties.forEach(insertVertexBuilder::property);
458 Vertex insertVertex = insertVertexBuilder.build();
460 String payload = insertVertex.toJson(champGson);
461 OperationResult getResult = client.put(url, payload, createHeader(), MediaType.APPLICATION_JSON_TYPE,
462 MediaType.APPLICATION_JSON_TYPE);
464 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
465 return Vertex.fromJson(getResult.getResult(), version);
467 // We didn't create a vertex with the supplied type, so just throw an
469 throw new CrudException("Failed to update vertex: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
474 public void deleteVertex(String id, String type, String txId) throws CrudException {
475 String url = baseObjectUrl + "/" + id + "?transactionId=" + txId;
476 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
478 if (getResult.getResultCode() != Response.Status.OK.getStatusCode()) {
479 // We didn't delete a vertex with the supplied id, so just throw an
481 throw new CrudException("Failed to delete vertex: " + getResult.getFailureCause(), Response.Status.fromStatusCode(getResult.getResultCode()));
486 public Edge updateEdge(Edge edge, String txId) throws CrudException {
487 if (!edge.getId().isPresent()) {
488 throw new CrudException("Unable to identify edge: " + edge.toString(), Response.Status.BAD_REQUEST);
490 String url = baseRelationshipUrl + "/" + edge.getId().get() + "?transactionId=" + txId;
491 OperationResult getResult = client.put(url, edge.toJson(champGson), createHeader(), MediaType.APPLICATION_JSON_TYPE,
492 MediaType.APPLICATION_JSON_TYPE);
494 if (getResult.getResultCode() == Response.Status.OK.getStatusCode()) {
495 return Edge.fromJson(getResult.getResult());
497 // We didn't create an edge with the supplied type, so just throw an
499 throw new CrudException("Failed to update edge: " + getResult.getFailureCause(),
500 Response.Status.fromStatusCode(getResult.getResultCode()));
505 public void deleteEdge(String id, String type, String txId) throws CrudException {
506 String url = baseRelationshipUrl + "/" + id + "?transactionId=" + txId;
507 OperationResult getResult = client.delete(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
509 if (getResult.getResultCode() != 200) {
510 // We didn't find an edge with the supplied type, so just throw an
512 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
517 public Edge getEdge(String id, String type, String txId) throws CrudException {
518 String url = baseRelationshipUrl + "/" + id + "?transactionId=" + txId;
519 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
521 if (getResult.getResultCode() == 200) {
522 Edge edge = Edge.fromJson(getResult.getResult());
524 if (!edge.getType().equalsIgnoreCase(type)) {
525 // We didn't find an edge with the supplied type, so just throw an
527 throw new CrudException("No edge with id " + id + "and type " + type + " found in graph",
528 javax.ws.rs.core.Response.Status.NOT_FOUND);
532 // We didn't find an edge with the supplied id, so just throw an
534 throw new CrudException("No edge with id " + id + " found in graph", javax.ws.rs.core.Response.Status.NOT_FOUND);
538 public Vertex getVertex(String id, String type, String version, String txId) throws CrudException {
539 String url = baseObjectUrl + "/" + id + "?transactionId=" + txId;
540 OperationResult getResult = client.get(url, createHeader(), MediaType.APPLICATION_JSON_TYPE);
542 if (getResult.getResultCode() == 200) {
543 Vertex vert = Vertex.fromJson(getResult.getResult(), version);
545 if (!vert.getType().equalsIgnoreCase(type)) {
546 // We didn't find a vertex with the supplied type, so just throw an
548 throw new CrudException("No vertex with id " + id + "and type " + type + " found in graph",
549 javax.ws.rs.core.Response.Status.NOT_FOUND);
553 // We didn't find a vertex with the supplied id, so just throw an
555 throw new CrudException("No vertex with id " + id + " found in graph",
556 javax.ws.rs.core.Response.Status.NOT_FOUND);
560 // https://stackoverflow.com/questions/26942330/convert-mapstring-string-to-listnamevaluepair-is-this-the-most-efficient
561 private List<NameValuePair> convertToNameValuePair(Map<String, Object> pairs) {
562 List<NameValuePair> nvpList = new ArrayList<>(pairs.size());
564 pairs.forEach((key, value) -> nvpList.add(new BasicNameValuePair(key, value.toString())));
569 // https://stackoverflow.com/questions/26942330/convert-mapstring-string-to-listnamevaluepair-is-this-the-most-efficient
570 private List<NameValuePair> convertToNameValuePair(String key, HashSet<String> values) {
571 List<NameValuePair> nvpList = new ArrayList<>(values.size());
573 values.forEach((value) -> nvpList.add(new BasicNameValuePair(key, value)));
578 private Map<String, List<String>> createHeader() {
579 Map<String, List<String>> headers = new HashMap<>();
580 headers.put(HEADER_FROM_APP, Arrays.asList(FROM_APP_NAME));
581 headers.put(HEADER_TRANS_ID, Arrays.asList(MDC.get(LoggingContext.LoggingField.REQUEST_ID.toString())));