71292ce60d41282bcfb1adc1b0139d24e9376942
[aai/champ.git] / champ-lib / champ-core / src / main / java / org / onap / aai / champcore / ie / GraphMLImporterExporter.java
1 /**
2  * ============LICENSE_START==========================================
3  * org.onap.aai
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
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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22 package org.onap.aai.champcore.ie;
23
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;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Optional;
35 import java.util.Set;
36 import java.util.concurrent.atomic.AtomicInteger;
37
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;
44
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;
65
66 public class GraphMLImporterExporter implements Importer, Exporter {
67
68         private static final Logger LOGGER = LoggerFactory.getLogger(GraphMLImporterExporter.class);
69
70         private static class GraphMLKey {
71                 private final String id;
72                 private final String attrName;
73                 private final String attrType;
74
75                 public GraphMLKey(String id, String attrName, Class<?> attrType) {
76                         this.id = id;
77                         this.attrName = attrName;
78
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";
91                         } else {
92                                 throw new RuntimeException("Cannot handle type " + attrType + " in GraphML");
93                         }
94                 }
95         }
96
97         public void importData(ChampAPI api, InputStream is) {
98
99                 try {
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);
104
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>> ();
109
110                         final NodeList keys = doc.getElementsByTagName("key");
111
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> ();
119
120                                 propertyDefinitions.put("attr.name", attrName);
121                                 propertyDefinitions.put("attr.type",  attrType);
122
123                                 final NodeList keyChildren = key.getChildNodes();
124
125                                 for (int j = 0; j < keyChildren.getLength(); j++) {
126                                         final Node keyChild = keyChildren.item(j);
127
128                                         if (keyChild.getNodeType() != Node.ELEMENT_NODE) continue;
129
130                                         if (keyChild.getNodeName().equals("default")) {
131                                                 propertyDefinitions.put("default", keyChild.getFirstChild().getNodeValue());
132
133                                                 if (elementType.equals("node")) nodeDefaults.add(propertyDefinitions);
134                                                 else if (elementType.equals("edge")) edgeDefaults.add(propertyDefinitions);
135                                         }
136                                 }
137
138                                 if (elementType.equals("node")) {
139                                         nodePropertyDefinitions.put(id, propertyDefinitions);
140                                 } else if (elementType.equals("edge")) {
141                                         edgePropertyDefinitions.put(id, propertyDefinitions);
142                                 } else {
143                                         LOGGER.warn("Unknown element type {}, skipping", elementType);
144                                 }
145                         }
146
147                         final NodeList graphs = doc.getElementsByTagName("graph");
148
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();
153
154                                 api.getGraph(graphName).storeObjectIndex(ChampObjectIndex.create()
155                                                                                                                                                         .ofName("importAssignedId")
156                                                                                                                                                         .onAnyType()
157                                                                                                                                                         .forField("importAssignedId")
158                                                                                                                                                         .build());
159
160                                 for (int j = 0; j < nodesAndEdges.getLength(); j++) {
161                                         final Node nodeOrEdge = nodesAndEdges.item(j);
162
163                                         if (nodeOrEdge.getNodeType() != Node.ELEMENT_NODE) continue;
164
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);
169                                         } else {
170                                                 LOGGER.warn("Unknown object {} found in graphML, skipping", nodeOrEdge.getNodeName());
171                                         }
172                                 }
173                         }
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);
180                 }
181         }
182
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;
190                 
191                 try {
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();
194
195                         if (!source.isPresent()) {
196                                 sourceObject = graph.storeObject(ChampObject.create()
197                                                                                                                 .ofType("undefined")
198                                                                                                                 .withoutKey()
199                                                                                                                 .build(),
200                                                                                                  Optional.empty());
201                         } else sourceObject = source.get();
202         
203                         if (!target.isPresent()) {
204                                 targetObject = graph.storeObject(ChampObject.create()
205                                                                                                                 .ofType("undefined")
206                                                                                                                 .withoutKey()
207                                                                                                                 .build(),
208                                                                                                  Optional.empty());
209                         } else targetObject = target.get();
210
211                 } catch (ChampMarshallingException e) {
212                         LOGGER.error("Failed to marshall object to backend type, skipping this edge", e);
213                         return;
214                 } catch (ChampSchemaViolationException e) {
215                         LOGGER.error("Source/target object violates schema constraint(s)", e);
216                         return;
217                 } catch (ChampObjectNotExistsException e) {
218                         LOGGER.error("Failed to update existing source/target ChampObject", e);
219                         return;
220                 } catch (ChampTransactionException e) {
221             LOGGER.error("Failed to commit or rollback transaction", e);
222                 }
223
224                 final ChampRelationship.Builder champRelBuilder = new ChampRelationship.Builder(sourceObject, targetObject, "undefined");
225
226                 for (Map<String, String> defaultProperty : edgeDefaults) {
227                         champRelBuilder.property(defaultProperty.get("attr.name"), defaultProperty.get("default"));
228                 }
229
230                 for (int k = 0; k < data.getLength(); k++) {
231                         final Node datum = data.item(k);
232
233                         if (datum.getNodeType() != Node.ELEMENT_NODE) continue;
234
235                         final String nodeProperty = datum.getAttributes().getNamedItem("key").getNodeValue();
236                         final Map<String, String> nodePropertyDefinition = edgePropertyDefinitions.get(nodeProperty);
237
238                         switch (nodePropertyDefinition.get("attr.type")) {
239                         case "boolean":
240                                 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Boolean.valueOf(datum.getFirstChild().getNodeValue()));
241                                 break;
242                         case "int":
243                                 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Integer.valueOf(datum.getFirstChild().getNodeValue()));
244                                 break;
245                         case "long":
246                                 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Long.valueOf(datum.getFirstChild().getNodeValue()));
247                                 break;
248                         case "float":
249                                 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Float.valueOf(datum.getFirstChild().getNodeValue()));
250                                 break;
251                         case "double":
252                                 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), Double.valueOf(datum.getFirstChild().getNodeValue()));
253                                 break;
254                         case "string":
255                                 champRelBuilder.property(nodePropertyDefinition.get("attr.name"), datum.getFirstChild().getNodeValue());
256                                 break;
257                         default:
258                                 throw new RuntimeException("Unknown node property attr.type " + nodePropertyDefinition.get("attr.type"));
259                         }
260                 }
261
262                 final ChampRelationship relToStore = champRelBuilder.build();
263
264                 try {
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");
278                 }
279                 
280         }
281
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> ();
287
288                 for (int k = 0; k < data.getLength(); k++) {
289                         final Node datum = data.item(k);
290
291                         if (datum.getNodeType() != Node.ELEMENT_NODE) continue;
292
293                         final String nodeProperty = datum.getAttributes().getNamedItem("key").getNodeValue();
294                         final Map<String, String> nodePropertyDefinition = nodePropertyDefinitions.get(nodeProperty);
295
296                         switch (nodePropertyDefinition.get("attr.type")) {
297                         case "boolean":
298                                 properties.put(nodePropertyDefinition.get("attr.name"), Boolean.valueOf(datum.getFirstChild().getNodeValue()));
299                                 break;
300                         case "int":
301                                 properties.put(nodePropertyDefinition.get("attr.name"), Integer.valueOf(datum.getFirstChild().getNodeValue()));
302                                 break;
303                         case "long":
304                                 properties.put(nodePropertyDefinition.get("attr.name"), Long.valueOf(datum.getFirstChild().getNodeValue()));
305                                 break;
306                         case "float":
307                                 properties.put(nodePropertyDefinition.get("attr.name"), Float.valueOf(datum.getFirstChild().getNodeValue()));
308                                 break;
309                         case "double":
310                                 properties.put(nodePropertyDefinition.get("attr.name"), Double.valueOf(datum.getFirstChild().getNodeValue()));
311                                 break;
312                         case "string":
313                                 properties.put(nodePropertyDefinition.get("attr.name"), datum.getFirstChild().getNodeValue());
314                                 break;
315                         default:
316                                 throw new RuntimeException("Unknown node property attr.type " + nodePropertyDefinition.get("attr.type"));
317                         }
318                 }
319
320                 if (!properties.containsKey("type")) throw new RuntimeException("No type provided for object (was this GraphML exported by Champ?)");
321
322                 final ChampObject.Builder champObjBuilder = new ChampObject.Builder((String) properties.get("type"));
323
324                 for (Map<String, String> defaultProperty : nodeDefaults) {
325                         champObjBuilder.property(defaultProperty.get("attr.name"), defaultProperty.get("default"));
326                 }
327
328                 properties.remove("type");
329
330                 champObjBuilder.properties(properties)
331                                                 .property("importAssignedId", importAssignedId);
332
333                 final ChampObject objectToStore = champObjBuilder.build();
334
335                 try {  
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");
345         }
346         }
347
348         @Override
349         public void exportData(ChampGraph graph, OutputStream os) {
350
351                 final XMLOutputFactory output = XMLOutputFactory.newInstance();
352
353                 try {
354                         final XMLStreamWriter writer = output.createXMLStreamWriter(os);
355
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");
361
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();
367
368                         graph.queryObjects(Collections.emptyMap(), Optional.empty()).forEach(object -> {
369                                 nodes.add(object);
370
371                                 for (Map.Entry<String, Object> property : object.getProperties().entrySet()) {
372                                         if (nodeKeys.containsKey(property.getKey())) continue;
373
374                                         nodeKeys.put(property.getKey(), new GraphMLKey("d" + elementCount.incrementAndGet(), property.getKey(), property.getValue().getClass()));
375                                 }
376
377                                 nodeKeys.put("type", new GraphMLKey("d" + elementCount.incrementAndGet(), "type", String.class));
378                         });
379
380                         graph.queryRelationships(Collections.emptyMap(), Optional.empty()).forEach(relationship -> {
381                                 edges.add(relationship);
382
383                                 for (Map.Entry<String, Object> property : relationship.getProperties().entrySet()) {
384                                         if (nodeKeys.containsKey(property.getKey())) continue;
385
386                                         edgeKeys.put(property.getKey(), new GraphMLKey("d" + elementCount.incrementAndGet(), property.getKey(), property.getValue().getClass()));
387                                 }
388
389                                 edgeKeys.put("type", new GraphMLKey("d" + elementCount.incrementAndGet(), "type", String.class));
390                         });
391
392                         for (Entry<String, GraphMLKey> nodeKey : nodeKeys.entrySet()) {
393                                 final GraphMLKey graphMlKey = nodeKey.getValue();
394
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();
401                         }
402
403                         for (Entry<String, GraphMLKey> edgeKey : edgeKeys.entrySet()) {
404                                 final GraphMLKey graphMlKey = edgeKey.getValue();
405
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();
412                         }
413
414                         for (ChampObject object : nodes) {
415                                 try {
416                                         writer.writeStartElement("node");
417                                         writer.writeAttribute("id", String.valueOf(object.getKey().get()));
418
419                                         writer.writeStartElement("data");
420                                         writer.writeAttribute("key", nodeKeys.get("type").id);
421                                         writer.writeCharacters(object.getType());
422                                         writer.writeEndElement();
423
424                                         for (Entry<String, Object> property : object.getProperties().entrySet()) {
425                                                 final GraphMLKey key = nodeKeys.get(property.getKey());
426
427                                                 writer.writeStartElement("data");
428                                                 writer.writeAttribute("key", key.id);
429                                                 writer.writeCharacters(String.valueOf(property.getValue()));
430                                                 writer.writeEndElement();
431                                         }
432
433                                         writer.writeEndElement();
434                                 } catch (XMLStreamException e) {
435                                         throw new RuntimeException("Failed to write edge to output stream", e);
436                                 }
437                         }
438
439                         for (ChampRelationship relationship : edges) {
440                                 try {
441                                         writer.writeStartElement("edge");
442                                         writer.writeAttribute("id", String.valueOf(relationship.getKey().get()));
443
444                                         writer.writeStartElement("data");
445                                         writer.writeAttribute("key", edgeKeys.get("type").id);
446                                         writer.writeCharacters(relationship.getType());
447                                         writer.writeEndElement();
448
449                                         for (Entry<String, Object> property : relationship.getProperties().entrySet()) {
450                                                 final GraphMLKey key = edgeKeys.get(property.getKey());
451
452                                                 writer.writeStartElement("data");
453                                                 writer.writeAttribute("key", key.id);
454                                                 writer.writeCharacters(String.valueOf(property.getValue()));
455                                                 writer.writeEndElement();
456                                         }
457
458                                         writer.writeEndElement();
459                                 } catch (XMLStreamException e) {
460                                         throw new RuntimeException("Failed to write edge to output stream", e);
461                                 }
462                         }
463
464                         writer.writeEndElement();
465                         writer.writeEndDocument();
466                         writer.flush();
467                 } catch (XMLStreamException | ChampTransactionException e) {
468                         throw new RuntimeException(e);
469                 }
470         }
471 }