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:ws.moor.bt.grapher.ReportBitThief.java

public void create(OutputStream os, File directory) throws IOException {
    buildCharts();//  w w  w .  j  a v  a 2s.  c  o  m
    directory.mkdirs();
    StringBuilder htmlFile = new StringBuilder();
    htmlFile.append("<html>\n");
    htmlFile.append("<h1 style=\"page-break-before: always;\">").append(getName()).append("</h1>\n");
    htmlFile.append("Running Time: ").append(getRunningTime() / 1000 / 60).append("min").append("<br/>\n");
    htmlFile.append("Total Down: ").append(getLastValue("network.rawbytes.in") / 1024 / 1024).append("MB")
            .append("<br/>\n");
    htmlFile.append("Total Up: ").append(getLastValue("network.rawbytes.out") / 1024 / 1024).append("MB")
            .append("<br/>\n");
    File piecesFile = new File(directory, "pieces.png");
    ChartUtilities.saveChartAsPNG(piecesFile, piecesChart, ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    appendHTMLForGraph(htmlFile, piecesFile, "Pieces", ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    File rawBytesFile = new File(directory, "rawbytes.png");
    ChartUtilities.saveChartAsPNG(rawBytesFile, rawBytesChart, ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    appendHTMLForGraph(htmlFile, rawBytesFile, "Raw Bytes", ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    File trackerFile = new File(directory, "tracker.png");
    ChartUtilities.saveChartAsPNG(trackerFile, trackerChart, ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    appendHTMLForGraph(htmlFile, trackerFile, "Tracker", ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    File connectionFile = new File(directory, "connections.png");
    ChartUtilities.saveChartAsPNG(connectionFile, connectionChart, ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    appendHTMLForGraph(htmlFile, connectionFile, "Connections", ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    File blockFile = new File(directory, "blocks.png");
    ChartUtilities.saveChartAsPNG(blockFile, blockChart, ReportBitThief.WIDTH, ReportBitThief.HEIGHT);
    appendHTMLForGraph(htmlFile, blockFile, "Blocks", ReportBitThief.WIDTH, ReportBitThief.HEIGHT);

    os.write(htmlFile.toString().getBytes());
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByService.java

/**
 * {@inheritDoc}//from   www  .ja v a 2  s. c  o m
 */
@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 {
        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 invocations for each service by method (action).<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Action</th><th>Invocations</th></tr>");
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                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)));
            try {
                List<String> actions = getSoapActions(urls.get(i), con);

                for (int k = 0; k < actions.size(); k++) {
                    long count = 0;

                    try {
                        cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                                + "(UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=?;");
                        cmd.setString(1, urls.get(i));
                        cmd.setLong(2, range.getStart().getTimeInMillis());
                        cmd.setLong(3, range.getEnd().getTimeInMillis());
                        cmd.setString(4, actions.get(k));
                        rs = cmd.executeQuery();
                        try {
                            if (rs.next()) {
                                count = rs.getLong(1);
                            }
                        } catch (Exception ex) {
                            log.log(Level.DEBUG, null, ex);
                        }
                    } catch (Exception ex) {
                        log.log(Level.WARN, null, ex);

                    } finally {
                        DBUtils.safeClose(rs);
                        DBUtils.safeClose(cmd);
                    }
                    data.append("<tr><td>").append(url).append("</td><td>");
                    data.append(Utility.encodeHTML(actions.get(k))).append("</td><td>").append(count + "")
                            .append("</td></tr>");
                    if (count > 0) {
                        set.addValue(count, actions.get(k), url);
                    }
                }
            } catch (Exception ex) {

                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }
        }
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
        } 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:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByHostingServer.java

/**
 * {@inheritDoc}/*from   w ww.  j  a v  a 2s  .  c o  m*/
 */
@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    if (!UserIdentityUtil.hasGlobalAdministratorRole(currentuser, "INVOCATIONS_BY_HOSTING_SERVER",
            classification, ctx)) {
        data.append("<h2>Access for " + GetDisplayName() + " was denied for non-global admin users</h2>");
        return;
    }
    int itemcount = 0;
    Connection con = Utility.getPerformanceDBConnection();
    try {
        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 Web Application Server utilization (host) by invocations.<br />");
        data.append("<table class=\"table table-hover\"><tr><th>Host</th><th>Invocations</th></tr>");
        List<String> dcs = new ArrayList<String>();
        try {
            cmd = con.prepareStatement("select hostingsource from RawData group by hostingsource;");
            rs = cmd.executeQuery();
            while (rs.next()) {
                dcs.add(rs.getString(1));
            }
        } catch (Exception ex) {
        } finally {
            DBUtils.safeClose(rs);
            DBUtils.safeClose(cmd);
        }
        try {

            itemcount = dcs.size();
            for (int i = 0; i < dcs.size(); i++) {
                data.append("<tr><td>").append(Utility.encodeHTML(dcs.get(i))).append("</td><td>");
                int success = 0;
                try {
                    cmd = con.prepareStatement(
                            "select count(*) from RawData where hostingsource=? and UTCdatetime > ? and UTCdatetime < ?;");
                    cmd.setString(1, dcs.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();
                    try {
                        if (rs.next()) {
                            success = rs.getInt(1);
                        }
                    } catch (Exception ex) {
                        log.log(Level.DEBUG, null, ex);
                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                data.append(success + "").append("</td></tr>");

                set.addValue(success, dcs.get(i), dcs.get(i));
            }

        } catch (Exception ex) {
            log.log(Level.ERROR, "Error generating chart information.", ex);
        }
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Hosting Servers", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(itemcount));
        } 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:guineu.modules.filter.report.areaVSheight.ReportTask.java

/**
 * Create the chart and save it into a png file.
 * @param dataset//from ww  w .j  av  a 2s.c o  m
 * @param lipidName
 */
private void createChart(CategoryDataset dataset, String lipidName) {
    try {

        JFreeChart chart = ChartFactory.createLineChart("Height/Area", "Samples", "Height/Area", dataset,
                PlotOrientation.VERTICAL, false, false, false);

        // Chart characteristics
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        final NumberAxis axis = (NumberAxis) plot.getRangeAxis();
        axis.setAutoRangeIncludesZero(false);
        LineAndShapeRenderer categoryRenderer = new LineAndShapeRenderer();
        categoryRenderer.setSeriesLinesVisible(0, false);
        categoryRenderer.setSeriesShapesVisible(0, true);
        plot.setRenderer(categoryRenderer);

        // Save all the charts in the folder choosen by the user
        ChartUtilities.saveChartAsPNG(new File(this.reportFileName + "/HeightvsArea:" + lipidName + ".png"),
                chart, 1000, 500);
    } catch (IOException ex) {
        Logger.getLogger(ReportTask.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:guineu.modules.filter.report.RTShift.ReportTask.java

/**
 * Create the chart and save it into a png file.
 * @param dataset/*  ww w  .ja v a 2s  .co m*/
 * @param lipidName
 */
private void createChart(CategoryDataset dataset, String lipidName) {
    try {

        JFreeChart chart = ChartFactory.createLineChart("RT shift", "Samples", "RT", dataset,
                PlotOrientation.VERTICAL, false, false, false);

        // Chart characteristics
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        final NumberAxis axis = (NumberAxis) plot.getRangeAxis();
        axis.setAutoRangeIncludesZero(false);
        axis.setAutoRangeMinimumSize(1.0);
        LineAndShapeRenderer categoryRenderer = new LineAndShapeRenderer();
        categoryRenderer.setSeriesLinesVisible(0, false);
        categoryRenderer.setSeriesShapesVisible(0, true);
        plot.setRenderer(categoryRenderer);

        // Save all the charts in the folder choosen by the user
        ChartUtilities.saveChartAsPNG(new File(this.reportFileName + "/RT Shift:" + lipidName + ".png"), chart,
                1000, (500));
    } catch (IOException ex) {
        Logger.getLogger(ReportTask.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:se.lnu.cs.doris.metrics.SLOC.java

private void generateImage(ImageType type) throws Exception {
    if (this.m_mainDir == null) {
        throw new Exception("Base directory not set.");
    }/*from   ww w. j a va 2s.c  o  m*/

    XYSeries linesOfCodeTotal = new XYSeries("Total lines");
    XYSeries linesOfCode = new XYSeries("Lines of code");
    XYSeries linesOfComments = new XYSeries("Lines of comments");
    XYSeries baseLine = new XYSeries("index 100");

    for (File f : this.m_mainDir.listFiles()) {
        if (f.isDirectory() && !f.getName().contains(this.m_avoid)) {

            int commitNumber = Utilities.parseInt(f.getName());
            int slocd = 0;
            int slocmt = 0;
            int sloct = 0;

            for (File sd : f.listFiles()) {
                if (!sd.getName().toLowerCase().contains(this.m_avoid)) {
                    slocd += this.countLines(sd, false);
                    slocmt += this.countLines(sd, true);
                    sloct += slocd + slocmt;
                }
            }

            if (this.m_baseValueTotal < 0) {
                this.m_baseValueTotal = sloct;
                this.m_baseValueComments = slocmt;
                this.m_baseValueCode = slocd;

                sloct = 100;
                slocmt = 100;
                slocd = 100;
            } else {
                sloct = (int) ((double) sloct / (double) this.m_baseValueTotal * 100);
                slocmt = (int) ((double) slocmt / (double) this.m_baseValueComments * 100);
                slocd = (int) ((double) slocd / (double) this.m_baseValueCode * 100);
            }

            linesOfCodeTotal.add(commitNumber, sloct);
            linesOfCode.add(commitNumber, slocd);
            linesOfComments.add(commitNumber, slocmt);
            baseLine.add(commitNumber, 100);

        }
    }

    XYSeriesCollection collection = new XYSeriesCollection();

    collection.addSeries(linesOfCodeTotal);
    collection.addSeries(linesOfCode);
    collection.addSeries(linesOfComments);
    collection.addSeries(baseLine);

    JFreeChart chart = ChartFactory.createXYLineChart(
            "Source lines of code change for " + this.m_projectName + " \nBase value code: "
                    + this.m_baseValueCode + "\nBase value comments: " + this.m_baseValueComments,
            "Commit", "SLOC change %", collection, PlotOrientation.VERTICAL, true, true, false);

    XYPlot plot = chart.getXYPlot();

    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setTickUnit(new NumberTickUnit(2));

    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setTickUnit(new NumberTickUnit(10));

    switch (type) {
    case JPEG:
        ChartUtilities.saveChartAsJPEG(new File(this.m_mainDir.getAbsolutePath(), "sloc_chart.jpg"), chart,
                1000, 720);
        break;
    case PNG:
        ChartUtilities.saveChartAsPNG(new File(this.m_mainDir.getAbsolutePath(), "sloc_chart.png"), chart, 1000,
                720);
        break;
    default:
        break;
    }
}

From source file:org.keycloak.testsuite.util.Timer.java

private void saveChart(String op) {
    XYSeries series = new XYSeries(op);
    int i = 0;/*from   ww w. ja v  a 2  s. com*/
    for (Long duration : stats.get(op)) {
        series.add(++i, duration);
    }
    final XYSeriesCollection data = new XYSeriesCollection(series);
    final JFreeChart chart = ChartFactory.createXYLineChart(op, "Operations", "Duration (ms)", data,
            PlotOrientation.VERTICAL, true, true, false);
    try {
        ChartUtilities.saveChartAsPNG(new File(CHARTS_DIR, op.replace(" ", "_") + ".png"), chart, 640, 480);
    } catch (IOException ex) {
        log.warn("Unable to save chart for operation '" + op + "'.");
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.AverageMessageSizeByService.java

/**
 * {@inheritDoc}//from w  w w. j  a  v a2 s  . co m
 */
@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 {
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>");
        data.append(GetDisplayName());
        data.append("</h2>");

        data.append(GetHtmlFormattedHelp() + "<br />");
        //add description
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Average Message Size (bytes)</th></tr>");
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                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><td>");
            try {
                cmd = con.prepareStatement(
                        "select AVG(responseSize + requestSize) as messagesSize from RawData 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();
                long count = -1;
                try {
                    if (rs.next()) {
                        count = rs.getLong(1);
                    }
                } catch (Exception ex) {
                    log.log(Level.DEBUG, " error querying database for average message size url:" + urls.get(i),
                            ex);
                }

                if (count >= 0) {
                    data.append(count + " bytes");
                } else {
                    data.append("N/A");
                }
                data.append("</td></tr>");
                if (count > 0) {
                    set.addValue(count, url, url);
                }
            } catch (Exception ex) {
                data.append("0 bytes</td></tr>");
                log.log(Level.ERROR, "Error opening or querying the database." + GetDisplayName(), ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
        }

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(
                    new File(path + getFilePathDelimitor() + "image_" + this.getClass().getName() + ".png"),
                    chart, 1500, Reporting.pixelHeightCalc(urls.size()));
        } catch (Exception ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getName()).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:org.miloss.fgsms.services.rs.impl.reports.ServiceLevelAgreementReport.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 {/*from ww w  .java2 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>URI</th><th>SLA Violations</th></tr>");

        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                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><td>");
            try {
                cmd = con.prepareStatement("select count(*) from slaviolations 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();
                long count = -1;
                try {
                    if (rs.next()) {
                        count = rs.getLong(1);
                    }
                } catch (Exception ex) {
                    log.log(Level.DEBUG, " error querying database url:" + urls.get(i), ex);
                }

                if (count >= 0) {
                    data.append(count + "");
                } else {
                    data.append("N/A");
                }

                if (count > 0) {
                    set.addValue(count, url, url);
                }
            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database." + GetDisplayName(), ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("</td></tr>");
        }

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, Reporting.pixelHeightCalc(urls.size()));
        } catch (Exception 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:org.esa.snap.pixex.output.ScatterPlotDecoratingStrategy.java

@Override
public void finish() {
    for (Map.Entry<Long, Map<PixExOp.VariableCombination, JFreeChart>> mapEntry : plotMaps.entrySet()) {
        final Map<PixExOp.VariableCombination, JFreeChart> plots = mapEntry.getValue();
        final Long productId = mapEntry.getKey();
        for (Map.Entry<PixExOp.VariableCombination, JFreeChart> entry : plots.entrySet()) {
            final PixExOp.VariableCombination variableCombination = entry.getKey();
            try {
                File targetFile = new File(parent,
                        String.format("%s_scatter_plot_%s_%s_%s.png", filePrefix,
                                variableCombination.originalVariableName,
                                variableCombination.productVariableName, productNames.get(productId)));
                ChartUtilities.saveChartAsPNG(targetFile, entry.getValue(), 600, 400);
            } catch (IOException e) {
                SystemUtils.LOG.warning(e.getMessage());
            }//from   w  w w. ja v a2  s.  com
        }
    }
}