2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.asdctool.impl;
23 import java.io.BufferedInputStream;
24 import java.io.BufferedOutputStream;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.FileWriter;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.OutputStream;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Map.Entry;
39 import org.apache.commons.configuration.BaseConfiguration;
40 import org.apache.commons.lang3.tuple.ImmutablePair;
41 import org.apache.tinkerpop.gremlin.structure.Direction;
42 import org.apache.tinkerpop.gremlin.structure.Edge;
43 import org.apache.tinkerpop.gremlin.structure.Element;
44 import org.apache.tinkerpop.gremlin.structure.Graph;
45 import org.apache.tinkerpop.gremlin.structure.Property;
46 import org.apache.tinkerpop.gremlin.structure.Vertex;
47 import org.apache.tinkerpop.gremlin.structure.io.IoCore;
48 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
49 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONReader;
50 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
51 import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
52 import org.openecomp.sdc.asdctool.Utils;
53 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
54 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 import com.google.gson.Gson;
59 import com.thinkaurelius.titan.core.TitanEdge;
60 import com.thinkaurelius.titan.core.TitanFactory;
61 import com.thinkaurelius.titan.core.TitanGraph;
62 import com.thinkaurelius.titan.core.TitanGraphQuery;
63 import com.thinkaurelius.titan.core.TitanVertex;
65 public class GraphMLConverter {
67 private static Logger log = LoggerFactory.getLogger(GraphMLConverter.class.getName());
69 private Gson gson = new Gson();
71 public boolean importGraph(String[] args) {
73 TitanGraph graph = null;
75 String titanFileLocation = args[1];
76 String inputFile = args[2];
77 graph = openGraph(titanFileLocation);
79 List<ImmutablePair<String, String>> propertiesCriteriaToDelete = new ArrayList<>();
80 ImmutablePair<String, String> immutablePair1 = new ImmutablePair<String, String>("healthcheckis", "GOOD");
81 ImmutablePair<String, String> immutablePair2 = new ImmutablePair<String, String>("nodeLabel", "user");
82 ImmutablePair<String, String> immutablePair3 = new ImmutablePair<String, String>("nodeLabel",
84 ImmutablePair<String, String> immutablePair4 = new ImmutablePair<String, String>("nodeLabel",
87 propertiesCriteriaToDelete.add(immutablePair1);
88 propertiesCriteriaToDelete.add(immutablePair2);
89 propertiesCriteriaToDelete.add(immutablePair3);
90 propertiesCriteriaToDelete.add(immutablePair4);
92 boolean result = importJsonGraph(graph, inputFile, propertiesCriteriaToDelete);
96 } catch (Exception e) {
108 public boolean exportGraph(String[] args) {
110 TitanGraph graph = null;
112 String titanFileLocation = args[1];
113 String outputDirectory = args[2];
114 graph = openGraph(titanFileLocation);
116 String result = exportJsonGraph(graph, outputDirectory);
118 if (result == null) {
122 System.out.println("Exported file=" + result);
123 } catch (Exception e) {
136 public String exportGraphMl(String[] args) {
138 TitanGraph graph = null;
139 String result = null;
141 String titanFileLocation = args[1];
142 String outputDirectory = args[2];
143 graph = openGraph(titanFileLocation);
145 result = exportGraphMl(graph, outputDirectory);
147 System.out.println("Exported file=" + result);
148 } catch (Exception e) {
160 public boolean findErrorInJsonGraph(String[] args) {
162 TitanGraph graph = null;
164 String titanFileLocation = args[1];
165 String outputDirectory = args[2];
166 graph = openGraph(titanFileLocation);
168 String result = findErrorInJsonGraph(graph, outputDirectory);
170 if (result == null) {
174 System.out.println("Exported file=" + result);
175 } catch (Exception e) {
188 public TitanGraph openGraph(String titanFileLocation) {
190 TitanGraph graph = TitanFactory.open(titanFileLocation);
196 public String exportJsonGraph(TitanGraph graph, String outputDirectory) {
198 String result = null;
200 // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
202 String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".json";
204 OutputStream out = null;
206 out = new BufferedOutputStream(new FileOutputStream(outputFile));
208 // GraphSONWriter.outputGraph(graph, outputFile);
209 final GraphSONWriter.Builder builder = GraphSONWriter.build();
210 final GraphSONMapper mapper = newGraphSONMapper(graph);
211 builder.mapper(mapper);
212 final GraphSONWriter writer = builder.create();
213 writer.writeGraph(out, graph);
215 // GraphSONWriter create = GraphSONWriter.build(). create();
216 // create.writeGraph(out, graph);
223 } catch (Exception e) {
225 graph.tx().rollback();
231 } catch (IOException e) {
239 public String exportGraphMl(TitanGraph graph, String outputDirectory) {
240 String result = null;
241 String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
243 try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
244 graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
248 } catch (Exception e) {
249 graph.tx().rollback();
256 private static GraphSONMapper newGraphSONMapper(final Graph graph) {
257 final GraphSONMapper.Builder builder = graph.io(IoCore.graphson()).mapper();
258 // Different failure with embedded type info.
259 // builder.embedTypes(true);
260 return builder.create();
263 public boolean importJsonGraph(TitanGraph graph, String graphJsonFile,
264 List<ImmutablePair<String, String>> propertiesCriteriaToDelete) {
266 boolean result = false;
268 InputStream is = null;
272 if (propertiesCriteriaToDelete != null) {
273 for (Entry<String, String> entry : propertiesCriteriaToDelete
277 String key = entry.getKey();
278 String value = entry.getValue();
279 Iterator iterator = graph.query().has(key, value).vertices().iterator();
280 while (iterator.hasNext()) {
281 Vertex vertex = (Vertex) iterator.next();
283 System.out.println("Remove vertex of type " + key + " and value " + value);
288 File file = new File(graphJsonFile);
289 if (false == file.isFile()) {
290 System.out.println("File " + graphJsonFile + " cannot be found.");
294 is = new BufferedInputStream(new FileInputStream(graphJsonFile));
295 System.out.println("Before importing file " + graphJsonFile);
297 // GraphSONReader.inputGraph(graph, graphJsonFile);
298 GraphSONReader create = GraphSONReader.build().create();
299 create.readGraph(is, graph);
306 } catch (Exception e) {
307 System.out.println("Failed to import graph " + e.getMessage());
310 graph.tx().rollback();
316 } catch (IOException e) {
325 public String findErrorInJsonGraph(TitanGraph graph, String outputDirectory) {
327 boolean runVertexScan = false;
328 boolean runEdgeScan = false;
330 String result = null;
332 // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
334 String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".json";
336 OutputStream out = null;
338 out = new BufferedOutputStream(new FileOutputStream(outputFile));
342 Vertex vertexFrom = null;
343 Vertex vertexTo = null;
346 // Iterable<Edge> edges = graph.getEdges();
347 // Iterable<Edge> edges = graph.query().edges();
348 Iterable<TitanEdge> edges = graph.query().edges();
349 // Iterator<Edge> iterator = edges.iterator();
350 Iterator<TitanEdge> iterator = edges.iterator();
351 while (iterator.hasNext()) {
355 edge = iterator.next();
357 // vertexFrom = edge.getVertex(Direction.OUT);
358 // vertexTo = edge.getVertex(Direction.IN);
359 vertexFrom = edge.outVertex();
360 vertexTo = edge.inVertex();
362 BaseConfiguration conf = new BaseConfiguration();
363 conf.setProperty("storage.backend", "inmemory");
364 TitanGraph openGraph = Utils.openGraph(conf);
366 TitanVertex addVertexFrom = openGraph.addVertex();
367 // ElementHelper.setProperties(addVertexFrom,
368 // ElementHelper.getProperties(vertexFrom));
369 Utils.setProperties(addVertexFrom, Utils.getProperties(vertexFrom));
371 TitanVertex addVertexTo = openGraph.addVertex();
372 // ElementHelper.setProperties(addVertexTo,
373 // ElementHelper.getProperties(vertexTo));
374 Utils.setProperties(addVertexTo, Utils.getProperties(vertexTo));
376 // Edge addEdge = openGraph.addEdge(null, addVertexFrom,
377 // addVertexTo, edge.getLabel());
379 // Edge edge = tGraph.addEdge(null,
380 // fromV.left().value(), toV.left().value(), type);
382 Edge addEdge = addVertexFrom.addEdge(edge.label(), addVertexTo);
383 // ElementHelper.setProperties(addEdge,
384 // ElementHelper.getProperties(edge));
385 Utils.setProperties(addEdge, Utils.getProperties(edge));
387 log.info("fromVertex={}", Utils.getProperties(vertexFrom));
388 log.info("toVertex={}", Utils.getProperties(vertexTo));
389 log.info("edge={} {} ",edge.label(),Utils.getProperties(edge));
391 // GraphSONWriter.outputGraph(openGraph, outputFile);
392 GraphSONWriter create = GraphSONWriter.build().create();
393 create.writeGraph(out, openGraph);
395 // openGraph.rollback();
396 openGraph.tx().rollback();
398 } catch (Exception e) {
401 log.error("fromVertex={}", Utils.getProperties(vertexFrom));
402 log.error("toVertex={}", Utils.getProperties(vertexTo));
403 log.error("edge={} {} ",edge.label(),Utils.getProperties(edge));
411 graph.tx().rollback();
417 Vertex vertex = null;
418 // Iterable<Vertex> vertices = graph.getVertices();
420 // Iterator<Vertex> iteratorVertex = vertices.iterator();
421 Iterator<Vertex> iteratorVertex = graph.vertices();
422 while (iteratorVertex.hasNext()) {
426 vertex = iteratorVertex.next();
428 // Iterable<Edge> edges2 =
429 // vertex.getEdges(Direction.BOTH);
431 // Iterator<Edge> iterator2 = edges2.iterator();
432 Iterator<Edge> iterator2 = vertex.edges(Direction.BOTH);
433 if (false == iterator2.hasNext()) {
435 BaseConfiguration conf = new BaseConfiguration();
436 conf.setProperty("storage.backend", "inmemory");
437 TitanGraph openGraph = Utils.openGraph(conf);
439 TitanVertex addVertexFrom = openGraph.addVertex();
440 Utils.setProperties(addVertexFrom, Utils.getProperties(vertex));
442 log.info("fromVertex={}", Utils.getProperties(addVertexFrom));
444 GraphSONWriter create = GraphSONWriter.build().create();
445 create.writeGraph(out, openGraph);
447 openGraph.tx().rollback();
451 } catch (Exception e) {
454 Object property1 = vertex.value(GraphPropertiesDictionary.HEALTH_CHECK.getProperty());
455 System.out.println(property1);
457 Object property2 = vertex.value("healthcheck");
458 System.out.println(property2);
466 graph.tx().rollback();
470 // Iterable<Vertex> vertices2 =
471 // graph.getVertices(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(),
473 Iterable<TitanVertex> vertices2 = graph.query()
474 .has(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(), "GOOD").vertices();
476 Vertex next = vertices2.iterator().next();
478 BaseConfiguration conf = new BaseConfiguration();
479 conf.setProperty("storage.backend", "inmemory");
480 TitanGraph openGraph = Utils.openGraph(conf);
482 // TitanVertex addVertexFrom = openGraph.addVertex();
484 // addVertexFrom.setProperty(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(),
486 // addVertexFrom.setProperty("healthcheck",
487 // next.getProperty("healthcheck"));
491 // next.removeProperty("healthcheck");
492 // next.removeProperty("healthcheckis");
496 // GraphSONWriter.outputGraph(openGraph, outputFile);
498 for (NodeTypeEnum nodeTypeEnum : NodeTypeEnum.values()) {
499 removeNodesByLabel(graph, nodeTypeEnum.getName());
502 // GraphSONWriter.outputGraph(graph, outputFile);
504 GraphSONWriter create = GraphSONWriter.build().create();
505 create.writeGraph(out, graph);
508 graph.tx().rollback();
510 } catch (Exception e) {
513 graph.tx().rollback();
519 } catch (IOException e) {
527 private void removeNodesByLabel(TitanGraph graph, String label) {
528 Iterable<TitanVertex> vertices = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), label)
530 Iterator<TitanVertex> iterator = vertices.iterator();
531 while (iterator.hasNext()) {
532 Vertex next2 = iterator.next();
537 public static void clearGraph(TitanGraph graph) {
539 Iterable<TitanVertex> vertices = graph.query().vertices();
543 if (vertices != null) {
544 Iterator<TitanVertex> iterator = vertices.iterator();
545 while (iterator.hasNext()) {
546 Vertex vertex = iterator.next();
547 // graph.removeVertex(vertex);
554 System.out.println("After erasing " + erased + " vertices.");
559 public String exportUsers(TitanGraph graph, String outputDirectory) {
561 List<Map<String, Object>> users = new ArrayList<>();
562 String result = null;
564 // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
566 String outputFile = outputDirectory + File.separator + "users." + System.currentTimeMillis() + ".json";
568 FileWriter fileWriter = null;
571 TitanGraphQuery graphQuery = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(),
572 NodeTypeEnum.User.getName());
574 @SuppressWarnings("unchecked")
575 Iterable<TitanVertex> vertices = graphQuery.vertices();
577 if (vertices != null) {
578 for (Vertex v : vertices) {
579 Map<String, Object> properties = getProperties(v);
580 properties.remove(GraphPropertiesDictionary.LABEL.getProperty());
581 users.add(properties);
587 String jsonUsers = gson.toJson(users);
589 fileWriter = new FileWriter(outputFile);
590 fileWriter.write(jsonUsers);
594 } catch (Exception e) {
596 graph.tx().rollback();
599 if (fileWriter != null) {
602 } catch (IOException e) {
610 public Map<String, Object> getProperties(Element element) {
612 Map<String, Object> result = new HashMap<String, Object>();
615 if (element.keys() != null && element.keys().size() > 0) {
616 Map<String, Property> propertyMap = ElementHelper.propertyMap(element,
617 element.keys().toArray(new String[element.keys().size()]));
619 for (Entry<String, Property> entry : propertyMap.entrySet()) {
620 String key = entry.getKey();
621 Object value = entry.getValue().value();
623 result.put(key, value);
629 public boolean exportUsers(String[] args) {
631 TitanGraph graph = null;
633 String titanFileLocation = args[1];
634 String outputDirectory = args[2];
635 graph = openGraph(titanFileLocation);
637 String result = exportUsers(graph, outputDirectory);
639 if (result == null) {
643 System.out.println("Exported file=" + result);
644 } catch (Exception e) {