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.jmxtrans.samples.graphite.GraphiteDataInjector.java

public void exportMetrics(TimeSeries timeSeries) throws IOException {
    System.out.println("Export " + timeSeries.getKey());
    Socket socket = new Socket(graphiteHost, graphitePort);
    OutputStream outputStream = socket.getOutputStream();

    if (generateDataPointsFile) {
        JFreeChart chart = ChartFactory.createXYLineChart("Purchase", "date", "Amount",
                new TimeSeriesCollection(timeSeries), PlotOrientation.VERTICAL, true, true, false);
        // chart.getXYPlot().setRenderer(new XYSplineRenderer(60));

        File file = new File("/tmp/" + timeSeries.getKey() + ".png");
        ChartUtilities.saveChartAsPNG(file, chart, 1200, 800);
        System.out.println("Exported " + file.getAbsolutePath());

        String pickleFileName = "/tmp/" + timeSeries.getKey().toString() + ".pickle";
        System.out.println("Generate " + pickleFileName);
        outputStream = new TeeOutputStream(outputStream, new FileOutputStream(pickleFileName));
    }//from w w w. j a  va  2  s  .  c om

    PyList list = new PyList();

    for (int i = 0; i < timeSeries.getItemCount(); i++) {
        if (debug)
            System.out.println(new DateTime(timeSeries.getDataItem(i).getPeriod().getStart()) + "\t"
                    + timeSeries.getDataItem(i).getValue().intValue());
        String metricName = graphiteMetricPrefix + timeSeries.getKey().toString();
        int time = (int) TimeUnit.SECONDS.convert(timeSeries.getDataItem(i).getPeriod().getStart().getTime(),
                TimeUnit.MILLISECONDS);
        int value = timeSeries.getDataItem(i).getValue().intValue();

        list.add(new PyTuple(new PyString(metricName), new PyTuple(new PyInteger(time), new PyInteger(value))));

        if (list.size() >= batchSize) {
            System.out.print("-");
            rateLimiter.acquire(list.size());
            sendDataPoints(outputStream, list);
        }
    }

    // send last data points
    if (!list.isEmpty()) {
        rateLimiter.acquire(list.size());
        sendDataPoints(outputStream, list);
    }

    Flushables.flushQuietly(outputStream);
    Closeables.close(outputStream, true);
    Closeables.close(socket, true);

    System.out.println();
    System.out.println("Exported " + timeSeries.getKey() + ": " + timeSeries.getItemCount() + " items");
}

From source file:com.deafgoat.ml.prognosticator.Charter.java

/**
 * Saves the given chart//  w ww  .  jav  a  2  s. c o  m
 * 
 * @param name
 *            The name to save the chart as
 * @param chart
 *            The chart to save
 * @throws IOException
 *             If the chart can not be saved
 */
private void saveChart(String name, JFreeChart chart) throws IOException {
    _logger.info("Saving chart for " + name);
    ChartUtilities.saveChartAsPNG(new File(name + ".png"), chart, 2000, 1500);
}

From source file:at.ac.tuwien.inso.subcat.ui.widgets.TimeChartControlPanel.java

public void saveChartAsPNG(File file, int width, int height) throws IOException {
    assert (chart != null);

    ChartUtilities.saveChartAsPNG(file, chart, width, height);
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByConsumerByServiceByMethod.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  ww.  j  a  va2  s. c o m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Consumer</th><th>Method</th><th>Invocations</th></tr>");
        Set<String> consumers2 = new HashSet<String>();
        List<String> actions = new ArrayList<String>();
        for (int k = 0; k < urls.size(); k++) {
            if (!isPolicyTypeOf(urls.get(k), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(k), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(k)));
            consumers2.clear();
            actions.clear();

            try {
                actions = getSoapActions(urls.get(k), con);

                rs = null;
                for (int k2 = 0; k2 < actions.size(); k2++) {
                    try {
                        consumers2.clear();

                        cmd = con.prepareStatement(
                                "select  consumeridentity from rawdata where uri=?  and (UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=? group by consumeridentity;");
                        cmd.setString(1, urls.get(k));
                        cmd.setLong(2, range.getStart().getTimeInMillis());
                        cmd.setLong(3, range.getEnd().getTimeInMillis());
                        cmd.setString(4, actions.get(k2));
                        rs = cmd.executeQuery();
                        while (rs.next()) {
                            String s = rs.getString(1);

                            //   log.log(Level.WARN, " debug INVOCATIONS_BY_CONSUMER_BY_SERVICE url:" + urls.get(k) + " user: " + s);
                            if (!Utility.stringIsNullOrEmpty(s)) {
                                String ids[] = s.split(";");
                                for (int i = 0; i < ids.length; i++) {
                                    if (!Utility.stringIsNullOrEmpty(ids[i])) {
                                        //  log.log(Level.WARN, " debug2 INVOCATIONS_BY_CONSUMER_BY_SERVICE url:" + urls.get(k) + " user: " + ids[i]);
                                        if (!consumers2.contains(ids[i])) {
                                            consumers2.add(ids[i]);
                                        }
                                    }
                                }
                            }

                        }

                    } catch (Exception ex) {
                        log.log(Level.WARN,
                                " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k),
                                ex);
                    } finally {
                        DBUtils.safeClose(rs);
                        DBUtils.safeClose(cmd);
                    }
                    consumers2.add("unspecified");

                    //ok for this service, count the times each consumer as hit it
                    Iterator<String> iterator = consumers2.iterator();
                    while (iterator.hasNext()) {

                        String u = iterator.next();

                        long count = 0;
                        try {
                            cmd = con.prepareStatement(
                                    "select count(*) from RawData where URI=? and soapaction=? and "
                                            + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity ~* ?;");
                            cmd.setString(1, urls.get(k));
                            cmd.setString(2, actions.get(k2));
                            cmd.setLong(3, range.getStart().getTimeInMillis());
                            cmd.setLong(4, range.getEnd().getTimeInMillis());
                            cmd.setString(5, u);

                            rs = cmd.executeQuery();
                            try {
                                if (rs.next()) {
                                    count = rs.getLong(1);
                                }
                            } catch (Exception ex) {
                                log.log(Level.WARN,
                                        " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE"
                                                + urls.get(k),
                                        ex);
                            }
                        } catch (Exception ex) {
                            log.log(Level.WARN, null, ex);
                        } finally {
                            DBUtils.safeClose(rs);
                            DBUtils.safeClose(cmd);
                        }

                        if (count > 0) { //cut down on the noise
                            data.append("<tr><td>").append(url).append("</td><td>")
                                    .append(Utility.encodeHTML(u)).append("</td><td>")
                                    .append(Utility.encodeHTML(actions.get(k2))).append("</td><td>");
                            data.append(count + "");
                            data.append("</td></tr>");

                            set.addValue(count, u, urls.get(k) + " " + actions.get(k2));
                        }
                    }

                    long count = 0;
                    try {
                        cmd = con.prepareStatement(
                                "select count(*) from RawData where URI=? and soapaction=? and "
                                        + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity is null;");
                        cmd.setString(1, urls.get(k));
                        cmd.setString(2, actions.get(k2));
                        cmd.setLong(3, range.getStart().getTimeInMillis());
                        cmd.setLong(4, range.getEnd().getTimeInMillis());

                        rs = cmd.executeQuery();

                        try {
                            if (rs.next()) {
                                count = rs.getLong(1);
                            }
                        } catch (Exception ex) {
                            log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE"
                                    + urls.get(k), ex);
                        }
                    } catch (Exception ex) {
                        log.log(Level.WARN, null, ex);
                    } finally {
                        DBUtils.safeClose(rs);
                        DBUtils.safeClose(cmd);
                    }

                    if (count > 0) { //cut down on the noise
                        data.append("<tr><td>").append(url).append("</td><td>unspecified</td><td>")
                                .append(Utility.encodeHTML(actions.get(k2))).append("</td><td>");
                        data.append(count + "");
                        data.append("</td></tr>");

                        set.addValue(count, "unspecified", url + " " + actions.get(k2));

                    }
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }
        }
        //  insert query for unspecified chart = org.jfree.chart.ChartFactory.createBarChart(toFriendlyName(get.getType()), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getColumnCount()));
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
        files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

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

public void save2File(File outputFile) throws IOException {
    ChartUtilities cu = new ChartUtilities() {
    };/* ww  w .  java 2 s  .c  om*/
    ChartUtilities.saveChartAsPNG(outputFile, this.chartPanel.getChart(), 800, 500);
    System.out.println("Saved at " + outputFile.toString() + " size = " + 800 + "x" + 500);
}

From source file:playground.anhorni.surprice.analysis.ModeSharesEventHandler.java

public void writeXYsGraphic(final String fileName, final int numberOfBins) {
    JFreeChart chart = this.getTraveledXYsHistogram(numberOfBins);
    try {/*from  ww w.jav  a2 s .c om*/
        ChartUtilities.saveChartAsPNG(new File(fileName), chart, 1024, 768);
    } catch (IOException e) {
        log.error("got an error while trying to write graphics to file."
                + " Error is not fatal, but output may be incomplete.");
        e.printStackTrace();
    }
}

From source file:com.joliciel.jochre.graphics.SourceImageImpl.java

private void drawChart(int[] pixelSpread, DescriptiveStatistics countStats,
        DescriptiveStatistics blackCountStats, DescriptiveStatistics blackSpread, int startWhite, int endWhite,
        int startBlack, int blackThresholdValue) {
    XYSeries xySeries = new XYSeries("Brightness data");
    double maxSpread = 0;
    for (int i = 0; i < 256; i++) {
        xySeries.add(i, pixelSpread[i]);
        if (pixelSpread[i] > maxSpread)
            maxSpread = pixelSpread[i];/*ww  w.j a v  a 2s  . co  m*/
    }

    XYSeries keyValues = new XYSeries("Key values");

    XYSeries counts = new XYSeries("Counts");

    counts.add(10.0, countStats.getMean());
    counts.add(100.0, blackCountStats.getMean());
    counts.add(125.0, blackCountStats.getMean() + (1.0 * blackCountStats.getStandardDeviation()));
    counts.add(150.0, blackCountStats.getMean() + (2.0 * blackCountStats.getStandardDeviation()));
    counts.add(175.0, blackCountStats.getMean() + (3.0 * blackCountStats.getStandardDeviation()));
    counts.add(75.0, blackCountStats.getMean() - (1.0 * blackCountStats.getStandardDeviation()));
    counts.add(50.0, blackCountStats.getMean() - (2.0 * blackCountStats.getStandardDeviation()));
    counts.add(25.0, blackCountStats.getMean() - (3.0 * blackCountStats.getStandardDeviation()));
    keyValues.add(startWhite, maxSpread / 4.0);
    keyValues.add(endWhite, maxSpread / 4.0);
    keyValues.add(startBlack, maxSpread / 4.0);
    keyValues.add(blackThresholdValue, maxSpread / 2.0);

    XYSeriesCollection dataset = new XYSeriesCollection(xySeries);
    dataset.addSeries(keyValues);
    dataset.addSeries(counts);
    final ValueAxis xAxis = new NumberAxis("Brightness");
    final ValueAxis yAxis = new NumberAxis("Count");
    yAxis.setUpperBound(maxSpread);
    xAxis.setUpperBound(255.0);

    //final XYItemRenderer  renderer = new XYBarRenderer();
    final XYBarRenderer renderer = new XYBarRenderer();
    renderer.setShadowVisible(false);
    final XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setOrientation(PlotOrientation.VERTICAL);
    String title = "BrightnessChart";
    final JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setBackgroundPaint(Color.white);
    File file = new File("data/" + title + ".png");
    try {
        ChartUtilities.saveChartAsPNG(file, chart, 600, 600);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:com.uttesh.pdfngreport.handler.PdfReportHandler.java

/**
 * Not Used for the current release//w ww  .j  a  v a2  s . c o  m
 *
 * @param dataSet
 */
public void pieExplodeChart(DefaultPieDataset dataSet, String os) {
    try {
        JFreeChart chart = ChartFactory.createPieChart("", dataSet, true, true, false);
        ChartStyle.theme(chart);
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setForegroundAlpha(0.6f);
        plot.setCircular(true);
        plot.setSectionPaint("Passed", Color.decode("#019244"));
        plot.setSectionPaint("Failed", Color.decode("#EE6044"));
        plot.setSectionPaint("Skipped", Color.decode("#F0AD4E"));
        Color transparent = new Color(0.0f, 0.0f, 0.0f, 0.0f);
        //plot.setLabelLinksVisible(Boolean.FALSE);
        plot.setLabelOutlinePaint(transparent);
        plot.setLabelBackgroundPaint(transparent);
        plot.setLabelShadowPaint(transparent);
        plot.setLabelLinkPaint(Color.GRAY);
        Font font = new Font("SansSerif", Font.PLAIN, 10);
        plot.setLabelFont(font);
        plot.setLabelPaint(Color.DARK_GRAY);
        plot.setExplodePercent("Passed", 0.10);
        //plot.setExplodePercent("Failed", 0.10);
        //plot.setExplodePercent("Skipped", 0.10);
        plot.setSimpleLabels(true);
        PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{1} ({2})", new DecimalFormat("0"),
                new DecimalFormat("0%"));
        plot.setLabelGenerator(gen);

        if (os != null && os.equalsIgnoreCase("w")) {
            ChartUtilities.saveChartAsPNG(
                    new File(reportLocation + Constants.BACKWARD_SLASH + Constants.REPORT_CHART_FILE), chart,
                    560, 200);
        } else {
            ChartUtilities.saveChartAsPNG(
                    new File(reportLocation + Constants.FORWARD_SLASH + Constants.REPORT_CHART_FILE), chart,
                    560, 200);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
        if (os != null && os.equalsIgnoreCase("w")) {
            new File(reportLocation + Constants.BACKWARD_SLASH + Constants.REPORT_CHART_FILE).delete();
        } else {
            new File(reportLocation + Constants.FORWARD_SLASH + Constants.REPORT_CHART_FILE).delete();
        }
        System.exit(-1);
    }
}

From source file:de.mpg.mpi_inf.bioinf.netanalyzer.ui.charts.JFreeChartConn.java

/**
 * Saves the given chart to a PNG image file.
 * //  ww  w  .j  a v a 2  s.co  m
 * @param aFile
 *            File to be saved to.
 * @param aChart
 *            Chart to be saved.
 * @param aWidth
 *            Desired width of the image.
 * @param aHeight
 *            Desired height of the image.
 * @throws IOException
 *             If I/O error occurs.
 */
public static void saveAsPng(File aFile, JFreeChart aChart, int aWidth, int aHeight) throws IOException {
    ChartUtilities.saveChartAsPNG(aFile, aChart, aWidth, aHeight);
}

From source file:analysis.postRun.PostRunWindow.java

/**
 * Method which creates and returns a graph in a chartpanel.
 * //from   w ww . jav a  2 s.  c  o  m
 * @param dset
 *             Which dataset to make a graph of.
 *       title
 *             Title for the graph.
 *      xTitle
 *             Title for the x axis.     
 *       yTitle
 *             Title for the y axis.
 *      legend
 *             Whether or not to include a legend - true if multiple series are to be shown.
 */
private ChartPanel getChart(DefaultXYDataset dset, String title, String xTitle, String yTitle, Boolean legend,
        Boolean percentage) {
    JFreeChart chart = ChartFactory.createXYLineChart(title, xTitle, yTitle, dset, PlotOrientation.VERTICAL,
            legend, true, false);
    if (percentage) {
        chart.getXYPlot().getRangeAxis().setRange(0.0, 100.0);
    }

    if (save) {
        try {
            //System.out.println("Saving charts.");
            ChartUtilities.saveChartAsPNG(
                    new File(currFile.substring(0, currFile.length() - 4) + title + "Chart"), chart, 1200, 800);
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
    return new ChartPanel(chart);
}