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.miloss.fgsms.services.rs.impl.reports.ws.MeanTimeBetweenFailureByService.java

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

    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>MTBF (ms)</th><th>Timespan</th><th>XML Duration Value</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 {
            long mtbf = meanTimeBetweenFailures(urls.get(i), range);
            Duration newDuration = df.newDuration(mtbf);
            data.append("<tr><td>").append(url).append("</td><td>");
            if (mtbf == -1 || mtbf == 0) {
                data.append("Never</td><td>0</td><td>0</d></tr>");
            } else {
                data.append(mtbf + "").append("ms</td><td>").append(Utility.durationToString(newDuration))
                        .append("</td><td>").append(newDuration.toString()).append("</td></tr>");
            }
            if (mtbf > 0) {
                set.addValue(mtbf, url, url);
            }

        } catch (Exception ex) {
            data.append("0 bytes</td></tr>");
            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 {
        if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
            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);
    }

}

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

public void writeGraphic(final String filename, int[] activities, int[] activitiesParticipatingAtHome,
        int[] activitiesParticipatingNotAtHome, int[] activitiesNotParticipatingAtHome,
        int[] activitiesNotParticipatingNotAtHome) {
    try {/*from w ww  . jav a  2s.  co  m*/
        ChartUtilities
                .saveChartAsPNG(new File(filename),
                        getGraphic(activities, activitiesParticipatingAtHome, activitiesParticipatingNotAtHome,
                                activitiesNotParticipatingAtHome, activitiesNotParticipatingNotAtHome),
                        1024, 768);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

/**
 * {@inheritDoc}/*from w  ww  . j a  v a2 s .com*/
 */
@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 average response time by service.<br />");
        //add description
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Average Response Time (ms)</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)));
            long count = 0;
            data.append("<tr><td>").append(url).append("</td><td>");
            try {
                cmd = con.prepareStatement(
                        "select AVG(responsetimems) 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();

                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);
                }

            } catch (Exception ex) {
                data.append("0 ms</td></tr>");
                log.log(Level.ERROR,
                        "Error opening or querying the database." + this.getClass().getSimpleName(), ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append(count + "").append(" ms</td></tr>");
            set.addValue(count, url, url);
        }
        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(urls.size()));
        } 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:info.mikaelsvensson.devtools.analysis.localaccesslog.LocalAccessLogReportGenerator.java

@Override
public void generateReport(File outputFile, ReportPrinter reportPrinter) throws FileNotFoundException {
    final PrintStream ps = new PrintStream(outputFile);
    final Collection<LocalAccessLogSample> allSamples = _log.getSamples();
    Map<String, Collection<LocalAccessLogSample>> samplesByTestSession = SampleCollector.COLLECTOR_BY_SESSION_DATE
            .getFilteredAndGrouped(allSamples);
    for (Map.Entry<String, Collection<LocalAccessLogSample>> sessionEntry : samplesByTestSession.entrySet()) {
        final Collection<LocalAccessLogSample> sessionSamples = sessionEntry.getValue();
        Map<String, Collection<LocalAccessLogSample>> samples = SAMPLE_COLLECTOR
                .getFilteredAndGrouped(sessionSamples);
        String[][] data = new String[samples.size() + 1][];
        int i = 0;
        int sumCount = 0;
        final DefaultPieDataset dataset = new DefaultPieDataset();
        final JFreeChart chart = ChartFactory.createPieChart(
                "Status Codes For Session " + sessionEntry.getKey(), dataset, true, false, Locale.ENGLISH);
        final File chartFile = new File(outputFile.getAbsolutePath() + "."
                + StringUtils.remove(sessionEntry.getKey(), ':').replace(' ', '-') + ".png");
        final PiePlot plot = (PiePlot) chart.getPlot();
        for (Map.Entry<String, Collection<LocalAccessLogSample>> entry : samples.entrySet()) {
            final Collection<LocalAccessLogSample> responseCodeSamples = entry.getValue();
            final int count = responseCodeSamples.size();
            data[i++] = new String[] { entry.getKey(), ToStringUtil.toString(count),
                    ToStringUtil.toString(_log.calculateAverage(responseCodeSamples)),
                    ToStringUtil.toString(_log.calculateMin(responseCodeSamples)),
                    ToStringUtil.toString(_log.calculateMax(responseCodeSamples)) };
            sumCount += count;/*from w  ww.j ava  2s  . c o m*/

            final String label = entry.getKey() + " (" + count + " reqs)";
            dataset.setValue(label, count);
            plot.setSectionPaint(label, entry.getKey().equals("200") ? Color.GREEN : Color.RED);
        }
        data[i] = new String[] { "All", ToStringUtil.toString(sumCount),
                ToStringUtil.toString(_log.calculateAverage(sessionSamples)),
                ToStringUtil.toString(_log.calculateMin(sessionSamples)),
                ToStringUtil.toString(_log.calculateMax(sessionSamples)) };

        reportPrinter.printTable(ps, sessionEntry.getKey(), 10,
                new String[] { "Status Code", "# Requests", "Avg [ms]", "Min [ms]", "Max [ms]" }, data, null);

        if (sumCount > NUMBER_OF_REQUESTS_IN_SHORT_TEST) {
            try {
                ChartUtilities.saveChartAsPNG(chartFile, chart, 500, 500);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
    ps.close();
}

From source file:de.berlios.statcvs.xml.chart.AbstractChart.java

public void save(File file, int width, int height) throws IOException {
    ChartUtilities.saveChartAsPNG(file, chart, width, height);
    logger.fine("saved chart as '" + filename + "'");
}

From source file:entropy.plan.visualization.GanttVisualizer.java

/**
 * Build the plan agenda//from   www . j a  v a  2  s  . c  o  m
 *
 * @param plan the plan to visualize
 * @return {@code true} if the generation succeeds
 */
@Override
public boolean buildVisualization(TimedReconfigurationPlan plan) {
    File parent = new File(out).getParentFile();
    if (parent != null && !parent.exists() && !parent.mkdirs()) {
        Plan.logger.error("Unable to create '" + out + "'");
        return false;
    }
    final TaskSeriesCollection collection = new TaskSeriesCollection();
    TaskSeries ts = new TaskSeries("actions");
    for (Action action : plan) {
        Task t = new Task(action.toString(),
                new SimpleTimePeriod(action.getStartMoment(), action.getFinishMoment()));
        ts.add(t);
    }
    collection.add(ts);
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());

    final JFreeChart chart = ChartFactory.createGanttChart(null, // chart title
            "Actions", // domain axis label
            "Time", // range axis label
            collection, // data
            false, // include legend
            true, // tooltips
            false // urls
    );
    CategoryPlot plot = chart.getCategoryPlot();
    DateAxis da = (DateAxis) plot.getRangeAxis();
    SimpleDateFormat sdfmt = new SimpleDateFormat();
    sdfmt.applyPattern("S");
    da.setDateFormatOverride(sdfmt);
    ((GanttRenderer) plot.getRenderer()).setShadowVisible(false);
    int width = 500 + 10 * plan.getDuration();
    int height = 50 + 20 * plan.size();
    try {
        switch (fmt) {
        case png:
            ChartUtilities.saveChartAsPNG(new File(out), chart, width, height);
            break;
        case jpg:
            ChartUtilities.saveChartAsJPEG(new File(out), chart, width, height);
            break;
        }
    } catch (IOException e) {
        Plan.logger.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:org.jmxtrans.embedded.samples.graphite.GraphiteDataInjector.java

public void exportMetrics(TimeSeries timeSeries) throws IOException {
    System.out.println("Export '" + timeSeries.getKey() + "' to " + graphiteHost + " with prefix '"
            + graphiteMetricPrefix + "'");
    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.  ja  va2 s  .c o m*/

    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);
    try {
        socket.close();
    } catch (Exception e) {
        // swallow exception
        e.printStackTrace();
    }

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

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

/**
 * {@inheritDoc}/*from   w w w.  j ava2s .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 average response time by Service by Method<br />");
        //add description
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Action</th><th>Average Response Time (ms)</th></tr>");
        int actioncount = 0;
        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)));
            List<String> actions = getSoapActions(urls.get(i), con);

            actioncount += actions.size();
            for (int k = 0; k < actions.size(); k++) {
                long count = 0;
                try {
                    cmd = con.prepareStatement("select AVG(responsetimems)  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();

                    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);
                } 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(" ms</td></tr>");
                set.addValue(count, actions.get(k), url);
            }

        }
        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(actioncount));
        } 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:sim.MarkersChart.java

/**
 * Save chart to disk as a PNG/*from ww w  .  ja v  a  2s  .c o  m*/
 */
public void save() {
    try {
        ChartUtilities.saveChartAsPNG(new File(params.path), chart, params.width, params.height);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

/**
 * {@inheritDoc}//from w ww . j  av  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 {
    int itemcount = 0;
    Connection con = Utility.getPerformanceDBConnection();
    try {
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        if (!UserIdentityUtil.hasGlobalAdministratorRole(currentuser, "THROUGHPUT_BY_HOSTING_SERVER",
                classification, ctx)) {
            data.append("<h2>Access for " + GetDisplayName() + " was denied for non-global admin users</h2>");
            return;
        }
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents Data Collector Service utilization.<br />");
        data.append("<table class=\"table table-hover\"><tr><th>Host</th><th>Invocations</th></tr>");
        List<String> dcs = new ArrayList<String>();
        try {

            //was select distinct monitorsource from RawData;
            cmd = con.prepareStatement("select monitorsource from rawdata group by monitorsource;");
            rs = cmd.executeQuery();
            while (rs.next()) {
                dcs.add(rs.getString(1));
            }
        } catch (Exception ex) {
            log.log(Level.WARN, null, 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 monitorsource=? 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();
                    if (rs.next()) {
                        success = rs.getInt(1);
                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }
                data.append("<td>").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(), "Monitoring 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);
    }
}