2 * JavaInspect - Utility to visualize java software
3 * Copyright (C) 2013, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 2 of the GNU General Public License
7 * as published by the Free Software Foundation.
10 package eu.svjatoslav.inspector.java.structure;
13 import java.io.IOException;
14 import java.io.PrintWriter;
15 import java.util.HashMap;
18 import eu.svjatoslav.commons.file.CommonPathResolver;
20 public class ClassGraph {
23 * Maps class fully qualified names to class descriptors.
25 Map<String, ClassDescriptor> nameToClassMap = new HashMap<String, ClassDescriptor>();
27 public Filter filter = new Filter();
32 public ClassGraph(final Class<? extends Object> clazz) {
36 public ClassGraph(final Object root) {
37 addClass(root.getClass());
40 public ClassDescriptor addClass(final Class<? extends Object> clazz) {
45 final String className = clazz.getName();
47 if (nameToClassMap.containsKey(className))
48 return nameToClassMap.get(className);
50 return new ClassDescriptor(clazz, this);
53 public ClassDescriptor addObject(final Object object) {
54 return addClass(object.getClass());
57 public void generateGraph(final String graphName) {
58 generateGraph(graphName, false);
61 public void generateGraph(final String graphName, final boolean keepDotFile) {
63 final String desktopPath = CommonPathResolver.getDesktopDirectory()
64 .getAbsolutePath() + "/";
66 final String dotFilePath = desktopPath + graphName + ".dot";
67 final String imageFilePath = desktopPath + graphName + ".png";
69 System.out.println("Dot file path:" + dotFilePath);
72 // write DOT file to disk
73 final PrintWriter out = new PrintWriter(dotFilePath);
77 // execute GraphViz to visualize graph
80 .exec(new String[] { "dot", "-Tpng", dotFilePath, "-o",
81 imageFilePath }).waitFor();
82 } catch (final InterruptedException e) {
88 final File dotFile = new File(dotFilePath);
91 } catch (final IOException e) {
92 System.err.println(e);
96 private String getDot() {
97 final StringBuffer result = new StringBuffer();
99 result.append("digraph Java {\n");
100 result.append("graph [rankdir=LR, overlap = false, concentrate=true];\n");
102 for (final Map.Entry<String, ClassDescriptor> entry : nameToClassMap
104 result.append(entry.getValue().getDot());
106 result.append("}\n");
108 final String resultStr = result.toString();