Example usage for org.jfree.chart ChartUtilities writeChartAsPNG

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

Introduction

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

Prototype

public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height)
        throws IOException 

Source Link

Document

Writes a chart to an output stream in PNG format.

Usage

From source file:org.korosoft.hudson.plugin.dynamic.CukeTestResultChartAction.java

public void doDynamic(RuSaladDynamicActionContext context, StaplerRequest req, StaplerResponse rsp)
        throws IOException, ServletException {
    rsp.setContentType("image/png");
    rsp.setHeader("Cache-Control", "no-cache");
    final OutputStream stream = rsp.getOutputStream();
    final JFreeChart chart = createChart(retrieveHistory(context.getProject()));
    ChartUtilities.writeChartAsPNG(stream, chart, 800, 450);
    stream.close();/*from w ww  .j  a va 2  s.co m*/
}

From source file:cherry.chart.app.LineChartBatch.java

@Override
public ExitStatus execute(String... args) {

    int nThread = (args.length < 1 ? defaultNumThread : parseInt(args[0]));
    int count = (args.length < 2 ? defaultCount : parseInt(args[1]));

    ExecutorService executorService = Executors.newFixedThreadPool(nThread);
    List<Future<Boolean>> tasks = new LinkedList<>();

    for (int i = 0; i < count; i++) {

        final String numStr = String.valueOf(i);
        tasks.add(executorService.submit(new Callable<Boolean>() {
            @Override//from www. j  av a2  s.c  om
            public Boolean call() {

                File f = new File(toDir, format(file, numStr));
                String t = format(title, numStr);

                CategoryDataset dataset = createDataset();
                JFreeChart chart = ChartFactory.createLineChart(t, xLabel, yLabel, dataset);

                try (OutputStream out = new FileOutputStream(f)) {
                    ChartUtilities.writeChartAsPNG(out, chart, width, height);
                    return true;
                } catch (IOException ex) {
                    log.error("failed to create file", ex);
                    return false;
                }
            }
        }));
    }

    boolean success = true;
    for (Future<Boolean> future : tasks) {
        try {
            success &= future.get();
        } catch (ExecutionException | InterruptedException ex) {
            log.error("failed to get result", ex);
            success = false;
        }
    }
    return (success ? ExitStatus.NORMAL : ExitStatus.ERROR);
}

From source file:org.lsug.quota.portlet.UserQuotaPortlet.java

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws IOException, PortletException {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    StringBundler sb = new StringBundler(5);

    JFreeChart jFreeChart = null;//  ww  w. ja v  a 2  s .  c  om

    DefaultPieDataset pieDataset = new DefaultPieDataset();

    try {
        long groupId = themeDisplay.getUser().getGroupId();

        long classNameId = PortalUtil.getClassNameId(User.class);

        Quota siteQuota = QuotaLocalServiceUtil.fetchQuotaByClassNameIdClassPK(classNameId, groupId);

        if (siteQuota != null && siteQuota.isEnabled()) {
            pieDataset.setValue(QuotaUtil.getResource(resourceRequest, "used-space"),
                    siteQuota.getQuotaUsedPercentage());
            pieDataset.setValue(QuotaUtil.getResource(resourceRequest, "unused-space"),
                    100 - siteQuota.getQuotaUsedPercentage());

            sb.append(QuotaUtil.getResource(resourceRequest, "user-site-current-used-size-diagram-title"));

            jFreeChart = getCurrentSizeJFreeChart(sb.toString(), pieDataset);

            resourceResponse.setContentType(ContentTypes.IMAGE_PNG);

            OutputStream outputStream = null;

            try {
                outputStream = resourceResponse.getPortletOutputStream();
                ChartUtilities.writeChartAsPNG(outputStream, jFreeChart, 400, 200);
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error(e);
        throw new PortletException(e);
    }
}

From source file:net.commerce.zocalo.freechart.ChartTest.java

public void testOHLCChart() throws IOException {
    File jpgFile = newEmptyFile(".", "testChart.jpg");
    File pngFile = newEmptyFile(".", "testChart.png");
    assertFalse(jpgFile.exists());/*  w w w .  j ava2 s . c o m*/
    assertFalse(pngFile.exists());

    OutputStream jpgStream = new FileOutputStream(jpgFile);
    OutputStream pngStream = new FileOutputStream(pngFile);

    OHLCDataset data2 = createOHLCDataSet(new Minute());
    JFreeChart chart = ChartFactory.createHighLowChart("testChart", "date", "values", data2, false);

    ChartUtilities.writeChartAsJPEG(jpgStream, chart, 200, 500);
    ChartUtilities.writeChartAsPNG(pngStream, chart, 200, 500);

    assertTrue(jpgFile.exists());
    assertTrue(pngFile.exists());
    jpgFile.delete();
    pngFile.delete();
}

From source file:BubbleChartDemo.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Connection conn = null;/*from w w  w. j  a va  2  s .  c  om*/
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsm = null;

    OutputStream out = response.getOutputStream();
    try {

        DefaultXYZDataset dataset = new DefaultXYZDataset();
        double[] x = { 2.1, 2.3, 2.3, 2.2, 2.2, 1.8, 1.8, 1.9, 2.3, 3.8 };
        double[] y = { 14.1, 11.1, 10.0, 8.8, 8.7, 8.4, 5.4, 4.1, 4.1, 25 };
        double[] z = { 2.4, 2.7, 2.7, 2.2, 2.2, 2.2, 2.1, 2.2, 1.6, 4 };
        double[][] series = new double[][] { x, y, z };
        dataset.addSeries("Series 1", series);

        JFreeChart chart = ChartFactory.createBubbleChart("Bubble Chart Demo 1", "X", "Y", dataset,
                PlotOrientation.HORIZONTAL, true, true, true);
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setForegroundAlpha(0.65f);

        XYItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(0, Color.blue);

        // increase the margins to account for the fact that the auto-range
        // doesn't take into account the bubble size...
        NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
        domainAxis.setLowerMargin(0.15);
        domainAxis.setUpperMargin(0.15);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setLowerMargin(0.15);
        rangeAxis.setUpperMargin(0.15);

        response.setContentType("image/png");
        int width = 800;
        int height = 600;
        ChartUtilities.writeChartAsPNG(out, chart, width, height);

    } catch (Exception e) {
        throw new ServletException(e);
    }

}

From source file:com.liferay.server.admin.web.internal.portlet.action.ViewChartMVCResourceCommand.java

@Override
protected void doServeResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String type = ParamUtil.getString(resourceRequest, "type", "max");
    long maxMemory = ParamUtil.getLong(resourceRequest, "maxMemory");
    long totalMemory = ParamUtil.getLong(resourceRequest, "totalMemory");
    long usedMemory = ParamUtil.getLong(resourceRequest, "usedMemory");

    ValueDataset valueDataset = null;//from ww w.  j a  va2  s  .c o m

    StringBundler sb = new StringBundler(5);

    ResourceBundle resourceBundle = ResourceBundleUtil.getBundle("content.Language", themeDisplay.getLocale(),
            getClass());

    sb.append(ResourceBundleUtil.getString(resourceBundle, "used-memory"));

    sb.append(StringPool.SPACE);
    sb.append(StringPool.FORWARD_SLASH);
    sb.append(StringPool.SPACE);

    if (type.equals("total")) {
        valueDataset = new DefaultValueDataset((usedMemory * 100) / totalMemory);

        sb.append(ResourceBundleUtil.getString(resourceBundle, "total-memory"));
    } else {
        valueDataset = new DefaultValueDataset((usedMemory * 100) / maxMemory);

        sb.append(ResourceBundleUtil.getString(resourceBundle, "maximum-memory"));
    }

    MeterPlot meterPlot = getMeterPlot(themeDisplay, valueDataset);

    JFreeChart jFreeChart = getJFreeChart(sb.toString(), meterPlot);

    resourceResponse.setContentType(ContentTypes.IMAGE_PNG);

    ChartUtilities.writeChartAsPNG(resourceResponse.getPortletOutputStream(), jFreeChart, 280, 180);
}

From source file:edu.jhuapl.graphs.controller.GraphObject.java

public void writeChartAsPNG(OutputStream out, int graphWidth, int graphHeight) throws IOException {
    ChartUtilities.writeChartAsPNG(out, graphSource.getChart(), graphWidth, graphHeight);
}

From source file:ai.susi.server.api.vis.PieChartServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Query post = RemoteAccess.evaluate(request);

    // Get the json data to visualize as a key value pair of data=

    if (post.isDoS_blackout()) {
        response.sendError(503, "Your request frequency is too high");
        return;//from w w w.  jav a2  s. c  o m
    }

    // Get the data json string passed as stream parameter
    String data = post.get("data", "");
    String legendBitString = post.get("legend", "");
    String tooltipBitString = post.get("tooltip", "");
    String widthString = post.get("width", "");
    String heightString = post.get("height", "");
    boolean legendBit = true;
    boolean tooltipBit = false;

    int width = 500;
    int height = 500;

    if ("".equals(legendBitString) || "false".equals(legendBitString)) {
        legendBit = true;
    } else {
        legendBit = false;
    }

    if ("".equals(tooltipBitString) || !"true".equals(tooltipBitString)) {
        tooltipBit = false;
    } else {
        tooltipBit = true;
    }

    if (!"".equals(widthString)) {
        width = Integer.parseInt(widthString);
    }

    if (!"".equals(heightString)) {
        height = Integer.parseInt(heightString);
    }

    JSONObject json = new JSONObject(data);

    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    JFreeChart chart = getChart(json, legendBit, tooltipBit);
    ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
}

From source file:com.controlj.addon.gwttree.server.GraphServlet.java

/**<!====== doPost ========================================================>
   Generates a graph from the specified parameters in the request.  The request
   will contain a date parameter with the date to graph.  The list of
   trend sources is obtained from the TreeService (synchronized via GWT RPC
   mechanism and not passed on every request).
<!=======================================================================>*/
@Override/*from   ww  w  .  ja va 2 s . c o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SystemConnection connection = createConnection(request);
    GraphParameters params = extractParameters(request);
    JFreeChart chart = createChart(connection, params);

    // generate response
    response.setHeader("Cache-Control", "no-cache");
    response.setContentType("image/png");
    try {
        // Generate the graph from the dataset and write out as a PNG
        ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 600, 400);
    } catch (IOException e) {
        //ignore errors writing out image
    }
}

From source file:net.sf.jsfcomp.chartcreator.ChartListener.java

private void writeChart(OutputStream stream, JFreeChart chart, ChartData chartData) throws IOException {
    if (chartData.getOutput().equalsIgnoreCase("png"))
        ChartUtilities.writeChartAsPNG(stream, chart, chartData.getWidth(), chartData.getHeight());
    else if (chartData.getOutput().equalsIgnoreCase("jpeg"))
        ChartUtilities.writeChartAsJPEG(stream, chart, chartData.getWidth(), chartData.getHeight());

    stream.flush();//from w  w  w . j  a  va2  s.c  o  m
    stream.close();
}