Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.69 KB | None | 0 0
  1. package core;
  2. // GraphViz.java - a simple API to call dot from Java programs
  3.  
  4. /*$Id$*/
  5. /*
  6.  ******************************************************************************
  7.  *                                                                            *
  8.  *                    (c) Copyright Laszlo Szathmary                          *
  9.  *                                                                            *
  10.  * This program is free software; you can redistribute it and/or modify it    *
  11.  * under the terms of the GNU Lesser General Public License as published by   *
  12.  * the Free Software Foundation; either version 2.1 of the License, or        *
  13.  * (at your option) any later version.                                        *
  14.  *                                                                            *
  15.  * This program is distributed in the hope that it will be useful, but        *
  16.  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
  17.  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public    *
  18.  * License for more details.                                                  *
  19.  *                                                                            *
  20.  * You should have received a copy of the GNU Lesser General Public License   *
  21.  * along with this program; if not, write to the Free Software Foundation,    *
  22.  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                              *
  23.  *                                                                            *
  24.  ******************************************************************************
  25.  */
  26.  
  27. import java.io.BufferedReader;
  28. import java.io.BufferedWriter;
  29. import java.io.DataInputStream;
  30. import java.io.File;
  31. import java.io.FileInputStream;
  32. import java.io.FileOutputStream;
  33. import java.io.FileWriter;
  34. import java.io.InputStreamReader;
  35. import java.util.Properties;
  36.  
  37. /**
  38.  * <dl>
  39.  * <dt>Purpose: GraphViz Java API
  40.  * <dd>
  41.  *
  42.  * <dt>Description:
  43.  * <dd> With this Java class you can simply call dot
  44.  *      from your Java programs.
  45.  * <dt>Example usage:
  46.  * <dd>
  47.  * <pre>
  48.  *    GraphViz gv = new GraphViz();
  49.  *    gv.addln(gv.start_graph());
  50.  *    gv.addln("A -> B;");
  51.  *    gv.addln("A -> C;");
  52.  *    gv.addln(gv.end_graph());
  53.  *    System.out.println(gv.getDotSource());
  54.  *
  55.  *    String type = "gif";
  56.  *    File out = new File("out." + type);   // out.gif in this example
  57.  *    gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out );
  58.  * </pre>
  59.  * </dd>
  60.  *
  61.  * </dl>
  62.  *
  63.  * @version v0.5.1, 2013/03/18 (March) -- Patch of Juan Hoyos (Mac support)
  64.  * @version v0.5, 2012/04/24 (April) -- Patch of Abdur Rahman (OS detection + start subgraph +
  65.  * read config file)
  66.  * @version v0.4, 2011/02/05 (February) -- Patch of Keheliya Gallaba is added. Now you
  67.  * can specify the type of the output file: gif, dot, fig, pdf, ps, svg, png, etc.
  68.  * @version v0.3, 2010/11/29 (November) -- Windows support + ability to read the graph from a text file
  69.  * @version v0.2, 2010/07/22 (July) -- bug fix
  70.  * @version v0.1, 2003/12/04 (December) -- first release
  71.  * @author  Laszlo Szathmary (<a href="jabba.laci@gmail.com">jabba.laci@gmail.com</a>)
  72.  */
  73. public class GraphViz
  74. {
  75.     /**
  76.      * Detects the client's operating system.
  77.      */
  78.     private final static String osName = System.getProperty("os.name").replaceAll("\\s","");
  79.  
  80.     /**
  81.      * Load the config.properties file.
  82.      */
  83.     private final static String cfgProp = "C:/Users/AQ38570/Desktop/graphviz_conf.txt";
  84.     private final static Properties configFile = new Properties() {
  85.         private final static long serialVersionUID = 1L; {
  86.             try {
  87.                 load(new FileInputStream(cfgProp));
  88.             } catch (Exception e) {}
  89.         }
  90.     };
  91.  
  92.     /**
  93.      * The dir. where temporary files will be created.
  94.      */
  95.   private static String TEMP_DIR = "C:/Users/AQ38570/Desktop/temp";
  96.  
  97.     /**
  98.      * Where is your dot program located? It will be called externally.
  99.      */
  100.   private static String DOT = configFile.getProperty("dotFor" + osName);
  101.  
  102.  
  103.     /**
  104.      * The image size in dpi. 96 dpi is normal size. Higher values are 10% higher each.
  105.      * Lower values 10% lower each.
  106.      *
  107.      * dpi patch by Peter Mueller
  108.      */
  109.     private int[] dpiSizes = {46, 51, 57, 63, 70, 78, 86, 96, 106, 116, 128, 141, 155, 170, 187, 206, 226, 249};
  110.  
  111.     /**
  112.      * Define the index in the image size array.
  113.      */
  114.     private int currentDpiPos = 7;
  115.  
  116.     /**
  117.      * Increase the image size (dpi).
  118.      */
  119.     public void increaseDpi() {
  120.         if ( this.currentDpiPos < (this.dpiSizes.length - 1) ) {
  121.             ++this.currentDpiPos;
  122.         }
  123.     }
  124.  
  125.     /**
  126.      * Decrease the image size (dpi).
  127.      */
  128.     public void decreaseDpi() {
  129.         if (this.currentDpiPos > 0) {
  130.             --this.currentDpiPos;
  131.         }
  132.     }
  133.  
  134.     public int getImageDpi() {
  135.         return this.dpiSizes[this.currentDpiPos];
  136.     }
  137.  
  138.     /**
  139.      * The source of the graph written in dot language.
  140.      */
  141.     private StringBuilder graph = new StringBuilder();
  142.  
  143.     /**
  144.      * Constructor: creates a new GraphViz object that will contain
  145.      * a graph.
  146.      */
  147.     public GraphViz() {
  148.          System.out.println(DOT + osName) ;
  149.     }
  150.  
  151.     /**
  152.      * Returns the graph's source description in dot language.
  153.      * @return Source of the graph in dot language.
  154.      */
  155.     public String getDotSource() {
  156.         return this.graph.toString();
  157.     }
  158.  
  159.     /**
  160.      * Adds a string to the graph's source (without newline).
  161.      */
  162.     public void add(String line) {
  163.         this.graph.append(line);
  164.     }
  165.  
  166.     /**
  167.      * Adds a string to the graph's source (with newline).
  168.      */
  169.     public void addln(String line) {
  170.         this.graph.append(line + "\n");
  171.     }
  172.  
  173.     /**
  174.      * Adds a newline to the graph's source.
  175.      */
  176.     public void addln() {
  177.         this.graph.append('\n');
  178.     }
  179.  
  180.     public void clearGraph(){
  181.         this.graph = new StringBuilder();
  182.     }
  183.  
  184.     /**
  185.      * Returns the graph as an image in binary format.
  186.      * @param dot_source Source of the graph to be drawn.
  187.      * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
  188.      * @return A byte array containing the image of the graph.
  189.      */
  190.     public byte[] getGraph(String dot_source, String type)
  191.     {
  192.         File dot;
  193.         byte[] img_stream = null;
  194.  
  195.         try {
  196.             dot = writeDotSourceToFile(dot_source);
  197.             if (dot != null)
  198.             {
  199.                 img_stream = get_img_stream(dot, type);
  200.                 if (dot.delete() == false)
  201.                     System.err.println("Warning: " + dot.getAbsolutePath() + " could not be deleted!");
  202.                 return img_stream;
  203.             }
  204.             return null;
  205.         } catch (java.io.IOException ioe) { return null; }
  206.     }
  207.  
  208.     /**
  209.      * Writes the graph's image in a file.
  210.      * @param img   A byte array containing the image of the graph.
  211.      * @param file  Name of the file to where we want to write.
  212.      * @return Success: 1, Failure: -1
  213.      */
  214.     public int writeGraphToFile(byte[] img, String file)
  215.     {
  216.         File to = new File(file);
  217.         return writeGraphToFile(img, to);
  218.     }
  219.  
  220.     /**
  221.      * Writes the graph's image in a file.
  222.      * @param img   A byte array containing the image of the graph.
  223.      * @param to    A File object to where we want to write.
  224.      * @return Success: 1, Failure: -1
  225.      */
  226.     public int writeGraphToFile(byte[] img, File to)
  227.     {
  228.         try {
  229.             FileOutputStream fos = new FileOutputStream(to);
  230.             fos.write(img);
  231.             fos.close();
  232.         } catch (java.io.IOException ioe) { return -1; }
  233.         return 1;
  234.     }
  235.  
  236.     /**
  237.      * It will call the external dot program, and return the image in
  238.      * binary format.
  239.      * @param dot Source of the graph (in dot language).
  240.      * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
  241.      * @return The image of the graph in .gif format.
  242.      */
  243.     private byte[] get_img_stream(File dot, String type)
  244.     {
  245.         File img;
  246.         byte[] img_stream = null;
  247.  
  248.         try {
  249.             img = File.createTempFile("graph_", "."+type, new File(GraphViz.TEMP_DIR));
  250.             Runtime rt = Runtime.getRuntime();
  251.  
  252.             // patch by Mike Chenault
  253.             String[] args = {DOT, "-T"+type, "-Gdpi="+dpiSizes[this.currentDpiPos], dot.getAbsolutePath(), "-o", img.getAbsolutePath()};
  254.             Process p = rt.exec(args);
  255.  
  256.             p.waitFor();
  257.  
  258.             FileInputStream in = new FileInputStream(img.getAbsolutePath());
  259.             img_stream = new byte[in.available()];
  260.             in.read(img_stream);
  261.             // Close it if we need to
  262.             if( in != null ) in.close();
  263.  
  264.             if (img.delete() == false)
  265.                 System.err.println("Warning: " + img.getAbsolutePath() + " could not be deleted!");
  266.         }
  267.         catch (java.io.IOException ioe) {
  268.             System.err.println("Error:    in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR+"\n");
  269.             System.err.println("       or in calling external command");
  270.             ioe.printStackTrace();
  271.         }
  272.         catch (java.lang.InterruptedException ie) {
  273.             System.err.println("Error: the execution of the external program was interrupted");
  274.             ie.printStackTrace();
  275.         }
  276.  
  277.         return img_stream;
  278.     }
  279.  
  280.     /**
  281.      * Writes the source of the graph in a file, and returns the written file
  282.      * as a File object.
  283.      * @param str Source of the graph (in dot language).
  284.      * @return The file (as a File object) that contains the source of the graph.
  285.      */
  286.     private File writeDotSourceToFile(String str) throws java.io.IOException
  287.     {
  288.         File temp;
  289.         try {
  290.             temp = File.createTempFile("dorrr",".dot", new File(GraphViz.TEMP_DIR));
  291.             FileWriter fout = new FileWriter(temp);
  292.             fout.write(str);
  293.                        BufferedWriter br=new BufferedWriter(new FileWriter("dotsource.dot"));
  294.                        br.write(str);
  295.                        br.flush();
  296.                        br.close();
  297.             fout.close();
  298.         }
  299.         catch (Exception e) {
  300.             System.err.println("Error: I/O error while writing the dot source to temp file!");
  301.             return null;
  302.         }
  303.         return temp;
  304.     }
  305.  
  306.     /**
  307.      * Returns a string that is used to start a graph.
  308.      * @return A string to open a graph.
  309.      */
  310.     public String start_graph() {
  311.         return "digraph G {";
  312.     }
  313.  
  314.     /**
  315.      * Returns a string that is used to end a graph.
  316.      * @return A string to close a graph.
  317.      */
  318.     public String end_graph() {
  319.         return "}";
  320.     }
  321.  
  322.     /**
  323.      * Takes the cluster or subgraph id as input parameter and returns a string
  324.      * that is used to start a subgraph.
  325.      * @return A string to open a subgraph.
  326.      */
  327.     public String start_subgraph(int clusterid) {
  328.         return "subgraph cluster_" + clusterid + " {";
  329.     }
  330.  
  331.     /**
  332.      * Returns a string that is used to end a graph.
  333.      * @return A string to close a graph.
  334.      */
  335.     public String end_subgraph() {
  336.         return "}";
  337.     }
  338.  
  339.     /**
  340.      * Read a DOT graph from a text file.
  341.      *
  342.      * @param input Input text file containing the DOT graph
  343.      * source.
  344.      */
  345.     public void readSource(String input)
  346.     {
  347.         StringBuilder sb = new StringBuilder();
  348.  
  349.         try
  350.         {
  351.             FileInputStream fis = new FileInputStream(input);
  352.             DataInputStream dis = new DataInputStream(fis);
  353.             BufferedReader br = new BufferedReader(new InputStreamReader(dis));
  354.             String line;
  355.             while ((line = br.readLine()) != null) {
  356.                 sb.append(line);
  357.             }
  358.             dis.close();
  359.         }
  360.         catch (Exception e) {
  361.             System.err.println("Error: " + e.getMessage());
  362.         }
  363.  
  364.         this.graph = sb;
  365.     }
  366.     public static void createDotGraph(String dotFormat,String fileName)
  367.     {
  368.         GraphViz gv=new GraphViz();
  369.         gv.addln(gv.start_graph());
  370.         gv.add(dotFormat);
  371.         gv.addln(gv.end_graph());
  372.        // String type = "gif";
  373.         String type = "pdf";
  374.       // gv.increaseDpi();
  375.         gv.decreaseDpi();
  376.         gv.decreaseDpi();
  377.         File out = new File(fileName+"."+ type);
  378.         gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out );
  379.     }
  380.     public static void main(String[] args) throws Exception {
  381.         String dotFormat="1 [label = \"a<=5\" ]" ;
  382.         createDotGraph(dotFormat, "C:/Users/AQ38570/Desktop/DotGraph");
  383.  }
  384.  
  385. } // end of class GraphViz
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement