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:Visao.grafico.Grafico.java

private void GerarPDF() throws DocumentException, FileNotFoundException {
    OutputStream arquivo;/* w ww . j a  v a 2  s .c o m*/
    try {
        arquivo = new FileOutputStream(titulo + ".png");
        ChartUtilities.writeChartAsPNG(arquivo, graf, 1204, 768);
        arquivo.close();
        this.dispose();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Grafico.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Grafico.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.kodemore.freechart.KmAbstractChart.java

protected byte[] toPngBytes(JFreeChart chart) {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        ChartUtilities.writeChartAsPNG(out, chart, getWidth(), getHeight());
        return out.toByteArray();
    } catch (IOException ex) {
        throw Kmu.toRuntime(ex);
    }/*from w  w w .j av  a 2 s . c o m*/
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.history.GraphController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.debug("Processing creating pie graph");
    String graphType = "";

    List<DownloadStatistic> topDownloadedFilesList = null;
    boolean isGroupAdmin;
    long countFile = 0;

    graphType = request.getParameter("graphType");
    int groupId = Integer.parseInt(request.getParameter("groupId"));
    isGroupAdmin = auth.userIsGroupAdmin();
    response.setContentType("image/png");

    topDownloadedFilesList = historyDao.getTopDownloadHistory(ChoiceHistory.valueOf(graphType), isGroupAdmin,
            groupId);//from w ww  .  ja  va 2s  .c  om

    DefaultPieDataset dataset = new DefaultPieDataset();
    if (groupId != -1) {
        for (int i = 0; i < topDownloadedFilesList.size(); i++) {
            dataset.setValue(topDownloadedFilesList.get(i).getFileName(),
                    new Long(topDownloadedFilesList.get(i).getCount()));
            countFile = countFile + topDownloadedFilesList.get(i).getCount();
        }

        if (historyDao.getCountOfFilesHistory(ChoiceHistory.valueOf(graphType), isGroupAdmin,
                groupId) > countFile) {
            dataset.setValue("Other",
                    historyDao.getCountOfFilesHistory(ChoiceHistory.valueOf(graphType), isGroupAdmin, groupId)
                            - countFile);
        }
    }
    JFreeChart chart = ChartFactory.createPieChart3D("Daily downloads", // chart title
            dataset, // data
            true, // include legend
            true, false);

    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    plot.setNoDataMessage("No data to display");

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 600, 400);
    response.getOutputStream().close();
    return null;
}

From source file:org.psystems.dicom.browser.server.stat.UseagStoreChartServlet.java

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

    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    JFreeChart chart = getChart();//from  w w w . j a va 2  s. c  om
    int width = 800;
    int height = 400;
    ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);

}

From source file:com.indicator_engine.controller.GraphController.java

@RequestMapping(value = "/jgraph", method = RequestMethod.GET)
public void processGraphRequests(@RequestParam(value = "indicator", required = false) String indicatorName,
        @RequestParam(value = "runFromMemory", defaultValue = "false", required = false) String runFromMemory,
        @RequestParam(value = "bean", defaultValue = "false", required = false) String runFromContextBean,
        @RequestParam(value = "default", defaultValue = "false", required = false) String defaultRun,
        HttpServletResponse response) {//from   w  ww. java  2  s.  co  m

    response.setContentType("image/png");
    if (defaultRun.equals("true")) {
        DefaultPieDataset dataSet = new DefaultPieDataset();
        dataSet.setValue("One", new Double(43.2));
        dataSet.setValue("Two", new Double(10.0));
        dataSet.setValue("Three", new Double(27.5));
        dataSet.setValue("Four", new Double(17.5));
        dataSet.setValue("Five", new Double(11.0));
        dataSet.setValue("Six", new Double(19.4));
        JFreeChart chart = createPieChart(dataSet, "Sample Graph");
        try {
            ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
            response.getOutputStream().close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else if (runFromContextBean.equals("true")) {
        EntitySpecification entitySpecificationBean = (EntitySpecification) appContext
                .getBean("entitySpecifications");
        if (entitySpecificationBean.getSelectedChartType().equals("Pie")) {
            PieDataset pdSet = createDataSet(entitySpecificationBean);
            JFreeChart chart = createPieChart(pdSet, entitySpecificationBean.getQuestionName());
            try {
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
                response.getOutputStream().close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else if (entitySpecificationBean.getSelectedChartType().equals("Bar")) {
            CategoryDataset dataset = createCategoryDataSet(entitySpecificationBean);
            JFreeChart chart = createBarChart(dataset, entitySpecificationBean.getQuestionName());
            try {
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
                response.getOutputStream().close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    } else if (runFromMemory.equals("true")) {

        EntitySpecification entitySpecificationBean = (EntitySpecification) appContext
                .getBean("entitySpecifications");
        GLAIndicator glaIndicator = new GLAIndicator();
        GLAIndicatorProps glaIndicatorProps = new GLAIndicatorProps();
        for (Iterator<GenQuery> genQuery = entitySpecificationBean.getQuestionsContainer().getGenQueries()
                .iterator(); genQuery.hasNext();) {
            GenQuery agenQuery = genQuery.next();
            if (agenQuery.getIndicatorName().equals(indicatorName)) {
                glaIndicator.setHql(agenQuery.getQuery());
                glaIndicator.setIndicator_name(agenQuery.getIndicatorName());
                glaIndicatorProps.setChartType(agenQuery.getGenIndicatorProps().getChartType());
                glaIndicatorProps.setComposite(agenQuery.getGenIndicatorProps().isComposite());
                glaIndicator.setGlaIndicatorProps(glaIndicatorProps);
            }
        }
        if (glaIndicator.getGlaIndicatorProps().getChartType().equals("Pie")) {
            PieDataset pdSet = createDataSet(glaIndicator);
            JFreeChart chart = createPieChart(pdSet, glaIndicator.getIndicator_name());
            try {
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
                response.getOutputStream().close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else if (glaIndicator.getGlaIndicatorProps().getChartType().equals("Bar")) {
            CategoryDataset dataset = createCategoryDataSet(glaIndicator);
            JFreeChart chart = createBarChart(dataset, glaIndicator.getIndicator_name());
            try {
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
                response.getOutputStream().close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    } else {

        GLAIndicatorDao glaIndicatorBean = (GLAIndicatorDao) appContext.getBean("glaIndicator");
        GLAQuestionDao glaQuestionBean = (GLAQuestionDao) appContext.getBean("glaQuestions");
        long indicatorID = glaIndicatorBean.findIndicatorID(indicatorName);
        GLAIndicator glaIndicator = glaIndicatorBean.loadByIndicatorID(indicatorID);
        if (glaIndicator.getGlaIndicatorProps().getChartType().equals("Pie")) {
            PieDataset pdSet = createDataSet(glaIndicator);
            JFreeChart chart = createPieChart(pdSet, glaIndicator.getIndicator_name());
            try {
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
                glaIndicatorBean.updateStatistics(indicatorID);
                long questionID = glaIndicatorBean.findQuestionID(indicatorID);
                glaQuestionBean.updateStatistics(questionID);
                response.getOutputStream().close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else if (glaIndicator.getGlaIndicatorProps().getChartType().equals("Bar")) {
            CategoryDataset dataset = createCategoryDataSet(glaIndicator);
            JFreeChart chart = createBarChart(dataset, glaIndicator.getIndicator_name());
            try {
                ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, 750, 400);
                glaIndicatorBean.updateStatistics(indicatorID);
                long questionID = glaIndicatorBean.findQuestionID(indicatorID);
                glaQuestionBean.updateStatistics(questionID);
                response.getOutputStream().close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

From source file:org.lsug.quota.web.internal.portlet.UserQuotaWebPortlet.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;/* w  w  w  .java 2  s .  c  o  m*/

    DefaultPieDataset pieDataset = new DefaultPieDataset();

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

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

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

        if (siteQuota != null && siteQuota.isEnabled()) {
            ResourceBundle resourceBundle = ResourceBundleUtil.getBundle("content.Language",
                    resourceRequest.getLocale(), getClass());
            pieDataset.setValue(LanguageUtil.get(resourceBundle, "used-space"),
                    siteQuota.getQuotaUsedPercentage());
            pieDataset.setValue(LanguageUtil.get(resourceBundle, "unused-space"),
                    100 - siteQuota.getQuotaUsedPercentage());

            sb.append(LanguageUtil.get(resourceBundle, "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:org.lsug.quota.portlet.SiteConfigurationQuotaPortlet.java

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

    StringBundler sb = new StringBundler(5);

    JFreeChart jFreeChart = null;//from ww w  . ja v a 2  s  . co  m

    DefaultPieDataset pieDataset = new DefaultPieDataset();

    try {
        long groupId = com.liferay.portal.util.PortalUtil.getScopeGroupId(resourceRequest);

        Group group = GroupLocalServiceUtil.getGroup(groupId);

        long classNameId = 0;

        if (QuotaUtil.isValidGroupQuota(group)) {
            classNameId = group.getClassNameId();

            if (group.isStagingGroup()) {
                groupId = group.getLiveGroupId();
            }
        }

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

        if (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, "sites-quota-enabled-sites-used-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:org.psystems.dicom.browser.server.stat.StatClientRequestsChartServlet.java

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

    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    CategoryDataset dataset = createDataset();
    JFreeChart chart = getChart(dataset);
    int width = 400;
    int height = 250;
    ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);

}

From source file:com.ikon.servlet.admin.StatsGraphServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String action = WebUtils.getString(request, "action", "graph");
    String type = WebUtils.getString(request, "t");
    JFreeChart chart = null;//  www .  ja va2  s  . c o  m
    updateSessionManager(request);

    try {
        if ("refresh".equals(action)) {
            new RepositoryInfo().runAs(null);
            ServletContext sc = getServletContext();
            sc.getRequestDispatcher("/admin/stats.jsp").forward(request, response);
        } else {
            response.setContentType("image/png");
            OutputStream out = response.getOutputStream();

            if (DOCUMENTS.equals(type) || DOCUMENTS_SIZE.equals(type) || FOLDERS.equals(type)) {
                chart = repoStats(type);
            } else if (DISK.equals(type)) {
                chart = diskStats();
            } else if (JVM_MEMORY.equals(type)) {
                chart = jvmMemStats();
            } else if (OS_MEMORY.equals(type)) {
                chart = osMemStats();
            }

            if (chart != null) {
                // Customize title font
                chart.getTitle().setFont(new Font("Tahoma", Font.BOLD, 16));

                // Match body {   background-color:#F6F6EE; }
                chart.setBackgroundPaint(new Color(246, 246, 238));

                // Customize no data
                PiePlot plot = (PiePlot) chart.getPlot();
                plot.setNoDataMessage("No data to display");

                // Customize labels
                plot.setLabelGenerator(null);

                // Customize legend
                LegendTitle legend = new LegendTitle(plot, new ColumnArrangement(), new ColumnArrangement());
                legend.setPosition(RectangleEdge.BOTTOM);
                legend.setFrame(BlockBorder.NONE);
                legend.setItemFont(new Font("Tahoma", Font.PLAIN, 12));
                chart.removeLegend();
                chart.addLegend(legend);

                if (DISK.equals(type) || JVM_MEMORY.equals(type) || OS_MEMORY.equals(type)) {
                    ChartUtilities.writeChartAsPNG(out, chart, 225, 225);
                } else {
                    ChartUtilities.writeChartAsPNG(out, chart, 250, 250);
                }
            }

            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get a base64-encoded image for inclusion in an img tag with a chart with kilobytes per minute produced and
 * consumed./*from  w w w  .j a v  a2 s  .  co  m*/
 *
 * @return chart as base64 string.
 */
public String getBase64BytesPerMinuteImage() {
    TimeSeries timeSeriesConsumed = new TimeSeries("Consumed");
    TimeSeries timeSeriesProduced = new TimeSeries("Produced");
    TimeSeries timeSeriesTotal = new TimeSeries("Total");
    for (PeriodMetrics m : getMessagesPerMinute()) {
        Minute minute = new Minute(m.getPeriodStart());
        timeSeriesConsumed.add(minute, m.getConsumedBytes() / 1024);
        timeSeriesProduced.add(minute, m.getProducedBytes() / 1024);
        timeSeriesTotal.add(minute, m.getTotalBytes() / 1024);
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(timeSeriesConsumed);
    timeSeriesCollection.addSeries(timeSeriesProduced);
    timeSeriesCollection.addSeries(timeSeriesTotal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Kilobytes per minute", "Time", "Bytes (k)",
                timeSeriesCollection);
        chart.getPlot().setBackgroundPaint(Color.WHITE);
        ChartUtilities.writeChartAsPNG(bos, chart, 1024, 500);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}