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 com.google.gson.Gson;
24 import com.thinkaurelius.titan.core.*;
25 import org.apache.commons.configuration.BaseConfiguration;
26 import org.apache.commons.lang3.tuple.ImmutablePair;
27 import org.apache.tinkerpop.gremlin.structure.*;
28 import org.apache.tinkerpop.gremlin.structure.io.IoCore;
29 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
30 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONReader;
31 import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
32 import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
33 import org.openecomp.sdc.asdctool.Utils;
34 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
35 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
36 import org.openecomp.sdc.common.log.wrappers.Logger;
40 import java.util.Map.Entry;
42 public class GraphMLConverter {
44 private static Logger log = Logger.getLogger(GraphMLConverter.class.getName());
46 private Gson gson = new Gson();
48 public boolean importGraph(String[] args) {
50 TitanGraph graph = null;
52 String titanFileLocation = args[1];
53 String inputFile = args[2];
54 graph = openGraph(titanFileLocation);
56 List<ImmutablePair<String, String>> propertiesCriteriaToDelete = new ArrayList<>();
57 ImmutablePair<String, String> immutablePair1 = new ImmutablePair<String, String>("healthcheckis", "GOOD");
58 ImmutablePair<String, String> immutablePair2 = new ImmutablePair<String, String>("nodeLabel", "user");
59 ImmutablePair<String, String> immutablePair3 = new ImmutablePair<String, String>("nodeLabel",
61 ImmutablePair<String, String> immutablePair4 = new ImmutablePair<String, String>("nodeLabel",
64 propertiesCriteriaToDelete.add(immutablePair1);
65 propertiesCriteriaToDelete.add(immutablePair2);
66 propertiesCriteriaToDelete.add(immutablePair3);
67 propertiesCriteriaToDelete.add(immutablePair4);
69 boolean result = importJsonGraph(graph, inputFile, propertiesCriteriaToDelete);
73 } catch (Exception e) {
74 log.info("import graph failed - {} " , e);
85 public boolean exportGraph(String[] args) {
87 TitanGraph graph = null;
89 String titanFileLocation = args[1];
90 String outputDirectory = args[2];
91 graph = openGraph(titanFileLocation);
93 String result = exportJsonGraph(graph, outputDirectory);
99 System.out.println("Exported file=" + result);
100 } catch (Exception e) {
101 log.info("export graph failed -{}" , e);
113 public String exportGraphMl(String[] args) {
115 TitanGraph graph = null;
116 String result = null;
118 String titanFileLocation = args[1];
119 String outputDirectory = args[2];
120 graph = openGraph(titanFileLocation);
122 result = exportGraphMl(graph, outputDirectory);
124 System.out.println("Exported file=" + result);
125 } catch (Exception e) {
126 log.info("export exportGraphMl failed - {}" , e);
137 public boolean findErrorInJsonGraph(String[] args) {
139 TitanGraph graph = null;
141 String titanFileLocation = args[1];
142 String outputDirectory = args[2];
143 graph = openGraph(titanFileLocation);
145 String result = findErrorInJsonGraph(graph, outputDirectory);
147 if (result == null) {
151 System.out.println("Exported file=" + result);
152 } catch (Exception e) {
153 log.info("find Error In Json Graph failed - {}" , e);
165 public TitanGraph openGraph(String titanFileLocation) {
167 TitanGraph graph = TitanFactory.open(titanFileLocation);
173 public String exportJsonGraph(TitanGraph graph, String outputDirectory) {
175 String result = null;
177 // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
179 String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".json";
181 OutputStream out = null;
183 out = new BufferedOutputStream(new FileOutputStream(outputFile));
185 // GraphSONWriter.outputGraph(graph, outputFile);
186 final GraphSONWriter.Builder builder = GraphSONWriter.build();
187 final GraphSONMapper mapper = newGraphSONMapper(graph);
188 builder.mapper(mapper);
189 final GraphSONWriter writer = builder.create();
190 writer.writeGraph(out, graph);
192 // GraphSONWriter create = GraphSONWriter.build(). create();
193 // create.writeGraph(out, graph);
200 } catch (Exception e) {
201 log.info("export Json Graph failed - {}" , e);
202 graph.tx().rollback();
208 } catch (IOException e) {
209 log.info("close FileOutputStream failed - {}" , e);
216 public String exportGraphMl(TitanGraph graph, String outputDirectory) {
217 String result = null;
218 String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
220 try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
221 graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
225 } catch (Exception e) {
226 graph.tx().rollback();
227 log.info("export Graph Ml failed - {}" , e);
233 private static GraphSONMapper newGraphSONMapper(final Graph graph) {
234 final GraphSONMapper.Builder builder = graph.io(IoCore.graphson()).mapper();
235 // Different failure with embedded type info.
236 // builder.embedTypes(true);
237 return builder.create();
240 public boolean importJsonGraph(TitanGraph graph, String graphJsonFile,
241 List<ImmutablePair<String, String>> propertiesCriteriaToDelete) {
243 boolean result = false;
245 InputStream is = null;
249 if (propertiesCriteriaToDelete != null) {
250 for (Entry<String, String> entry : propertiesCriteriaToDelete
254 String key = entry.getKey();
255 String value = entry.getValue();
256 Iterator iterator = graph.query().has(key, value).vertices().iterator();
257 while (iterator.hasNext()) {
258 Vertex vertex = (Vertex) iterator.next();
260 System.out.println("Remove vertex of type " + key + " and value " + value);
265 File file = new File(graphJsonFile);
266 if (false == file.isFile()) {
267 System.out.println("File " + graphJsonFile + " cannot be found.");
271 is = new BufferedInputStream(new FileInputStream(graphJsonFile));
272 System.out.println("Before importing file " + graphJsonFile);
274 // GraphSONReader.inputGraph(graph, graphJsonFile);
275 GraphSONReader create = GraphSONReader.build().create();
276 create.readGraph(is, graph);
283 } catch (Exception e) {
284 System.out.println("Failed to import graph " + e.getMessage());
285 log.info("Failed to import graph - {}" , e);
287 graph.tx().rollback();
293 } catch (IOException e) {
294 log.info("close FileOutputStream failed - {}" , e);
302 public String findErrorInJsonGraph(TitanGraph graph, String outputDirectory) {
304 boolean runVertexScan = false;
305 boolean runEdgeScan = false;
307 String result = null;
309 // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
311 String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".json";
313 OutputStream out = null;
315 out = new BufferedOutputStream(new FileOutputStream(outputFile));
319 Vertex vertexFrom = null;
320 Vertex vertexTo = null;
323 // Iterable<Edge> edges = graph.getEdges();
324 // Iterable<Edge> edges = graph.query().edges();
325 Iterable<TitanEdge> edges = graph.query().edges();
326 // Iterator<Edge> iterator = edges.iterator();
327 Iterator<TitanEdge> iterator = edges.iterator();
328 while (iterator.hasNext()) {
332 edge = iterator.next();
334 // vertexFrom = edge.getVertex(Direction.OUT);
335 // vertexTo = edge.getVertex(Direction.IN);
336 vertexFrom = edge.outVertex();
337 vertexTo = edge.inVertex();
339 BaseConfiguration conf = new BaseConfiguration();
340 conf.setProperty("storage.backend", "inmemory");
341 TitanGraph openGraph = Utils.openGraph(conf);
343 TitanVertex addVertexFrom = openGraph.addVertex();
344 // ElementHelper.setProperties(addVertexFrom,
345 // ElementHelper.getProperties(vertexFrom));
346 Utils.setProperties(addVertexFrom, Utils.getProperties(vertexFrom));
348 TitanVertex addVertexTo = openGraph.addVertex();
349 // ElementHelper.setProperties(addVertexTo,
350 // ElementHelper.getProperties(vertexTo));
351 Utils.setProperties(addVertexTo, Utils.getProperties(vertexTo));
353 // Edge addEdge = openGraph.addEdge(null, addVertexFrom,
354 // addVertexTo, edge.getLabel());
356 // Edge edge = tGraph.addEdge(null,
357 // fromV.left().value(), toV.left().value(), type);
359 Edge addEdge = addVertexFrom.addEdge(edge.label(), addVertexTo);
360 // ElementHelper.setProperties(addEdge,
361 // ElementHelper.getProperties(edge));
362 Utils.setProperties(addEdge, Utils.getProperties(edge));
364 log.info("fromVertex={}", Utils.getProperties(vertexFrom));
365 log.info("toVertex={}", Utils.getProperties(vertexTo));
366 log.info("edge={} {} ",edge.label(),Utils.getProperties(edge));
368 // GraphSONWriter.outputGraph(openGraph, outputFile);
369 GraphSONWriter create = GraphSONWriter.build().create();
370 create.writeGraph(out, openGraph);
372 // openGraph.rollback();
373 openGraph.tx().rollback();
375 } catch (Exception e) {
376 log.info("run Edge Scan failed - {}" , e);
378 log.error("fromVertex={}", Utils.getProperties(vertexFrom));
379 log.error("toVertex={}", Utils.getProperties(vertexTo));
380 log.error("edge={} {} ",edge.label(),Utils.getProperties(edge));
388 graph.tx().rollback();
394 Vertex vertex = null;
395 // Iterable<Vertex> vertices = graph.getVertices();
397 // Iterator<Vertex> iteratorVertex = vertices.iterator();
398 Iterator<Vertex> iteratorVertex = graph.vertices();
399 while (iteratorVertex.hasNext()) {
403 vertex = iteratorVertex.next();
405 // Iterable<Edge> edges2 =
406 // vertex.getEdges(Direction.BOTH);
408 // Iterator<Edge> iterator2 = edges2.iterator();
409 Iterator<Edge> iterator2 = vertex.edges(Direction.BOTH);
410 if (false == iterator2.hasNext()) {
412 BaseConfiguration conf = new BaseConfiguration();
413 conf.setProperty("storage.backend", "inmemory");
414 TitanGraph openGraph = Utils.openGraph(conf);
416 TitanVertex addVertexFrom = openGraph.addVertex();
417 Utils.setProperties(addVertexFrom, Utils.getProperties(vertex));
419 log.info("fromVertex={}", Utils.getProperties(addVertexFrom));
421 GraphSONWriter create = GraphSONWriter.build().create();
422 create.writeGraph(out, openGraph);
424 openGraph.tx().rollback();
428 } catch (Exception e) {
429 log.info("run Vertex Scan failed - {}" , e);
431 Object property1 = vertex.value(GraphPropertiesDictionary.HEALTH_CHECK.getProperty());
432 System.out.println(property1);
434 Object property2 = vertex.value("healthcheck");
435 System.out.println(property2);
443 graph.tx().rollback();
447 // Iterable<Vertex> vertices2 =
448 // graph.getVertices(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(),
450 Iterable<TitanVertex> vertices2 = graph.query()
451 .has(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(), "GOOD").vertices();
453 Vertex next = vertices2.iterator().next();
455 BaseConfiguration conf = new BaseConfiguration();
456 conf.setProperty("storage.backend", "inmemory");
457 TitanGraph openGraph = Utils.openGraph(conf);
459 // TitanVertex addVertexFrom = openGraph.addVertex();
461 // addVertexFrom.setProperty(GraphPropertiesDictionary.HEALTH_CHECK.getProperty(),
463 // addVertexFrom.setProperty("healthcheck",
464 // next.getProperty("healthcheck"));
468 // next.removeProperty("healthcheck");
469 // next.removeProperty("healthcheckis");
473 // GraphSONWriter.outputGraph(openGraph, outputFile);
475 for (NodeTypeEnum nodeTypeEnum : NodeTypeEnum.values()) {
476 removeNodesByLabel(graph, nodeTypeEnum.getName());
479 // GraphSONWriter.outputGraph(graph, outputFile);
481 GraphSONWriter create = GraphSONWriter.build().create();
482 create.writeGraph(out, graph);
485 graph.tx().rollback();
487 } catch (Exception e) {
488 log.info("find Error In Json Graph failed - {}" , e);
490 graph.tx().rollback();
496 } catch (IOException e) {
497 log.info("close FileOutputStream failed - {}" , e);
504 private void removeNodesByLabel(TitanGraph graph, String label) {
505 Iterable<TitanVertex> vertices = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), label)
507 Iterator<TitanVertex> iterator = vertices.iterator();
508 while (iterator.hasNext()) {
509 Vertex next2 = iterator.next();
514 public static void clearGraph(TitanGraph graph) {
516 Iterable<TitanVertex> vertices = graph.query().vertices();
520 if (vertices != null) {
521 Iterator<TitanVertex> iterator = vertices.iterator();
522 while (iterator.hasNext()) {
523 Vertex vertex = iterator.next();
524 // graph.removeVertex(vertex);
531 System.out.println("After erasing " + erased + " vertices.");
536 public String exportUsers(TitanGraph graph, String outputDirectory) {
538 List<Map<String, Object>> users = new ArrayList<>();
539 String result = null;
541 // GraphMLWriter graphMLWriter = new GraphMLWriter(graph);
543 String outputFile = outputDirectory + File.separator + "users." + System.currentTimeMillis() + ".json";
545 FileWriter fileWriter = null;
548 TitanGraphQuery graphQuery = graph.query().has(GraphPropertiesDictionary.LABEL.getProperty(),
549 NodeTypeEnum.User.getName());
551 @SuppressWarnings("unchecked")
552 Iterable<TitanVertex> vertices = graphQuery.vertices();
554 if (vertices != null) {
555 for (Vertex v : vertices) {
556 Map<String, Object> properties = getProperties(v);
557 properties.remove(GraphPropertiesDictionary.LABEL.getProperty());
558 users.add(properties);
564 String jsonUsers = gson.toJson(users);
566 fileWriter = new FileWriter(outputFile);
567 fileWriter.write(jsonUsers);
571 } catch (Exception e) {
572 log.info("export Users failed - {}" , e);
573 graph.tx().rollback();
576 if (fileWriter != null) {
579 } catch (IOException e) {
580 log.info("close FileOutputStream failed - {}" , e);
587 public Map<String, Object> getProperties(Element element) {
589 Map<String, Object> result = new HashMap<String, Object>();
592 if (element.keys() != null && element.keys().size() > 0) {
593 Map<String, Property> propertyMap = ElementHelper.propertyMap(element,
594 element.keys().toArray(new String[element.keys().size()]));
596 for (Entry<String, Property> entry : propertyMap.entrySet()) {
597 String key = entry.getKey();
598 Object value = entry.getValue().value();
600 result.put(key, value);
606 public boolean exportUsers(String[] args) {
608 TitanGraph graph = null;
610 String titanFileLocation = args[1];
611 String outputDirectory = args[2];
612 graph = openGraph(titanFileLocation);
614 String result = exportUsers(graph, outputDirectory);
616 if (result == null) {
620 System.out.println("Exported file=" + result);
621 } catch (Exception e) {
622 log.info("export Users failed - {}" , e);