Example usage for org.jfree.chart ChartUtilities saveChartAsPNG

List of usage examples for org.jfree.chart ChartUtilities saveChartAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities saveChartAsPNG.

Prototype

public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height) throws IOException 

Source Link

Document

Saves a chart to the specified file in PNG format.

Usage

From source file:org.terracotta.offheapstore.paging.TableStealingFromStorageIT.java

@Test
@Ignore//  w  ww . j av a  2  s . com
public void testSelfStealingIsStable() throws IOException {
    PageSource source = new UpfrontAllocatingPageSource(new HeapBufferSource(), MEGABYTES.toBytes(2),
            MEGABYTES.toBytes(1));

    OffHeapHashMap<Integer, byte[]> selfStealer = new WriteLockedOffHeapClockCache<>(source, true,
            new SplitStorageEngine<>(new IntegerStorageEngine(), new OffHeapBufferHalfStorageEngine<>(source,
                    KILOBYTES.toBytes(16), ByteArrayPortability.INSTANCE, false, true)));

    // failing seed value
    //long seed = 1302292028471110000L;

    long seed = System.nanoTime();
    System.err.println("Random Seed = " + seed);
    Random rndm = new Random(seed);
    int payloadSize = rndm.nextInt(KILOBYTES.toBytes(1));
    System.err.println("Payload Size = " + payloadSize);

    List<Long> sizes = new ArrayList<>();
    List<Long> tableSizes = new ArrayList<>();

    int terminalKey = 0;
    for (int key = 0; true; key++) {
        int size = selfStealer.size();
        byte[] payload = new byte[payloadSize];
        Arrays.fill(payload, (byte) key);
        selfStealer.put(key, payload);
        sizes.add((long) selfStealer.size());
        tableSizes.add(selfStealer.getTableCapacity());
        if (size >= selfStealer.size()) {
            terminalKey = key;
            selfStealer.remove(terminalKey);
            break;
        }
    }

    System.err.println("Terminal Key = " + terminalKey);

    int shrinkCount = 0;
    for (int key = terminalKey; key < 10 * terminalKey; key++) {
        byte[] payload = new byte[payloadSize];
        Arrays.fill(payload, (byte) key);
        long preTableSize = selfStealer.getTableCapacity();
        selfStealer.put(key, payload);
        if (rndm.nextBoolean()) {
            selfStealer.remove(rndm.nextInt(key));
        }
        long postTableSize = selfStealer.getTableCapacity();
        if (preTableSize > postTableSize) {
            shrinkCount++;
        }
        sizes.add((long) selfStealer.size());
        tableSizes.add(postTableSize);
    }

    if (shrinkCount != 0) {
        Map<String, List<? extends Number>> data = new HashMap<>();
        data.put("actual size", sizes);
        data.put("table size", tableSizes);

        JFreeChart chart = ChartFactory.createXYLineChart("Cache Size", "operations", "size",
                new LongListXYDataset(data), PlotOrientation.VERTICAL, true, false, false);
        File plotOutput = new File("target/TableStealingFromStorageTest.testSelfStealingIsStable.png");
        ChartUtilities.saveChartAsPNG(plotOutput, chart, 640, 480);
        fail("Expected no shrink events after reaching equilibrium : saw " + shrinkCount + " [plot in "
                + plotOutput + "]");
    }
}

From source file:org.lmn.fc.common.datatranslators.DataExporter.java

/***********************************************************************************************
 * exportChart().//from   www.  j a va 2s  .co  m
 * This variant uses a fully specified filename.
 *
 * @param dao
 * @param chartui
 * @param metadatalist
 * @param fullfilename
 * @param type
 * @param width
 * @param height
 * @param log
 * @param clock
 * @param verbose
 *
 * @return boolean
 */

public static boolean exportChartUsingFilename(final ObservatoryInstrumentDAOInterface dao,
        final ChartUIComponentPlugin chartui, final List<Metadata> metadatalist, final String fullfilename,
        final String type, final int width, final int height, final Vector<Vector> log,
        final ObservatoryClockInterface clock, final boolean verbose) {
    final String SOURCE = "DataExporter.exportChartUsingFilename() ";
    final boolean boolDebug;
    boolean boolSuccess;

    boolDebug = (LOADER_PROPERTIES.isChartDebug() || LOADER_PROPERTIES.isMetadataDebug()
            || LOADER_PROPERTIES.isStaribusDebug() || LOADER_PROPERTIES.isStarinetDebug());

    boolSuccess = false;

    // Let the User know the Chart must have data!
    if ((fullfilename != null) && (!EMPTY_STRING.equals(fullfilename)) && (type != null)
            && (!EMPTY_STRING.equals(type)) && (chartui != null) && (log != null) && (clock != null)) {
        try {
            final File file;

            file = new File(fullfilename);
            FileUtilities.overwriteFile(file);

            // Force the Chart to be generated, even if not visible
            // This calls ChartHelper.associateChartUIWithDAO()
            chartui.refreshChart(dao, true, SOURCE);

            if ((chartui.getChartPanel() != null) && (chartui.getChartPanel().getChart() != null)) {
                if (FileUtilities.jpg.equalsIgnoreCase(type)) {
                    LOGGER.debug(boolDebug, SOURCE + "writing [file " + file.getAbsolutePath() + "] [width="
                            + width + "] [height" + height + "]");
                    ChartUtilities.saveChartAsJPEG(file, chartui.getChartPanel().getChart(), width, height);
                    boolSuccess = true;

                    if (verbose) {
                        SimpleEventLogUIComponent.logEvent(
                                log, EventStatus.INFO, METADATA_TARGET_CHART + METADATA_ACTION_EXPORT
                                        + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR,
                                SOURCE, clock);
                    }
                } else if (FileUtilities.png.equalsIgnoreCase(type)) {
                    LOGGER.debug(boolDebug, SOURCE + "writing [file " + file.getAbsolutePath() + "] [width="
                            + width + "] [height" + height + "]");
                    ChartUtilities.saveChartAsPNG(file, chartui.getChartPanel().getChart(), width, height);
                    boolSuccess = true;

                    if (verbose) {
                        SimpleEventLogUIComponent.logEvent(
                                log, EventStatus.INFO, METADATA_TARGET_CHART + METADATA_ACTION_EXPORT
                                        + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR,
                                SOURCE, clock);
                    }
                } else {
                    SimpleEventLogUIComponent
                            .logEvent(
                                    log, EventStatus.FATAL, METADATA_TARGET_CHART + METADATA_ACTION_EXPORT
                                            + METADATA_RESULT + ERROR_INVALID_FORMAT + TERMINATOR,
                                    SOURCE, clock);
                }
            }
        }

        catch (SecurityException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_ACCESS_DENIED
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (FileNotFoundException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_NOT_FOUND
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (IOException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_SAVE
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }
    } else {
        //            System.out.println("FILENAME=" + ((fullfilename != null) && (!EMPTY_STRING.equals(fullfilename))));
        //            System.out.println("TYPE=" + ((type != null) && (!EMPTY_STRING.equals(type))));
        //            System.out.println("CHART=" + (chart != null));
        //            System.out.println("LOG=" + (log != null));
        //            System.out.println("CLOCK=" + (clock != null));
        SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                METADATA_TARGET_CHART + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_CHART + TERMINATOR,
                SOURCE, clock);
    }

    return (boolSuccess);
}

From source file:playground.christoph.evacuation.analysis.AgentsInEvacuationAreaWriter.java

public void writeGraphic(final String filename, String title, String legend, String legMode, int[] data) {
    try {/*from  w  w  w.ja  v  a2 s  . co m*/
        ChartUtilities.saveChartAsPNG(new File(filename), getGraphic(title, legend, legMode, data), 1024, 768);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.NetworkIOReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {// w w  w  .j av  a2 s. co  m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents the network throughput rates of a machine over time.<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Send Rate</th><th>Average Recieve Rate</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(sendkbs) from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(receivekbs) from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td></tr>");

            //ok now get the raw data....
            TimeSeriesContainer tsc = new TimeSeriesContainer();
            try {
                cmd = con.prepareStatement(
                        "select receivekbs, sendkbs, utcdatetime, nicid from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {

                    TimeSeries ts = tsc.Get(url + " " + rs.getString("nicid") + " RX", Millisecond.class);
                    TimeSeries ts2 = tsc.Get(url + " " + rs.getString("nicid") + " TX", Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(3));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getLong(1));
                    ts2.addOrUpdate(m, rs.getLong(2));
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            for (int ik = 0; ik < tsc.data.size(); ik++) {
                col.addSeries(tsc.data.get(ik));
            }

        }

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Rate", col,
                true, false, false);

        data.append("</table>");
        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }

}

From source file:org.graphstream.algorithm.measure.ChartMeasure.java

/**
 * Output some charts according to a set of parameters. Actually, only one
 * chart is supported. According to {@link PlotParameters#outputType}, plot
 * is displayed on screen or saved in a file.
 * //from  ww w.ja va 2  s.  c  o m
 * @param params
 *            parameters used to plot
 * @param charts
 *            charts to output
 * @throws PlotException
 */
public static void outputPlot(PlotParameters params, JFreeChart... charts) throws PlotException {
    if (charts == null || charts.length == 0)
        throw new PlotException("no chart");

    if (charts.length > 1)
        throw new PlotException("multiple charts not yet supported");

    JFreeChart chart = charts[0];

    switch (params.outputType) {
    case SCREEN:
        ChartPanel panel = new ChartPanel(chart, params.width, params.height, params.width, params.height,
                params.width + 50, params.height + 50, true, true, true, true, true, true);

        JFrame frame = new JFrame(params.title);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

        break;
    case JPEG:
        try {
            ChartUtilities.saveChartAsJPEG(new File(params.path), chart, params.width, params.height);
        } catch (IOException e) {
            throw new PlotException(e);
        }

        break;
    case PNG:
        try {
            ChartUtilities.saveChartAsPNG(new File(params.path), chart, params.width, params.height);
        } catch (IOException e) {
            throw new PlotException(e);
        }

        break;
    }

}

From source file:playground.dgrether.analysis.categoryhistogram.CategoryHistogramWriter.java

/**
 * Writes a graphic showing the number of departures, arrivals and vehicles
 * en route of all legs/trips with the specified transportation mode to the
 * specified file./*  ww w  .j a  v a 2  s.co m*/
 *
 * @param filename
 * @param legMode
 *
 * @see #getGraphic(String)
 */
public void writeGraphic(final CategoryHistogram modeData, final String filename, final String legMode) {
    try {
        ChartUtilities.saveChartAsPNG(new File(filename), getGraphic(modeData, legMode), 1024, 768);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:no.uio.medicine.virsurveillance.charts.BoxAndWhiskerChart_AWT.java

/**
 * For testing from the command line./*from www .j  ava 2 s  .  c  o  m*/
 *
 * @param args ignored.
 */
public void save2File(File outputFile) throws IOException {
    ChartUtilities cu = new ChartUtilities() {
    };
    ChartUtilities.saveChartAsPNG(outputFile, this.chartPanel.getChart(), 1200, 500);
    System.out.println("Saved at " + outputFile.toString() + " size = " + 1200 + "x" + 500);
}

From source file:GraphUI.java

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
    int width = 640;
    int height = 480;
    fc = new JFileChooser();
    fc.addChoosableFileFilter(new FileNameExtensionFilter("PNG (*.png)", "png"));
    fc.setAcceptAllFileFilterUsed(false);
    fc.showSaveDialog(null);/*w w w .  ja v  a2s. c  om*/

    String path = fc.getSelectedFile().getAbsolutePath() + ".png";
    String filename = fc.getSelectedFile().getName() + ".png";
    File imageFile = new File(path);

    /*
    System.out.println("getCurrentDirectory(): "
        + f.getCurrentDirectory());
    System.out.println("getSelectedFile() : "
        + f.getSelectedFile());
     */
    try {
        ChartUtilities.saveChartAsPNG(imageFile, chart, width, height);
        JOptionPane.showMessageDialog(null, "Graph saved as " + filename);
    } catch (IOException ex) {
        System.err.println(ex);
    }

}

From source file:com.jolbox.benchmark.BenchmarkLaunch.java

/**
 * @param results//from ww w. j  a v a 2  s .com
 * @param delay 
 * @param statementBenchmark 
 * @param noC3P0 
 * @throws IOException 
 */
private static void doPlotLineGraph(long[][] results, int delay, boolean statementBenchmark, boolean noC3P0)
        throws IOException {
    String title = "Multi-Thread test (" + delay + "ms delay)";
    if (statementBenchmark) {
        title += "\n(with PreparedStatements tests)";
    }
    String fname = System.getProperty("java.io.tmpdir") + File.separator + "bonecp-multithread-" + delay
            + "ms-delay";
    if (statementBenchmark) {
        fname += "-with-preparedstatements";
    }
    fname += "-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads;
    if (noC3P0) {
        fname += "-noC3P0";
    }
    PrintWriter out = new PrintWriter(new FileWriter(fname + ".txt"));
    fname += ".png";

    XYSeriesCollection dataset = new XYSeriesCollection();
    for (int i = 0; i < ConnectionPoolType.values().length; i++) { //
        if (!ConnectionPoolType.values()[i].isEnabled()
                || (noC3P0 && ConnectionPoolType.values()[i].equals(ConnectionPoolType.C3P0))) {
            continue;
        }
        XYSeries series = new XYSeries(ConnectionPoolType.values()[i].toString());
        out.println(ConnectionPoolType.values()[i].toString());
        for (int j = 1 + BenchmarkTests.stepping; j < results[i].length; j += BenchmarkTests.stepping) {
            series.add(j, results[i][j]);
            out.println(j + "," + results[i][j]);
        }
        dataset.addSeries(series);
    }
    out.close();

    //         Generate the graph
    JFreeChart chart = ChartFactory.createXYLineChart(title, // Title
            "threads", // x-axis Label
            "time (ns)", // y-axis Label
            dataset, // Dataset
            PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );

    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(renderer);
    renderer.setSeriesPaint(0, Color.BLUE);
    renderer.setSeriesPaint(1, Color.YELLOW);
    renderer.setSeriesPaint(2, Color.BLACK);
    renderer.setSeriesPaint(3, Color.DARK_GRAY);
    renderer.setSeriesPaint(4, Color.MAGENTA);
    renderer.setSeriesPaint(5, Color.RED);
    renderer.setSeriesPaint(6, Color.LIGHT_GRAY);
    //          renderer.setSeriesShapesVisible(1, true);   
    //          renderer.setSeriesShapesVisible(2, true);   

    try {
        ChartUtilities.saveChartAsPNG(new File(fname), chart, 1024, 768);
        System.out.println("******* Saved chart to: " + fname);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

}

From source file:com.jolbox.benchmark.BenchmarkMain.java

/**
 * @param results/*from w  ww . j  av  a 2 s. c  om*/
 * @param delay 
 * @param statementBenchmark 
 * @param noC3P0 
 */
private static void doPlotLineGraph(long[][] results, int delay, boolean statementBenchmark, boolean noC3P0) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    for (int i = 0; i < ConnectionPoolType.values().length; i++) { //
        if (!ConnectionPoolType.values()[i].isEnabled()
                || (noC3P0 && ConnectionPoolType.values()[i].equals(ConnectionPoolType.C3P0))) {
            continue;
        }
        XYSeries series = new XYSeries(ConnectionPoolType.values()[i].toString());

        for (int j = 1 + BenchmarkTests.stepping; j < results[i].length; j += BenchmarkTests.stepping) {
            series.add(j, results[i][j]);
        }
        dataset.addSeries(series);
    }

    //         Generate the graph
    String title = "Multi-Thread test (" + delay + "ms delay)";
    if (statementBenchmark) {
        title += "\n(with PreparedStatements tests)";
    }
    JFreeChart chart = ChartFactory.createXYLineChart(title, // Title
            "threads", // x-axis Label
            "time (ns)", // y-axis Label
            dataset, // Dataset
            PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );

    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(renderer);
    renderer.setSeriesPaint(0, Color.BLUE);
    renderer.setSeriesPaint(1, Color.YELLOW);
    renderer.setSeriesPaint(2, Color.BLACK);
    renderer.setSeriesPaint(3, Color.DARK_GRAY);
    renderer.setSeriesPaint(4, Color.MAGENTA);
    renderer.setSeriesPaint(5, Color.RED);
    renderer.setSeriesPaint(6, Color.LIGHT_GRAY);
    //          renderer.setSeriesShapesVisible(1, true);   
    //          renderer.setSeriesShapesVisible(2, true);   

    try {
        String fname = System.getProperty("java.io.tmpdir") + File.separator + "bonecp-multithread-" + delay
                + "ms-delay";
        if (statementBenchmark) {
            fname += "-with-preparedstatements";
        }
        fname += "-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads;
        if (noC3P0) {
            fname += "-noC3P0";
        }
        fname += ".png";
        ChartUtilities.saveChartAsPNG(new File(fname), chart, 1024, 768);
        System.out.println("******* Saved chart to: " + fname);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

}