Example usage for org.jfree.chart.servlet ServletUtilities saveChartAsPNG

List of usage examples for org.jfree.chart.servlet ServletUtilities saveChartAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart.servlet ServletUtilities saveChartAsPNG.

Prototype

public static String saveChartAsPNG(JFreeChart chart, int width, int height, ChartRenderingInfo info,
        HttpSession session) throws IOException 

Source Link

Document

Saves the chart as a PNG format file in the temporary directory and populates the ChartRenderingInfo object which can be used to generate an HTML image map.

Usage

From source file:com.glaf.chart.util.ChartUtils.java

public static byte[] createChart(Chart chartModel, JFreeChart chart) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    try {// w w w .  j  a va2  s  .  c om
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        java.awt.image.BufferedImage bi = chart.createBufferedImage(chartModel.getChartWidth(),
                chartModel.getChartHeight());

        if ("png".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos);
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsPNG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        } else if ("jpeg".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos);
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsJPEG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        }

        bos.flush();
        baos.flush();

        return baos.toByteArray();

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(bos);
    }
}

From source file:nl.wur.plantbreeding.www.marker2seq.GoDistribution.java

/**
 * Generate the Pie chart for a set of given Go terms.
 * @param distrib a HashMap of GO name and GO frequency
 * @param title the title of the GO graph
 * @param url the url used for the tooltips
 * @param session the HttpSession used to save the file
 * @param legend Print the legend or not
 * @param tooltips Add tooltip or not//  ww  w .j  a v  a 2 s  .c o m
 * @param urls Add urls or not (link in the graph)
 * @param max Maximum number of item to display
 * @return a list containing the filename and the map for the figure
 * @throws IOException when something happens while writting the image
 */
public static String[] generateDistribution(final HashMap<String, Integer> distrib, final String title,
        final String url, final HttpSession session, final boolean legend, final boolean tooltips,
        final boolean urls, final int max) throws IOException {

    final PieChart piec = new PieChart();
    final PieDataset piedata = piec.createDataset(distrib);

    final JFreeChart chart = piec.createChart(piedata, title, legend, tooltips, urls);
    final PiePlot plot = (PiePlot) chart.getPlot();
    if (distrib.size() >= max) {
        plot.setLabelGenerator(null);
    }
    plot.setURLGenerator(new StandardPieURLGenerator(url, "section"));

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    final String filename = ServletUtilities.saveChartAsPNG(chart, 500, 400, info, session);

    final String map = ChartUtilities.getImageMap(filename, info);

    final String[] output = { filename, map };
    return output;
}

From source file:com.glaf.chart.util.ChartUtils.java

public static void createChart(String path, Chart chartModel, JFreeChart chart) {
    try {//  ww  w . ja va2 s  . c  o  m
        java.awt.image.BufferedImage bi = chart.createBufferedImage(chartModel.getChartWidth(),
                chartModel.getChartHeight());

        String name = chartModel.getChartName();
        if (StringUtils.isNotEmpty(chartModel.getMapping())) {
            name = chartModel.getMapping();
        }

        if ("png".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(),
                    new FileOutputStream(path + "/" + name + ".png"));
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsPNG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        } else if ("jpeg".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(),
                    new FileOutputStream(path + "/" + name + ".jpg"));
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsJPEG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:org.webguitoolkit.ui.controls.chart.Chart.java

/**
 * generate the image an send the url to the client
 *//* w  ww.  j  a v a  2 s  .c o m*/
public void load() {
    HttpSession session = Page.getServletRequest().getSession(true);
    ChartRenderingInfo info = new ChartRenderingInfo();
    JFreeChart chart = getModel().getChart();
    if (chart == null)
        return; // happen for example in the init process

    try {
        String filename = ServletUtilities.saveChartAsPNG(chart, getWidth(), getHeight(), info, session);
        filename = URLEncoder.encode(filename, "UTF-8");
        String mapName = id4Map() + filename + ".name";
        String imagemap = ImageMapUtilities.getImageMap(mapName, info, new OverLIBToolTipTagFragmentGenerator(),
                null); // no urls   

        // transfer image map to clinet
        getContext().add(id4Map(), imagemap, IContext.TYPE_HTML, IContext.STATUS_NOT_EDITABLE);
        // the img-tag to use the map
        getContext().add(id4Img() + ".usemap", "#" + mapName, IContext.TYPE_ATT, IContext.STATUS_NOT_EDITABLE);
        // transfer src- atribute to client

        String imageUrl = "Chart/DisplayChart?filename=" + filename;
        getContext().add(id4Img() + ".src", imageUrl, IContext.TYPE_ATT, IContext.STATUS_NOT_EDITABLE);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WGTException(e);
    }
}

From source file:nl.wur.plantbreeding.www.marker2seq.GoDistribution.java

/**
 * Generate the Pie chart for a set of given Go terms.
 * @param gotermlist of String (here GO names)
 * @param title the title of the GO graph
 * @param url the url used for the tooltips
 * @param session the HttpSession used to save the file
 * @param legend Print the legend or not
 * @param tooltips Add tooltip or not/*from   w ww  .j av  a 2  s .  c om*/
 * @param urls Add urls or not (link in the graph)
 * @param max Maximum number of item to display
 * @return a list containing the filename and the map for the figure
 * @throws IOException when something happens while writting the image
 */
public static String[] generateDistribution(final List<String> gotermlist, final String title, final String url,
        final HttpSession session, final boolean legend, final boolean tooltips, final boolean urls,
        final int max) throws IOException {
    final PieChart piec = new PieChart();
    final PieDataset dataset = piec.createDataset(gotermlist);
    final JFreeChart chart = piec.createChart(dataset, title, legend, tooltips, urls);
    final PiePlot plot = (PiePlot) chart.getPlot();
    if (gotermlist.size() >= max) {
        plot.setLabelGenerator(null);
    }
    plot.setURLGenerator(new StandardPieURLGenerator(url, "section"));

    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    final String filename = ServletUtilities.saveChartAsPNG(chart, 500, 400, info, session);

    final String map = ChartUtilities.getImageMap(filename, info);

    final String[] output = { filename, map };
    return output;

}

From source file:org.gaixie.micrite.action.GenericAction.java

public void putChartResultList(JFreeChart chart) {
    StandardEntityCollection entityCollection = new StandardEntityCollection();
    ChartRenderingInfo info = new ChartRenderingInfo(entityCollection);
    String filename = "";
    try {//from  w w w. j ava 2 s.c o  m
        filename = ServletUtilities.saveChartAsPNG(chart, getChartWidth(), getChartHeight(), info, null);
        String mapName = "map" + new Date();
        String mapInfo = ChartUtilities.getImageMap(mapName, info);
        resultMap.put("success", true);
        resultMap.put("filename", filename);
        resultMap.put("map", mapInfo);
        resultMap.put("mapName", mapName);
    } catch (IOException e) {
        resultMap.put("success", false);
    }
}

From source file:gov.nih.nci.cma.web.graphing.PCAPlot.java

public String generatePCAPlotChart(String components, HttpServletRequest request, PrintWriter pw) {
    String finalURLpath = null; //imageHandler.getFinalURLPath();
    try {/*from w  ww  .j  a  v  a2s. c  o  m*/
        //check the components to see which graph to get
        CMAPrincipalComponentAnalysisPlot plot = null;
        if (components.equalsIgnoreCase("PC1vsPC2")) {
            plot = new CMAPrincipalComponentAnalysisPlot(pcaData, PCAcomponent.PC2, PCAcomponent.PC1,
                    sampleGroupNames);
        }
        if (components.equalsIgnoreCase("PC1vsPC3")) {
            plot = new CMAPrincipalComponentAnalysisPlot(pcaData, PCAcomponent.PC3, PCAcomponent.PC1,
                    sampleGroupNames);
        }
        if (components.equalsIgnoreCase("PC2vsPC3")) {
            plot = new CMAPrincipalComponentAnalysisPlot(pcaData, PCAcomponent.PC3, PCAcomponent.PC2,
                    sampleGroupNames);
        }
        chart = plot.getChart();

        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        // BW
        if (chart != null) {
            //int bwwidth = new BigDecimal(1.5).multiply(new BigDecimal(imgW)).intValue();
            finalURLpath = ServletUtilities.saveChartAsPNG(chart, 500, 400, info, request.getSession());
            CustomOverlibToolTipTagFragmentGenerator ttip = new CustomOverlibToolTipTagFragmentGenerator();
            ttip.setExtra(" href='javascript:void(0);' "); //must have href for area tags to have cursor:pointer
            //ChartUtilities.writeImageMap(pw, finalURLpath, info,
            //      ttip,
            //      new StandardURLTagFragmentGenerator());
            //ChartUtilities.writeImageMap(pw, finalURLpath, info, true);
            pw.write(ImageMapUtil.getBoundingRectImageMapTag(finalURLpath, false, info));
            info.clear(); // lose the first one
            info = new ChartRenderingInfo(new StandardEntityCollection());
        }

        pw.flush();
    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }
    return finalURLpath;
}

From source file:org.orbeon.oxf.processor.JFreeChartProcessor.java

protected ChartInfo createChart(org.orbeon.oxf.pipeline.api.PipelineContext context,
        JFreeChartSerializer.ChartConfig chartConfig) {

    Document data = readInputAsDOM4J(context, getInputByName(INPUT_DATA));

    Dataset ds;//from   w  ww . ja v  a  2s .  c om
    if (chartConfig.getType() == JFreeChartSerializer.ChartConfig.PIE_TYPE
            || chartConfig.getType() == JFreeChartSerializer.ChartConfig.PIE3D_TYPE)
        ds = createPieDataset(chartConfig, data);
    else if (chartConfig.getType() == ChartConfig.XY_LINE_TYPE)
        ds = createXYDataset(chartConfig, data);
    else if (chartConfig.getType() == ChartConfig.TIME_SERIES_TYPE)
        ds = createTimeSeriesDataset(chartConfig, data);
    else
        ds = createDataset(chartConfig, data);

    JFreeChart chart = drawChart(chartConfig, ds);
    ChartRenderingInfo info = new ChartRenderingInfo();

    String file;
    try {
        final ExternalContext.Session session = ((ExternalContext) context
                .getAttribute(PipelineContext.EXTERNAL_CONTEXT)).getSession(true);
        file = ServletUtilities.saveChartAsPNG(chart, chartConfig.getxSize(), chartConfig.getySize(), info,
                new HttpSession() {
                    public Object getAttribute(String s) {
                        return session.getAttributesMap(PortletSession.APPLICATION_SCOPE).get(s);
                    }

                    public Enumeration getAttributeNames() {
                        return Collections.enumeration(
                                session.getAttributesMap(PortletSession.APPLICATION_SCOPE).keySet());
                    }

                    public long getCreationTime() {
                        return session.getCreationTime();
                    }

                    public String getId() {
                        return session.getId();
                    }

                    public long getLastAccessedTime() {
                        return session.getLastAccessedTime();
                    }

                    public int getMaxInactiveInterval() {
                        return session.getMaxInactiveInterval();
                    }

                    public ServletContext getServletContext() {
                        return null;
                    }

                    public HttpSessionContext getSessionContext() {
                        return null;
                    }

                    public Object getValue(String s) {
                        return getAttribute(s);
                    }

                    public String[] getValueNames() {
                        List list = new ArrayList();
                        for (Enumeration e = getAttributeNames(); e.hasMoreElements();) {
                            list.add(e.nextElement());
                        }
                        String[] array = new String[list.size()];
                        list.toArray(array);
                        return array;
                    }

                    public void invalidate() {
                        session.invalidate();
                    }

                    public boolean isNew() {
                        return session.isNew();
                    }

                    public void putValue(String s, Object o) {
                        setAttribute(s, o);
                    }

                    public void removeAttribute(String s) {
                        session.getAttributesMap(PortletSession.APPLICATION_SCOPE).remove(s);
                    }

                    public void removeValue(String s) {
                        removeAttribute(s);
                    }

                    public void setAttribute(String s, Object o) {
                        session.getAttributesMap(PortletSession.APPLICATION_SCOPE).put(s, o);
                    }

                    public void setMaxInactiveInterval(int i) {
                        session.setMaxInactiveInterval(i);
                    }
                });
    } catch (Exception e) {
        throw new OXFException(e);
    }
    return new ChartInfo(info, file);
}

From source file:org.cyberoam.iview.charts.Chart.java

/**
 * Get chart for web application rendering. 
 * @param Request instance used for chart generation process
 * @param out instance used for tool tip image map
 * @param rsw specifies data set which would be used for the Chart
 * @param requeest used for Hyperlink generation from uri.
 * @param imagehieght used for image height
 * @param imagewidht used for image width
 * @return fileName//from  ww  w  .  j a  va  2s  . c  o m
 */
public static String getChartForWeb(HttpServletRequest request, PrintWriter out, ResultSetWrapper rsw,
        int imageWidth, int imageHeight) {
    String fileName = null;
    try {
        int reportID = request.getParameter("reportid") == null ? -1
                : Integer.parseInt(request.getParameter("reportid"));
        JFreeChart chart = Chart.getChart(reportID, rsw, request);

        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        //Save the generated Chart image to system temporary directory.
        fileName = ServletUtilities.saveChartAsPNG(chart, imageWidth, imageHeight, info, request.getSession());
        //  Write the tool tip map to GUI.
        org.jfree.chart.ChartUtilities.writeImageMap(out, fileName, info, false);
        out.flush();
    } catch (Exception e) {
        CyberoamLogger.appLog.debug("Chart.getChartForWeb:" + e, e);
    }
    return fileName;
}

From source file:org.n52.server.sos.generator.Generator.java

protected String createAndSaveImage(DesignOptions options, JFreeChart chart, ChartRenderingInfo renderingInfo)
        throws Exception {
    int width = options.getWidth();
    int height = options.getHeight();
    BufferedImage image = chart.createBufferedImage(width, height, renderingInfo);
    Graphics2D chartGraphics = image.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);
    chart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));

    try {//from   ww w. ja v  a  2s  . c  om
        return ServletUtilities.saveChartAsPNG(chart, width, height, renderingInfo, null);
    } catch (IOException e) {
        throw new Exception("Could not save PNG!", e);
    }
}