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:com.controller.PolicyController.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String action1 = request.getParameter("registerAction");
    System.out.println("ACTION    BY IMAGE " + action1);
    if ("pieChart".equals(action1)) {

        System.out.println("makePiechart");

        OutputStream out = response.getOutputStream(); /* Get the output stream from the response object */
        response.setContentType("image/png"); /* Set the HTTP Response Type */

        com.util.PieChart_AWT piechart = new com.util.PieChart_AWT("YoYo");

        JFreeChart chart = piechart.getPolicyChart();
        // Create chart

        ChartUtilities.writeChartAsPNG(out, chart, 500, 600);/* Write the data to the output stream */

    }/*from  w w  w .j a v  a 2s.  co m*/

}

From source file:org.openmrs.module.pmtct.web.view.chart.AbstractChartView.java

/**
 * @see org.springframework.web.servlet.view.AbstractView
 *//*from w  ww .j  ava2s  .c  o m*/
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // Respond as a PNG image
    response.setContentType("image/png");

    // Disable caching
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache");

    int width = 400;
    int height = 300;

    JFreeChart chart = createChart(model, request);
    chart.setBackgroundPaint(Color.WHITE);
    chart.getPlot().setOutlineStroke(new BasicStroke(0));
    chart.getPlot().setOutlinePaint(getBackgroundColor());
    chart.getPlot().setBackgroundPaint(getBackgroundColor());
    chart.getPlot().setNoDataMessage("No data available");

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);
}

From source file:org.pau.assetmanager.viewmodel.chart.ResourceImageGenerator.java

@Override
public String apply(JFreeChart jfchart) {
    String tempFileName = "";
    try {/*  w w w.  j a  va  2  s. c om*/
        ServletContext servletContext = Sessions.getCurrent().getWebApp().getServletContext();
        String tempDirPath = servletContext.getRealPath("") + File.separator + "TMP";
        File tempDir = new File(tempDirPath);
        if (!tempDir.exists()) {
            tempDir.mkdir();
        } else {
            cleanTempFolder(tempDir);
        }
        File tempFile = File.createTempFile("tmp", ".png", tempDir);
        tempFileName = tempFile.getName();
        FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
        ChartUtilities.writeChartAsPNG(fileOutputStream, jfchart, 1200, 500);
    } catch (Throwable t) {
        logger.error("Error generating chart.", t);
    }
    Clients.clearBusy();
    return "TMP" + File.separator + tempFileName;
}

From source file:com.voterData.controller.ChartGenerationController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  www .j  a  v  a2  s .  c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();

    String url = "/home.jsp";
    response.setContentType("image/png");
    OutputStream outputStream = response.getOutputStream();
    int width = 700;
    int height = 700;

    int width2 = 500;
    int height2 = 500;
    // get current action
    String action = request.getParameter("action");
    if (action == null) {
        url = "/home.jsp"; // default action
    } else {
        switch (action) {
        case "getPopulationDistribtn":
            ArrayList<VoterDetails> voterDetList = new ArrayList<VoterDetails>();
            voterDetList = VoterDetailsDB.getPopulationDist();
            JFreeChart chart = Graph.getPopulationDistChart(voterDetList);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width2, height2);
            break;

        case "getEthnicityDistribtn":
            ArrayList<VoterDetails> voterDetList2 = new ArrayList<VoterDetails>();
            voterDetList2 = VoterDetailsDB.getEthnicityDist();
            for (VoterDetails voterDetObj : voterDetList2) {
                System.out.println(voterDetObj.getEthnic_code() + " - "
                        + Double.parseDouble(voterDetObj.getVoter_reg_num()));
            }

            JFreeChart chart2 = Graph.getEthnicityDistChart(voterDetList2);
            ChartUtilities.writeChartAsPNG(outputStream, chart2, width2, height2);
            break;

        case "getRaceDistribtn":
            ArrayList<VoterDetails> voterDetList3 = new ArrayList<VoterDetails>();
            voterDetList3 = VoterDetailsDB.getRaceDist();
            JFreeChart chart3 = Graph.getRaceDistChart(voterDetList3);
            ChartUtilities.writeChartAsPNG(outputStream, chart3, width2, height2);
            break;

        case "getGenderDistribtn":

            Map<String, Double> chartData = ElectionsVotedDB.getGenderDistbn();
            JFreeChart genderDistChart = Graph.getGenderDistChart(chartData);
            ChartUtilities.writeChartAsPNG(outputStream, genderDistChart, width, height);
            break;

        case "getAgeDistribtn2008":

            Map<String, Double> chartMap = ElectionsVotedDB.getAgeDistbn2008();
            JFreeChart ageDistChart2008 = Graph.getAgeDistChart2008(chartMap);
            ChartUtilities.writeChartAsPNG(outputStream, ageDistChart2008, width, height);
            break;

        case "getAgeDistribtn2012":

            Map<String, Double> chartMap2 = ElectionsVotedDB.getAgeDistbn2012();
            JFreeChart ageDistChart2012 = Graph.getAgeDistChart2012(chartMap2);
            ChartUtilities.writeChartAsPNG(outputStream, ageDistChart2012, width, height);
            break;

        case "getEthnicityDistbn":
            Map<String, Double> chartMap4 = (Map<String, Double>) session.getAttribute("ethnicityMap");
            JFreeChart ethnicityChart = Graph.getEthnicityDistbn(chartMap4);
            ChartUtilities.writeChartAsPNG(outputStream, ethnicityChart, width, height);
            break;

        case "getHLEthnicityDistbn":
            Map<String, Double> charMap5 = (Map<String, Double>) session.getAttribute("ethnicityMap");
            JFreeChart hlethnicityChart = Graph.getHLEthnicityDistbn(charMap5);
            ChartUtilities.writeChartAsPNG(outputStream, hlethnicityChart, width, height);
            break;

        case "getRaceDistbn2008":
            Map<String, Double> chartMap5 = (Map<String, Double>) session.getAttribute("raceMap");
            JFreeChart raceChart2008 = Graph.getRaceDistbn2008(chartMap5);
            ChartUtilities.writeChartAsPNG(outputStream, raceChart2008, width, height);
            break;

        case "getRaceDistbn2012":
            Map<String, Double> charMap6 = (Map<String, Double>) session.getAttribute("raceMap");
            JFreeChart raceChart2012 = Graph.getRaceDistbn2012(charMap6);
            ChartUtilities.writeChartAsPNG(outputStream, raceChart2012, width, height);
            break;
        }
    }

}

From source file:org.radargun.reporting.BarPlotGenerator.java

/**
 * @param operation Name of the plotted operation
 * @param ranges ranges[0] = min, ranges[ranges.length - 1] = max
 * @param counts counts[i] is number of entries with value >= ranges[i - 1] and < ranges[i]
 * @param reportDir/*www .j a v a 2 s. c  o  m*/
 * @param filename
 * @throws IOException
 */
public static void generate(String operation, long[] ranges, long[] counts, String reportDir, String filename)
        throws IOException {
    XYSeries series = new XYSeries(operation + " response times");
    long totalCount = 0;
    for (long count : counts) {
        totalCount += count;
    }
    double left = Math.log10(ranges[0]);
    double right = Math.log10(ranges[ranges.length - 1]);

    for (int i = 0; i < counts.length; i++) {
        series.add(Math.log10(ranges[i]), (double) counts[i] / totalCount);
    }
    series.add(right, 0d);
    XYDataset dataset = new XYSeriesCollection(series);
    JFreeChart chart = ChartFactory.createXYStepAreaChart(operation + " response time histogram",
            "Response time", "Percentage", dataset, PlotOrientation.VERTICAL, false, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    NumberAxis d = (NumberAxis) plot.getDomainAxis();
    d.setRange(left, right);
    d.setStandardTickUnits(new HistoTickUnitSource());
    plot.setDomainAxis(d);
    FileOutputStream output = new FileOutputStream(new File(reportDir + File.separator + filename));
    ChartUtilities.writeChartAsPNG(output, chart, 1024, 768);
    output.close();
}

From source file:net.sourceforge.subsonic.controller.UserChartController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String type = request.getParameter("type");
    CategoryDataset dataset = createDataset(type);
    JFreeChart chart = createChart(dataset, request);

    int imageHeight = Math.max(IMAGE_MIN_HEIGHT, 15 * dataset.getColumnCount());

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, imageHeight);
    return null;//from  w ww.j  a v a 2 s. c om
}

From source file:com.hmsinc.epicenter.webapp.chart.ChartRenderingController.java

/**
 * @param id/*from w w  w  .  j a v  a 2  s.  c  om*/
 * @param width
 * @param height
 * @param response
 * @throws IOException
 */
@RequestMapping("/chart")
public void getChart(@RequestParam("id") final String id, @RequestParam("width") final int width,
        @RequestParam("height") final int height, final HttpServletResponse response) throws IOException {

    Validate.notNull(id, "No chart specified.");
    Validate.notNull(width, "No width specified.");
    Validate.notNull(height, "No height specified.");

    final Element e = chartCache.get(id);
    Validate.notNull(e, "Invalid chart id " + id);

    final JFreeChart chart = (JFreeChart) e.getObjectValue();
    Validate.notNull(chart, "Chart was null!");

    response.setContentType("image/png");
    response.addHeader("cache-control", "must-revalidate");

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);

}

From source file:org.openmrs.module.tracpatienttransfer.web.view.chart.AbstractChartView.java

/**
 * @see org.springframework.web.servlet.view.AbstractView
 *//* www.  j  a  va  2  s.c  o  m*/
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // Respond as a PNG image
    response.setContentType("image/png");

    // Disable caching
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache");

    int width = Integer.valueOf(request.getParameter("width"));
    int height = Integer.valueOf(request.getParameter("height"));
    ;

    JFreeChart chart = createChart(model, request);
    chart.setBackgroundPaint(Color.WHITE);
    chart.getPlot().setOutlineStroke(new BasicStroke(0));
    chart.getPlot().setOutlinePaint(getBackgroundColor());
    chart.getPlot().setBackgroundPaint(getBackgroundColor());
    chart.getPlot().setNoDataMessage(
            TransferOutInPatientUtil.getMessage("tracpatienttransfer.error.noDataAvailable", null));

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);
}

From source file:net.sqs2.omr.result.chart.StackedBarChart.java

public static void write(OutputStream outputStream, int width, int height, LegendHandler legendHandler,
        StatisticsContentsWriter statisticsContentsFactory) {
    // (1)create dataset
    List<Legend> legendList = legendHandler.getLegendList();
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Legend legend0 = legendList.get(0);// w  w  w  .j  a v  a 2 s  .co m
    Legend legend1 = legendList.get(1);
    for (FormArea formArea0 : legend0.formAreaList) {
        int itemIndex0 = formArea0.getItemIndex();
        for (FormArea formArea1 : legend1.formAreaList) {
            int itemIndex1 = formArea1.getItemIndex();
            String key = createKey(legendHandler.getAxis(), itemIndex0, itemIndex1);
            int count = statisticsContentsFactory.getCount(key);
            dataset.addValue(count, formArea1.getItemLabel(), formArea0.getItemLabel());
        }
        if (legend0.primaryFormArea.isSelectSingle()) {
            String key = createKey(legendHandler.getAxis(), itemIndex0, -1);
            int count = statisticsContentsFactory.getCount(key);
            dataset.addValue(count, ChartConstants.NO_ANSWER, formArea0.getItemLabel());
        }
    }
    if (legend1.primaryFormArea.isSelectSingle()) {
        for (FormArea formArea1 : legend1.formAreaList) {
            int itemIndex1 = formArea1.getItemIndex();
            String key = createKey(legendHandler.getAxis(), -1, itemIndex1);
            int count = statisticsContentsFactory.getCount(key);
            dataset.addValue(count, formArea1.getItemLabel(), ChartConstants.NO_ANSWER);
        }
    }
    if (legend1.primaryFormArea.isSelectSingle()) {
        String key = createKey(legendHandler.getAxis(), -1, -1);
        int count = statisticsContentsFactory.getCount(key);
        dataset.addValue(count, ChartConstants.NO_ANSWER, ChartConstants.NO_ANSWER);
    }

    // String title = StringUtil.join(formAreaList.get(0).getHints(), "\n");
    String title = "";
    // (2)create JFreeChart instance
    // JFreeChart chart =
    // ChartFactory.createBarChart(StringUtil.join(formAreaList.get(0).getHints(),
    // "\n"),
    JFreeChart chart = ChartFactory.createStackedBarChart(title, legend0.primaryFormArea.getLabel(),
            legend1.primaryFormArea.getLabel(), dataset, PlotOrientation.HORIZONTAL, true, false, false);

    // (3)create chart image
    try {
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
    } catch (IOException ioEx) {
        ioEx.printStackTrace();
    }
}

From source file:org.openmrs.web.taglib.ShowGraphTag.java

/**
 * Render graph./*  w  w w .  ja  v  a 2 s. c om*/
 *
 * @return return result code
 */
public int doStartTag() throws JspException {

    Patient patient = Context.getPatientService().getPatient(patientId);
    Concept concept = Context.getConceptService().getConceptByName(conceptName);

    if (concept != null && concept.isNumeric()) {
        List<Obs> observations = Context.getObsService().getObservationsByPersonAndConcept(patient, concept);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (Obs obs : observations) {
            dataset.addValue(obs.getValueNumeric(), conceptName, obs.getObsDatetime());
        }
        JFreeChart chart = ChartFactory.createLineChart(conceptName, "Value", "Date", dataset,
                PlotOrientation.VERTICAL, true, true, false);

        try {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            ChartUtilities.writeChartAsPNG(byteArray, chart, width, height);
            pageContext.getResponse().setContentType("image/png");
            pageContext.getResponse().getWriter().write(byteArray.toString());

        } catch (IOException e) {
            log.error(e);
        }
    }

    return EVAL_BODY_BUFFERED;
}