2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 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============================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 package org.onap.aai.champcore.ie;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.LinkedList;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.concurrent.atomic.AtomicInteger;
38 import javax.xml.parsers.DocumentBuilder;
39 import javax.xml.parsers.DocumentBuilderFactory;
40 import javax.xml.parsers.ParserConfigurationException;
41 import javax.xml.stream.XMLOutputFactory;
42 import javax.xml.stream.XMLStreamException;
43 import javax.xml.stream.XMLStreamWriter;
45 import org.onap.aai.champcore.ChampAPI;
46 import org.onap.aai.champcore.ChampGraph;
47 import org.onap.aai.champcore.ChampTransaction;
48 import org.onap.aai.champcore.exceptions.ChampMarshallingException;
49 import org.onap.aai.champcore.exceptions.ChampObjectNotExistsException;
50 import org.onap.aai.champcore.exceptions.ChampRelationshipNotExistsException;
51 import org.onap.aai.champcore.exceptions.ChampSchemaViolationException;
52 import org.onap.aai.champcore.exceptions.ChampTransactionException;
53 import org.onap.aai.champcore.exceptions.ChampUnmarshallingException;
54 import org.onap.aai.champcore.model.ChampObject;
55 import org.onap.aai.champcore.model.ChampObjectIndex;
56 import org.onap.aai.champcore.model.ChampRelationship;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.w3c.dom.NamedNodeMap;
61 import org.w3c.dom.Node;
62 import org.w3c.dom.NodeList;
63 import org.xml.sax.InputSource;
64 import org.xml.sax.SAXException;
66 public class GraphMLImporterExporter implements Importer, Exporter {
68 private static final Logger LOGGER = LoggerFactory.getLogger(GraphMLImporterExporter.class);
70 private static class GraphMLKey {
71 private final String id;
72 private final String attrName;
73 private final String attrType;
75 public GraphMLKey(String id, String attrName, Class<?> attrType) {
77 this.attrName = attrName;
79 if (attrType.equals(Boolean.class)) {
80 this.attrType = "boolean";
81 } else if (attrType.equals(Integer.class)) {
82 this.attrType = "int";
83 } else if (attrType.equals(Long.class)) {
84 this.attrType = "long";
85 } else if (attrType.equals(Float.class)) {
86 this.attrType = "float";
87 } else if (attrType.equals(Double.class)) {
88 this.attrType = "double";
89 } else if (attrType.equals(String.class)) {
90 this.attrType = "string";
92 throw new RuntimeException("Cannot handle type " + attrType + " in GraphML");
97 public void importData(ChampAPI api, InputStream is) {
100 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
101 final DocumentBuilder builder = factory.newDocumentBuilder();
102 final InputSource inputSource = new InputSource(is);
103 final Document doc = builder.parse(inputSource);
105 final Map<String, Map<String, String>> nodePropertyDefinitions = new HashMap<String, Map<String, String>> ();
106 final Map<String, Map<String, String>> edgePropertyDefinitions = new HashMap<String, Map<String, String>> ();
107 final Set<Map<String, String>> nodeDefaults = new HashSet<Map<String, String>> ();
108 final Set<Map<String, String>> edgeDefaults = new HashSet<Map<String, String>> ();
110 final NodeList keys = doc.getElementsByTagName("key");
112 for (int i = 0; i < keys.getLength(); i++) {
113 final Node key = keys.item(i);
114 final String id = key.getAttributes().getNamedItem("id").getNodeValue();
115 final String attrName = key.getAttributes().getNamedItem("attr.name").getNodeValue();
116 final String attrType = key.getAttributes().getNamedItem("attr.type").getNodeValue();
117 final String elementType = key.getAttributes().getNamedItem("for").getNodeValue();
118 final Map<String, String> propertyDefinitions = new HashMap<String, String> ();
120 propertyDefinitions.put("attr.name", attrName);
121 propertyDefinitions.put("attr.type", attrType);
123 final NodeList keyChildren = key.getChildNodes();
125 for (int j = 0; j < keyChildren.getLength(); j++) {
126 final Node keyChild = keyChildren.item(j);
128 if (keyChild.getNodeType() != Node.ELEMENT_NODE) continue;
130 if (keyChild.getNodeName().equals("default")) {
131 propertyDefinitions.put("default", keyChild.getFirstChild().getNodeValue());
133 if (elementType.equals("node")) nodeDefaults.add(propertyDefinitions);
134 else if (elementType.equals("edge")) edgeDefaults.add(propertyDefinitions);
138 if (elementType.equals("node")) {
139 nodePropertyDefinitions.put(id, propertyDefinitions);
140 } else if (elementType.equals("edge")) {
141 edgePropertyDefinitions.put(id, propertyDefinitions);
143 LOGGER.warn("Unknown element type {}, skipping", elementType);
147 final NodeList graphs = doc.getElementsByTagName("graph");
149 for (int i = 0; i < graphs.getLength(); i++) {
150 final Node graph = graphs.item(i);
151 final String graphName = graph.getAttributes().getNamedItem("id").getNodeValue();
152 final NodeList nodesAndEdges = graph.getChildNodes();
154 api.getGraph(graphName).storeObjectIndex(ChampObjectIndex.create()
155 .ofName("importAssignedId")
157 .forField("importAssignedId")
160 for (int j = 0; j < nodesAndEdges.getLength(); j++) {
161 final Node nodeOrEdge = nodesAndEdges.item(j);
163 if (nodeOrEdge.getNodeType() != Node.ELEMENT_NODE) continue;
165 if (nodeOrEdge.getNodeName().equals("node")) {
166 writeNode(api.getGraph(graphName), nodeOrEdge, nodePropertyDefinitions, nodeDefaults);
167 } else if (nodeOrEdge.getNodeName().equals("edge")) {
168 writeEdge(api.getGraph(graphName), nodeOrEdge, edgePropertyDefinitions, edgeDefaults);
170 LOGGER.warn("Unknown object {} found in graphML, skipping", nodeOrEdge.getNodeName());
174 } catch (ParserConfigurationException e) {
175 throw new RuntimeException("Failed to setup DocumentBuilder", e);
176 } catch (SAXException e) {
177 throw new RuntimeException("Failed to parse input stream", e);
178 } catch (IOException e) {
179 throw new RuntimeException("Failed to parse input stream", e);
183 private void writeEdge(ChampGraph graph, Node edge, Map<String, Map<String, String>> edgePropertyDefinitions, Set<Map<String, String>> edgeDefaults) {
184 final NamedNodeMap edgeAttributes = edge.getAttributes();
185 final NodeList data = edge.getChildNodes();
186 final Object sourceKey = edgeAttributes.getNamedItem("source").getNodeValue();
187 final Object targetKey = edgeAttributes.getNamedItem("target").getNodeValue();
188 ChampObject sourceObject=null;
189 ChampObject targetObject=null;
192 final Optional<ChampObject> source = graph.queryObjects(Collections.singletonMap("importAssignedId", sourceKey), Optional.empty()).findFirst();
193 final Optional<ChampObject> target = graph.queryObjects(Collections.singletonMap("importAssignedId", targetKey), Optional.empty()).findFirst();
195 if (!source.isPresent()) {
196 sourceObject = graph.storeObject(ChampObject.create()
201 } else sourceObject = source.get();
203 if (!target.isPresent()) {
204 targetObject = graph.storeObject(ChampObject.create()
209 } else targetObject = target.get();
211 } catch (ChampMarshallingException e) {
212 LOGGER.error("Failed to marshall object to backend type, skipping this edge", e);
214 } catch (ChampSchemaViolationException e) {
215 LOGGER.error("Source/target object violates schema constraint(s)", e);
217 } catch (ChampObjectNotExistsException e) {
218 LOGGER.error("Failed to update existing source/target ChampObject", e);
220 } catch (ChampTransactionException e) {
221 LOGGER.error("Failed to commit or rollback transaction", e);
224 final ChampRelationship.Builder champRelBuilder = new ChampRelationship.Builder(sourceObject, targetObject, "undefined");
226 for (Map<String, String> defaultProperty : edgeDefaults) {
227 champRelBuilder.property(defaultProperty.get("attr.name"), defaultProperty.get("default"));
230 for (int k = 0; k < data.getLength(); k++) {
231 final Node datum = data.item(k);
233 if (datum.getNodeType() != Node.ELEMENT_NODE) continue;
235 final String nodeProperty = datum.getAttributes().getNamedItem("key").getNodeValue();
236 final Map<String, String> nodePropertyDefinition = edgePropertyDefinitions.get(nodeProperty);
238 switch (nodePropertyDefinition.get("attr.type")) {
240 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Boolean.valueOf(datum.getFirstChild().getNodeValue()));
243 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Integer.valueOf(datum.getFirstChild().getNodeValue()));
246 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Long.valueOf(datum.getFirstChild().getNodeValue()));
249 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Float.valueOf(datum.getFirstChild().getNodeValue()));
252 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Double.valueOf(datum.getFirstChild().getNodeValue()));
255 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), datum.getFirstChild().getNodeValue());
258 throw new RuntimeException("Unknown node property attr.type " + nodePropertyDefinition.get("attr.type"));
262 final ChampRelationship relToStore = champRelBuilder.build();
265 graph.storeRelationship(relToStore, Optional.empty());
266 } catch (ChampMarshallingException e) {
267 LOGGER.warn("Failed to marshall ChampObject to backend type", e);
268 } catch (ChampSchemaViolationException e) {
269 LOGGER.error("Failed to store object (schema violated): " + relToStore, e);
270 } catch (ChampRelationshipNotExistsException e) {
271 LOGGER.error("Failed to update existing ChampRelationship", e);
272 } catch (ChampObjectNotExistsException e) {
273 LOGGER.error("Objects bound to relationship do not exist (should never happen)");
274 } catch (ChampUnmarshallingException e) {
275 LOGGER.error("Failed to unmarshall ChampObject to backend type");
276 } catch (ChampTransactionException e) {
277 LOGGER.error("Failed to commit or rollback transaction");
282 private void writeNode(ChampGraph graph, Node node, Map<String, Map<String, String>> nodePropertyDefinitions, Set<Map<String, String>> nodeDefaults) {
283 final NamedNodeMap nodeAttributes = node.getAttributes();
284 final Object importAssignedId = nodeAttributes.getNamedItem("id").getNodeValue();
285 final NodeList data = node.getChildNodes();
286 final Map<String, Object> properties = new HashMap<String, Object> ();
288 for (int k = 0; k < data.getLength(); k++) {
289 final Node datum = data.item(k);
291 if (datum.getNodeType() != Node.ELEMENT_NODE) continue;
293 final String nodeProperty = datum.getAttributes().getNamedItem("key").getNodeValue();
294 final Map<String, String> nodePropertyDefinition = nodePropertyDefinitions.get(nodeProperty);
296 switch (nodePropertyDefinition.get("attr.type")) {
298 properties.put(nodePropertyDefinition.get("attr.name"), Boolean.valueOf(datum.getFirstChild().getNodeValue()));
301 properties.put(nodePropertyDefinition.get("attr.name"), Integer.valueOf(datum.getFirstChild().getNodeValue()));
304 properties.put(nodePropertyDefinition.get("attr.name"), Long.valueOf(datum.getFirstChild().getNodeValue()));
307 properties.put(nodePropertyDefinition.get("attr.name"), Float.valueOf(datum.getFirstChild().getNodeValue()));
310 properties.put(nodePropertyDefinition.get("attr.name"), Double.valueOf(datum.getFirstChild().getNodeValue()));
313 properties.put(nodePropertyDefinition.get("attr.name"), datum.getFirstChild().getNodeValue());
316 throw new RuntimeException("Unknown node property attr.type " + nodePropertyDefinition.get("attr.type"));
320 if (!properties.containsKey("type")) throw new RuntimeException("No type provided for object (was this GraphML exported by Champ?)");
322 final ChampObject.Builder champObjBuilder = new ChampObject.Builder((String) properties.get("type"));
324 for (Map<String, String> defaultProperty : nodeDefaults) {
325 champObjBuilder.property(defaultProperty.get("attr.name"), defaultProperty.get("default"));
328 properties.remove("type");
330 champObjBuilder.properties(properties)
331 .property("importAssignedId", importAssignedId);
333 final ChampObject objectToStore = champObjBuilder.build();
336 graph.storeObject(objectToStore, Optional.empty());
337 } catch (ChampMarshallingException e) {
338 LOGGER.warn("Failed to marshall ChampObject to backend type", e);
339 } catch (ChampSchemaViolationException e) {
340 LOGGER.error("Failed to store object (schema violated): " + objectToStore, e);
341 } catch (ChampObjectNotExistsException e) {
342 LOGGER.error("Failed to update existing ChampObject", e);
343 } catch (ChampTransactionException e) {
344 LOGGER.error("Failed to commit or rollback transaction");
349 public void exportData(ChampGraph graph, OutputStream os) {
351 final XMLOutputFactory output = XMLOutputFactory.newInstance();
354 final XMLStreamWriter writer = output.createXMLStreamWriter(os);
356 writer.writeStartDocument();
357 writer.writeStartElement("graphml");
358 writer.writeDefaultNamespace("http://graphml.graphdrawing.org/xmlns");
359 writer.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
360 writer.writeAttribute("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation", "http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd");
362 final List<ChampObject> nodes = new LinkedList<ChampObject> ();
363 final List<ChampRelationship> edges = new LinkedList<ChampRelationship> ();
364 final Map<String, GraphMLKey> nodeKeys = new HashMap<String, GraphMLKey> ();
365 final Map<String, GraphMLKey> edgeKeys = new HashMap<String, GraphMLKey> ();
366 final AtomicInteger elementCount = new AtomicInteger();
368 graph.queryObjects(Collections.emptyMap(), Optional.empty()).forEach(object -> {
371 for (Map.Entry<String, Object> property : object.getProperties().entrySet()) {
372 if (nodeKeys.containsKey(property.getKey())) continue;
374 nodeKeys.put(property.getKey(), new GraphMLKey("d" + elementCount.incrementAndGet(), property.getKey(), property.getValue().getClass()));
377 nodeKeys.put("type", new GraphMLKey("d" + elementCount.incrementAndGet(), "type", String.class));
380 graph.queryRelationships(Collections.emptyMap(), Optional.empty()).forEach(relationship -> {
381 edges.add(relationship);
383 for (Map.Entry<String, Object> property : relationship.getProperties().entrySet()) {
384 if (nodeKeys.containsKey(property.getKey())) continue;
386 edgeKeys.put(property.getKey(), new GraphMLKey("d" + elementCount.incrementAndGet(), property.getKey(), property.getValue().getClass()));
389 edgeKeys.put("type", new GraphMLKey("d" + elementCount.incrementAndGet(), "type", String.class));
392 for (Entry<String, GraphMLKey> nodeKey : nodeKeys.entrySet()) {
393 final GraphMLKey graphMlKey = nodeKey.getValue();
395 writer.writeStartElement("key");
396 writer.writeAttribute("id", graphMlKey.id);
397 writer.writeAttribute("for", "node");
398 writer.writeAttribute("attr.name", graphMlKey.attrName);
399 writer.writeAttribute("attr.type", graphMlKey.attrType);
400 writer.writeEndElement();
403 for (Entry<String, GraphMLKey> edgeKey : edgeKeys.entrySet()) {
404 final GraphMLKey graphMlKey = edgeKey.getValue();
406 writer.writeStartElement("key");
407 writer.writeAttribute("id", graphMlKey.id);
408 writer.writeAttribute("for", "edge");
409 writer.writeAttribute("attr.name", graphMlKey.attrName);
410 writer.writeAttribute("attr.type", graphMlKey.attrType);
411 writer.writeEndElement();
414 for (ChampObject object : nodes) {
416 writer.writeStartElement("node");
417 writer.writeAttribute("id", String.valueOf(object.getKey().get()));
419 writer.writeStartElement("data");
420 writer.writeAttribute("key", nodeKeys.get("type").id);
421 writer.writeCharacters(object.getType());
422 writer.writeEndElement();
424 for (Entry<String, Object> property : object.getProperties().entrySet()) {
425 final GraphMLKey key = nodeKeys.get(property.getKey());
427 writer.writeStartElement("data");
428 writer.writeAttribute("key", key.id);
429 writer.writeCharacters(String.valueOf(property.getValue()));
430 writer.writeEndElement();
433 writer.writeEndElement();
434 } catch (XMLStreamException e) {
435 throw new RuntimeException("Failed to write edge to output stream", e);
439 for (ChampRelationship relationship : edges) {
441 writer.writeStartElement("edge");
442 writer.writeAttribute("id", String.valueOf(relationship.getKey().get()));
444 writer.writeStartElement("data");
445 writer.writeAttribute("key", edgeKeys.get("type").id);
446 writer.writeCharacters(relationship.getType());
447 writer.writeEndElement();
449 for (Entry<String, Object> property : relationship.getProperties().entrySet()) {
450 final GraphMLKey key = edgeKeys.get(property.getKey());
452 writer.writeStartElement("data");
453 writer.writeAttribute("key", key.id);
454 writer.writeCharacters(String.valueOf(property.getValue()));
455 writer.writeEndElement();
458 writer.writeEndElement();
459 } catch (XMLStreamException e) {
460 throw new RuntimeException("Failed to write edge to output stream", e);
464 writer.writeEndElement();
465 writer.writeEndDocument();
467 } catch (XMLStreamException | ChampTransactionException e) {
468 throw new RuntimeException(e);