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:net.commerce.zocalo.freechart.ChartTest.java

public void testOverlaidOHLCPlusStepChart() throws IOException {
    Minute now = new Minute();
    File jpgFile = newEmptyFile(".", "OverlaidChart.jpg");
    File pngFile = newEmptyFile(".", "OverlaidChart.png");

    assertFalse(jpgFile.exists());//from w  w  w  .  ja  va2  s.co  m
    assertFalse(pngFile.exists());

    TimePeriodValuesCollection bottom = createBottomValues(now);
    TimePeriodValuesCollection top = createTopValues(now);

    OHLCDataset OHLCdata = createOHLCDataSet(now);
    JFreeChart chart = ChartGenerator.createOverlaidOHLCAndStepChart(bottom, top, OHLCdata);

    OutputStream jpgStream = new FileOutputStream(jpgFile);
    OutputStream pngStream = new FileOutputStream(pngFile);
    ChartUtilities.writeChartAsJPEG(jpgStream, chart, 500, 500);
    ChartUtilities.writeChartAsPNG(pngStream, chart, 500, 500);

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

From source file:org.projectforge.web.scripting.ScriptingPage.java

private void jFreeChartExport() {
    try {// w  ww . ja v a 2s  . c  o  m
        final ExportJFreeChart exportJFreeChart = (ExportJFreeChart) groovyResult.getResult();
        final JFreeChart chart = exportJFreeChart.getJFreeChart();
        final int width = exportJFreeChart.getWidth();
        final int height = exportJFreeChart.getHeight();
        final StringBuffer buf = new StringBuffer();
        buf.append("pf_chart_");
        buf.append(DateHelper.getTimestampAsFilenameSuffix(new Date()));
        final Response response = getResponse();
        if (exportJFreeChart.getImageType() == JFreeChartImageType.PNG) {
            ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);
            buf.append(".png");
        } else {
            ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, width, height);
            buf.append(".jpg");
        }
        final String filename = buf.toString();
        final JFreeChartImage image = new JFreeChartImage("image", chart, exportJFreeChart.getImageType(),
                width, height);
        image.add(AttributeModifier.replace("width", String.valueOf(width)));
        image.add(AttributeModifier.replace("height", String.valueOf(height)));
        imageResultContainer.removeAll();
        imageResultContainer.add(image).setVisible(true);
        ((WebResponse) response).setAttachmentHeader(filename);
        ((WebResponse) response).setContentType(DownloadUtils.getContentType(filename));
        response.getOutputStream().flush();
    } catch (final Exception ex) {
        error(getLocalizedMessage("error", ex.getMessage()));
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.gbif.portal.web.controller.dataset.IndexingHistoryController.java

/**
 * Create a time series graphic to display indexing processes.
 * /*from  w w w.j ava 2  s.c o  m*/
 * @param dataProvider
 * @param dataResource
 * @param activities
 * @param fileNamePrefix
 * @return
 */
public String timeSeriesTest(DataProviderDTO dataProvider, DataResourceDTO dataResource,
        List<LoggedActivityDTO> loggedActivities, String fileNamePrefix, int minProcessingTimeToRender) {

    List<LoggedActivityDTO> activities = new ArrayList<LoggedActivityDTO>();
    for (LoggedActivityDTO la : loggedActivities) {
        if (la.getDataResourceKey() != null && la.getDataResourceName() != null && la.getEventName() != null)
            activities.add(la);
    }

    //if no activities to render, return
    if (activities.isEmpty())
        return null;

    Map<String, Integer> drActualCount = new HashMap<String, Integer>();
    Map<String, Integer> drCount = new HashMap<String, Integer>();

    //record the actual counts
    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {
            if (drActualCount.get(laDTO.getDataResourceName()) == null) {
                drActualCount.put(laDTO.getDataResourceName(), new Integer(4));
                drCount.put(laDTO.getDataResourceName(), new Integer(0));
            } else {
                Integer theCount = drActualCount.get(laDTO.getDataResourceName());
                theCount = new Integer(theCount.intValue() + 4);
                drActualCount.remove(laDTO.getDataResourceName());
                drActualCount.put(laDTO.getDataResourceName(), theCount);
            }
        }
    }

    StringBuffer fileNameBuffer = new StringBuffer(fileNamePrefix);
    if (dataResource != null) {
        fileNameBuffer.append("-resource-");
        fileNameBuffer.append(dataResource.getKey());
    } else if (dataProvider != null) {
        fileNameBuffer.append("-provider-");
        fileNameBuffer.append(dataProvider.getKey());
    }
    fileNameBuffer.append(".png");

    String fileName = fileNameBuffer.toString();
    String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName;
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    boolean generateChart = false;

    int count = 1;
    int dataResourceCount = 1;

    Collections.sort(activities, new Comparator<LoggedActivityDTO>() {
        public int compare(LoggedActivityDTO o1, LoggedActivityDTO o2) {
            if (o1 == null || o2 == null || o1.getDataResourceKey() != null || o2.getDataResourceKey() != null)
                return -1;
            return o1.getDataResourceKey().compareTo(o2.getDataResourceKey());
        }
    });

    String currentDataResourceKey = activities.get(0).getDataResourceKey();

    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {

            if (currentDataResourceKey != null && !currentDataResourceKey.equals(laDTO.getDataResourceKey())) {
                dataResourceCount++;
                count = count + 1;
                currentDataResourceKey = laDTO.getDataResourceKey();
            }
            TimeSeries s1 = new TimeSeries(laDTO.getDataResourceName(), "Process time period",
                    laDTO.getEventName(), Hour.class);
            s1.add(new Hour(laDTO.getStartDate()), count);
            s1.add(new Hour(laDTO.getEndDate()), count);
            dataset.addSeries(s1);
            generateChart = true;
        }
    }

    if (!generateChart)
        return null;

    // create a pie chart...
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);

    XYPlot plot = chart.getXYPlot();
    plot.setWeight(10);
    plot.getRangeAxis().setAutoRange(false);
    plot.getRangeAxis().setRange(0, drCount.size() + 1);
    plot.getRangeAxis().setAxisLineVisible(false);
    plot.getRangeAxis().setAxisLinePaint(Color.WHITE);
    plot.setDomainCrosshairValue(1);
    plot.setRangeGridlinesVisible(false);
    plot.getRangeAxis().setVisible(false);
    plot.getRangeAxis().setLabel("datasets");

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setItemLabelsVisible(true);
    MyXYItemLabelGenerator labelGenerator = new MyXYItemLabelGenerator();
    labelGenerator.setDataResourceActualCount(drActualCount);
    labelGenerator.setDataResourceCount(drCount);
    renderer.setItemLabelGenerator(labelGenerator);

    List<TimeSeries> seriesList = dataset.getSeries();
    for (TimeSeries series : seriesList) {
        if (((String) series.getRangeDescription()).startsWith("extraction")) {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.RED);
        } else {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.BLUE);
        }
        renderer.setSeriesStroke(seriesList.indexOf(series), new BasicStroke(7f));
    }

    int imageHeight = 30 * dataResourceCount;
    if (imageHeight < 100) {
        imageHeight = 100;
    } else {
        imageHeight = imageHeight + 100;
    }

    final BufferedImage image = new BufferedImage(900, imageHeight, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 900, imageHeight);

    // draw
    chart.draw(g2, chartArea, null, null);

    //styling
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    try {
        FileOutputStream fOut = new FileOutputStream(filePath);
        ChartUtilities.writeChartAsPNG(fOut, chart, 900, imageHeight);
        return fileName;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.smhdemo.common.report.generate.factory.ChartFactory.java

public byte[] export(Chart report, Map<String, String> pageParams) throws Exception {
    if (report == null) {
        return null;
    }/*from  w  w w. jav  a 2  s . c o  m*/
    DefaultCategoryDataset dataset = buildDataset(report, pageParams);
    java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(),
            report.getFontSize());
    String chartTitle = report.getChartTitle();
    chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
    String horizAxisLabel = report.getHorizAxisLabel();
    horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
    String vertAxisLabel = report.getVertAxisLabel();
    vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
    Boolean showLegend = report.getShowLegend();
    Boolean showTooltips = report.getShowTooltips();
    Boolean drillThroughEnabled = false;
    Chart.Type chartType = report.getType();

    CategoryURLGenerator urlGenerator = null;

    JFreeChart chart = null;
    switch (chartType) {
    case VERTBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case VERTBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDHORIZBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case STACKEDHORIZBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case VERTLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case PIEBYCOLUMN:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYROW:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYCOLUMN3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);

        break;
    case PIEBYROW3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    default:
        throw new BaseException("", "");
    }
    try {
        Integer bgColorR = report.getBgColorR();
        Integer bgColorG = report.getBgColorG();
        Integer bgColorB = report.getBgColorB();
        chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

        String axisFontName = report.getAxisFontName();
        Integer axisFontStyle = report.getAxisFontStyle();
        Integer axisFontSize = report.getAxisFontSize();
        java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);

        String axisTickFontName = report.getAxisTickFontName();
        Integer axisTickFontStyle = report.getAxisTickFontStyle();
        Integer axisTickFontSize = report.getAxisTickFontSize();
        java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);

        String legendFontName = report.getLegendFontName();
        Integer legendFontStyle = report.getLegendFontStyle();
        Integer legendFontSize = report.getLegendFontSize();
        java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
        Integer tickLabelRotate = report.getTickLabelRotate();

        String dataFontName = report.getDataFontName();
        Integer dataFontStyle = report.getDataFontStyle();
        Integer dataFontSize = report.getDataFontSize();
        java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);

        Plot plot = chart.getPlot();
        if (!(plot instanceof MultiplePiePlot)) {
            CategoryPlot categoryPlot = chart.getCategoryPlot();
            CategoryItemRenderer renderer = categoryPlot.getRenderer();
            renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
            renderer.setBaseItemLabelFont(dataFont);
            renderer.setBaseItemLabelsVisible(true);
            if (chartType == Chart.Type.VERTLINE || chartType == Chart.Type.HORIZLINE) {
                LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                lineRenderer.setBaseShapesVisible(true);
                lineRenderer.setDrawOutlines(true);
                lineRenderer.setUseFillPaint(true);
            }
        }

        if (plot instanceof CategoryPlot) {
            CategoryPlot catPlot = (CategoryPlot) plot;
            catPlot.getDomainAxis().setLabelFont(axisFont);
            catPlot.getRangeAxis().setLabelFont(axisFont);
            catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
            catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
            catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f);
            double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate;
            CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions();
            CategoryLabelPositions newp = new CategoryLabelPositions(oldp.getLabelPosition(RectangleEdge.TOP),
                    new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT,
                            TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f),
                    oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT));
            catPlot.getDomainAxis().setCategoryLabelPositions(newp);
        } else if (plot instanceof PiePlot3D) {
            PiePlot3D piePlot = (PiePlot3D) plot;
            piePlot.setLabelFont(axisFont);
            piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
            piePlot.setForegroundAlpha(0.5f);
            piePlot.setNoDataMessage("?");
        } else if (plot instanceof PiePlot) {
            PiePlot piePlot = (PiePlot) plot;
            piePlot.setLabelFont(axisFont);
        }
        LegendTitle legend = (LegendTitle) chart.getLegend();
        if (legend != null) {
            legend.setItemFont(legendFont);
            RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
            Integer legendPosition = report.getLegendPosition();
            switch (legendPosition) {
            case 0:
                legendRectEdge = RectangleEdge.LEFT;
                break;
            case 1:
                legendRectEdge = RectangleEdge.TOP;
                break;
            case 2:
                legendRectEdge = RectangleEdge.RIGHT;
                break;
            case 3:
                legendRectEdge = RectangleEdge.BOTTOM;
                break;
            }
            legend.setPosition(legendRectEdge);
        }
    } catch (Exception e) {
        logger.error("Chart Export Exception", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
    return out.toByteArray();
}

From source file:com.ewcms.plugin.report.generate.factory.ChartFactory.java

public byte[] export(ChartReport report, Map<String, String> pageParams) throws Exception {
    if (report == null) {
        return null;
    }/*www  .  j av  a 2 s .c  o  m*/
    DefaultCategoryDataset dataset = buildDataset(report, pageParams);
    java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(),
            report.getFontSize());
    String chartTitle = report.getChartTitle();
    chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
    String horizAxisLabel = report.getHorizAxisLabel();
    horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
    String vertAxisLabel = report.getVertAxisLabel();
    vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
    Boolean showLegend = report.getShowLegend();
    Boolean showTooltips = report.getShowTooltips();
    Boolean drillThroughEnabled = false;
    ChartReport.Type chartType = report.getType();

    CategoryURLGenerator urlGenerator = null;

    JFreeChart chart = null;
    switch (chartType) {
    case VERTBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case VERTBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDHORIZBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case STACKEDHORIZBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case VERTLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case PIEBYCOLUMN:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYROW:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYCOLUMN3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);

        break;
    case PIEBYROW3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    default:
        throw new BaseException("", "");
    }
    try {
        Integer bgColorR = report.getBgColorR();
        Integer bgColorG = report.getBgColorG();
        Integer bgColorB = report.getBgColorB();
        chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

        String axisFontName = report.getAxisFontName();
        Integer axisFontStyle = report.getAxisFontStyle();
        Integer axisFontSize = report.getAxisFontSize();
        java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);

        String axisTickFontName = report.getAxisTickFontName();
        Integer axisTickFontStyle = report.getAxisTickFontStyle();
        Integer axisTickFontSize = report.getAxisTickFontSize();
        java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);

        String legendFontName = report.getLegendFontName();
        Integer legendFontStyle = report.getLegendFontStyle();
        Integer legendFontSize = report.getLegendFontSize();
        java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
        Integer tickLabelRotate = report.getTickLabelRotate();

        String dataFontName = report.getDataFontName();
        Integer dataFontStyle = report.getDataFontStyle();
        Integer dataFontSize = report.getDataFontSize();
        java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);

        Plot plot = chart.getPlot();
        if (!(plot instanceof MultiplePiePlot)) {
            CategoryPlot categoryPlot = chart.getCategoryPlot();
            CategoryItemRenderer renderer = categoryPlot.getRenderer();
            renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
            renderer.setBaseItemLabelFont(dataFont);
            renderer.setBaseItemLabelsVisible(true);
            if (chartType == ChartReport.Type.VERTLINE || chartType == ChartReport.Type.HORIZLINE) {
                LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                lineRenderer.setBaseShapesVisible(true);
                lineRenderer.setDrawOutlines(true);
                lineRenderer.setUseFillPaint(true);
            }
        }

        if (plot instanceof CategoryPlot) {
            CategoryPlot catPlot = (CategoryPlot) plot;
            catPlot.getDomainAxis().setLabelFont(axisFont);
            catPlot.getRangeAxis().setLabelFont(axisFont);
            catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
            catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
            catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f);
            double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate;
            CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions();
            CategoryLabelPositions newp = new CategoryLabelPositions(oldp.getLabelPosition(RectangleEdge.TOP),
                    new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT,
                            TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f),
                    oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT));
            catPlot.getDomainAxis().setCategoryLabelPositions(newp);
        } else if (plot instanceof PiePlot3D) {
            PiePlot3D piePlot = (PiePlot3D) plot;
            piePlot.setLabelFont(axisFont);
            piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
            piePlot.setForegroundAlpha(0.5f);
            piePlot.setNoDataMessage("?");
        } else if (plot instanceof PiePlot) {
            PiePlot piePlot = (PiePlot) plot;
            piePlot.setLabelFont(axisFont);
        }
        LegendTitle legend = (LegendTitle) chart.getLegend();
        if (legend != null) {
            legend.setItemFont(legendFont);
            RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
            Integer legendPosition = report.getLegendPosition();
            switch (legendPosition) {
            case 0:
                legendRectEdge = RectangleEdge.LEFT;
                break;
            case 1:
                legendRectEdge = RectangleEdge.TOP;
                break;
            case 2:
                legendRectEdge = RectangleEdge.RIGHT;
                break;
            case 3:
                legendRectEdge = RectangleEdge.BOTTOM;
                break;
            }
            legend.setPosition(legendRectEdge);
        }
    } catch (Exception e) {
        logger.error("Chart Export Exception", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
    return out.toByteArray();
}

From source file:osh.comdriver.simulation.cruisecontrol.ScheduleDrawer.java

public void refreshDiagram(List<Schedule> schedules, HashMap<VirtualCommodity, PriceSignal> ps,
        HashMap<VirtualCommodity, PowerLimitSignal> pls, long time, boolean saveGraph) {

    JFreeChart chart = createStuffForPanel(schedules, ps, pls, time);

    if (!saveGraph) {
        panel.setChart(chart);// w w w.j av a2 s . c o m
    } else {
        BufferedOutputStream out;
        try {
            out = new BufferedOutputStream(new FileOutputStream("logs/graphic_" + counter + ".png"));
            ChartUtilities.writeChartAsPNG(out, chart, 1024, 768);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        counter++;
    }

}

From source file:org.paxle.tools.charts.impl.gui.ChartServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response) {
    String chartType = null;/*from  ww w.  jav a2s  . c om*/
    try {
        String display = request.getParameter("display");
        chartType = request.getParameter("t");

        if ((display == null || display.equals("plain")) && (chartType != null)) {
            // getting requested graph size 
            String wStrg = request.getParameter("w");
            int width = Integer.parseInt(wStrg == null ? "385" : wStrg);

            String hStrg = request.getParameter("h");
            int height = Integer.parseInt(hStrg == null ? "200" : hStrg);

            // getting the reuested chart
            JFreeChart chart = this.chartMap.get(chartType);
            if (chart == null) {
                response.setStatus(404);
                return;
            }

            // set response type
            response.setContentType("image/png");

            // render image
            ServletOutputStream out = response.getOutputStream();
            ChartUtilities.writeChartAsPNG(out, chart, width, height);
            out.flush();
        } else {
            // using velocity template
            super.doRequest(request, response);
        }
    } catch (Exception e) {
        if (e instanceof IIOException && e.getCause() != null && e.getCause().getCause() != null
                && e.getCause().getCause().getMessage() != null
                && e.getCause().getCause().getMessage().equalsIgnoreCase("Broken pipe")) {
            this.logger.debug(String.format("Broken pipe while writing chart '%s'.", chartType));
        } else if (e.getClass().getName().equals("org.mortbay.jetty.EofException")) { //c.f. bug #293
            this.logger.debug(String.format("Broken connection while writing chart '%s'.", chartType));
        } else {
            this.logger.error(String.format("Unexpected '%s' while writing chart '%s'.", e.getClass().getName(),
                    chartType), e);
        }
    }
}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Add graph in slide/*from   w w  w.j av  a 2s.  c o  m*/
 * 
 * @param slideToSet slide to set
 * @param graph graph to add
 * @param anchor place to add graph
 * @throws IOException if error
 */
protected void addJFreeChart(Slide slideToSet, JFreeChart graph, Rectangle anchor) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int width = anchor.width;
    int height = anchor.height;
    if (width <= 0) {
        width = getPresentation().getPageSize().width;
    }
    if (height <= 0) {
        height = getPresentation().getPageSize().height;
    }
    ChartUtilities.writeChartAsPNG(out, graph, width, height);
    addPicture(slideToSet, out.toByteArray(), anchor);
}

From source file:org.pentaho.platform.plugin.action.jfreechart.ChartComponent.java

@Override
protected boolean executeAction() {
    int height = -1;
    int width = -1;
    String title = ""; //$NON-NLS-1$
    Node chartDocument = null;//  w ww  .  j av a  2 s  . co m
    IPentahoResultSet data = (IPentahoResultSet) getInputValue(ChartComponent.CHART_DATA_PROP);
    if (!data.isScrollable()) {
        getLogger().debug("ResultSet is not scrollable. Copying into memory"); //$NON-NLS-1$
        IPentahoResultSet memSet = data.memoryCopy();
        data.close();
        data = memSet;
    }

    String urlTemplate = (String) getInputValue(ChartComponent.URL_TEMPLATE);

    Node chartAttributes = null;
    String chartAttributeString = null;

    // Attempt to get chart attributes as an input string or as a resource file
    // If these don't trip, then we assume the chart attributes are defined in
    // the component-definition of the chart action.

    if (getInputNames().contains(ChartComponent.CHART_ATTRIBUTES_PROP)) {
        chartAttributeString = getInputStringValue(ChartComponent.CHART_ATTRIBUTES_PROP);
    } else if (isDefinedResource(ChartComponent.CHART_ATTRIBUTES_PROP)) {
        IActionSequenceResource resource = getResource(ChartComponent.CHART_ATTRIBUTES_PROP);
        chartAttributeString = getResourceAsString(resource);
    }

    // Realize chart attributes as an XML document
    if (chartAttributeString != null) {
        try {
            chartDocument = XmlDom4JHelper.getDocFromString(chartAttributeString, new PentahoEntityResolver());
        } catch (XmlParseException e) {
            getLogger().error(
                    Messages.getInstance().getString("ChartComponent.ERROR_0005_CANT_DOCUMENT_FROM_STRING"), e); //$NON-NLS-1$
            return false;
        }

        chartAttributes = chartDocument.selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP);

        // This line of code handles a discrepancy between the schema of a chart definition
        // handed to a dashboard versus a ChartComponent schema. The top level node for the dashboard charts
        // is <chart>, whereas the ChartComponent expects <chart-attributes>.

        // TODO:
        // This discrepancy should be resolved when we have ONE chart solution.

        if (chartAttributes == null) {
            chartAttributes = chartDocument.selectSingleNode(ChartComponent.ALTERNATIVE_CHART_ATTRIBUTES_PROP);
        }
    }

    // Default chart attributes are in the component-definition section of the action definition.
    if (chartAttributes == null) {
        chartAttributes = getComponentDefinition(true).selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP);
    }

    // URL click-through attributes (useBaseURL, target) are only processed IF we
    // have an urlTemplate attribute
    if ((urlTemplate == null) || (urlTemplate.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE) != null) {
            urlTemplate = chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE).getText();
        }
    }

    // These parameters are replacement variables parsed into the
    // urlTemplate specifically when we have a URL that is a drill-through
    // link in a chart intended to drill down into the chart data.
    String parameterName = (String) getInputValue(ChartComponent.PARAMETER_NAME);
    if ((parameterName == null) || (parameterName.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME) != null) {
            parameterName = chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME).getText();
        }
    }

    // These parameters are replacement variables parsed into the
    // urlTemplate specifically when we have a URL that is a drill-through
    // link in a chart intended to drill down into the chart data.
    String outerParameterName = (String) getInputValue(ChartComponent.OUTER_PARAMETER_NAME);
    if ((outerParameterName == null) || (outerParameterName.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME) != null) {
            outerParameterName = chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME)
                    .getText();
        }
    }

    String chartType = chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME).getText();

    // --------------- This code allows inputs to override the chartAttributes
    // of width, height, and title
    Object widthObj = getInputValue(ChartDefinition.WIDTH_NODE_NAME);
    if (widthObj != null) {
        width = Integer.parseInt(widthObj.toString());
        if (width != -1) {
            if (chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME) == null) {
                ((Element) chartAttributes).addElement(ChartDefinition.WIDTH_NODE_NAME);
            }
            chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME).setText(Integer.toString(width));
        }
    }
    Object heightObj = getInputValue(ChartDefinition.HEIGHT_NODE_NAME);
    if (heightObj != null) {
        height = Integer.parseInt(heightObj.toString());
        if (height != -1) {
            if (chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME) == null) {
                ((Element) chartAttributes).addElement(ChartDefinition.HEIGHT_NODE_NAME);
            }
            chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME)
                    .setText(Integer.toString(height));
        }
    }
    Object titleObj = getInputValue(ChartDefinition.TITLE_NODE_NAME);
    if (titleObj != null) {
        if (chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME) == null) {
            ((Element) chartAttributes).addElement(ChartDefinition.TITLE_NODE_NAME);
        }
        chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME).setText(titleObj.toString());
    }
    // ----------------End of Override

    // ---------------Feed the Title and Subtitle information through the input substitution
    Node titleNode = chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME);
    if (titleNode != null) {
        String titleStr = titleNode.getText();
        if (titleStr != null) {
            title = titleStr;
            String newTitle = applyInputsToFormat(titleStr);
            titleNode.setText(newTitle);
        }
    }

    List subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);

    if ((subtitles == null) || (subtitles.isEmpty())) {
        Node subTitlesNode = chartAttributes.selectSingleNode(ChartDefinition.SUBTITLES_NODE_NAME);
        if (subTitlesNode != null) {
            subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);
        }
    } else {
        // log a deprecation warning for this property...
        getLogger().warn(Messages.getInstance().getString("CHART.WARN_DEPRECATED_CHILD", //$NON-NLS-1$
                ChartDefinition.SUBTITLE_NODE_NAME, ChartDefinition.SUBTITLES_NODE_NAME));
        getLogger().warn(Messages.getInstance().getString("CHART.WARN_PROPERTY_WILL_NOT_VALIDATE", //$NON-NLS-1$
                ChartDefinition.SUBTITLE_NODE_NAME));
    }

    if (subtitles != null) {
        for (Iterator iter = subtitles.iterator(); iter.hasNext();) {
            Node subtitleNode = (Node) iter.next();
            if (subtitleNode != null) {
                String subtitleStr = subtitleNode.getText();
                if (subtitleStr != null) {
                    String newSubtitle = applyInputsToFormat(subtitleStr);
                    subtitleNode.setText(newSubtitle);
                }
            }
        }
    }

    // ----------------End of Format

    // Determine if we are going to read the chart data set by row or by column
    boolean byRow = false;
    if (getInputStringValue(ChartComponent.BY_ROW_PROP) != null) {
        byRow = Boolean.valueOf(getInputStringValue(ChartComponent.BY_ROW_PROP)).booleanValue();
    }

    // TODO Figure out why these overrides are called here. Seems like we are doing the same thing we just did above,
    // but
    // could possibly step on the height and width values set previously.

    if (height == -1) {
        height = (int) getInputLongValue(
                ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.HEIGHT_NODE_NAME, 50); //$NON-NLS-1$
    }
    if (width == -1) {
        width = (int) getInputLongValue(
                ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.WIDTH_NODE_NAME, 100); //$NON-NLS-1$      
    }

    if (title.length() <= 0) {
        title = getInputStringValue(
                ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.TITLE_NODE_NAME); //$NON-NLS-1$
    }

    // Select the right dataset to use based on the chart type
    // Default to category dataset
    String datasetType = ChartDefinition.CATEGORY_DATASET_STR;
    boolean isStacked = false;
    Node datasetTypeNode = chartAttributes.selectSingleNode(ChartDefinition.DATASET_TYPE_NODE_NAME);
    if (datasetTypeNode != null) {
        datasetType = datasetTypeNode.getText();
    }
    Dataset dataDefinition = null;
    if (ChartDefinition.XY_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {
        dataDefinition = new XYSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.TIME_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {

        Node stackedNode = chartAttributes.selectSingleNode(ChartDefinition.STACKED_NODE_NAME);
        if (stackedNode != null) {
            isStacked = Boolean.valueOf(stackedNode.getText()).booleanValue();
        }
        if ((isStacked) && (ChartDefinition.AREA_CHART_STR.equalsIgnoreCase(chartType))) {
            dataDefinition = new TimeTableXYDatasetChartDefinition(data, byRow, chartAttributes, getSession());
        } else {
            dataDefinition = new TimeSeriesCollectionChartDefinition(data, byRow, chartAttributes,
                    getSession());
        }
    } else if (ChartDefinition.PIE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new PieDatasetChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.DIAL_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new DialWidgetDefinition(data, byRow, chartAttributes, width, height, getSession());
    } else if (ChartDefinition.BAR_LINE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new BarLineChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.BUBBLE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new XYZSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
    } else {
        dataDefinition = new CategoryDatasetChartDefinition(data, byRow, chartAttributes, getSession());
    }

    // Determine what we are sending back - Default to OUTPUT_PNG output
    // OUTPUT_PNG = the chart gets written to a file in .png format
    // OUTPUT_SVG = the chart gets written to a file in .svg (XML) format
    // OUTPUT_CHART = the chart in a byte stream gets stored as as an IContentItem
    // OUTPUT_PNG_BYTES = the chart gets sent as a byte stream in .png format

    int outputType = JFreeChartEngine.OUTPUT_PNG;

    if (getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP) != null) {
        if (ChartComponent.SVG_TYPE.equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_SVG;
        } else if (ChartComponent.CHART_TYPE
                .equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_CHART;
        } else if (ChartComponent.PNG_BYTES_TYPE
                .equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_PNG_BYTES;
        }
    }

    boolean keepTempFile = false;
    if (isDefinedInput(KEEP_TEMP_FILE_PROP)) {
        keepTempFile = getInputBooleanValue(KEEP_TEMP_FILE_PROP, false);
    }

    JFreeChart chart = null;

    switch (outputType) {

    /**************************** OUTPUT_PNG_BYTES *********************************************/
    case JFreeChartEngine.OUTPUT_PNG_BYTES:

        chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this); //$NON-NLS-1$

        // TODO Shouldn't the mime types and other strings here be constant somewhere? Where do we
        // put this type of general info ?

        String mimeType = "image/png"; //$NON-NLS-1$
        IContentItem contentItem = getOutputItem("chartdata", mimeType, ".png"); //$NON-NLS-1$ //$NON-NLS-2$
        contentItem.setMimeType(mimeType);
        try {

            OutputStream output = contentItem.getOutputStream(getActionName());
            ChartUtilities.writeChartAsPNG(output, chart, width, height);

        } catch (Exception e) {
            error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0004_CANT_CREATE_IMAGE"), e); //$NON-NLS-1$
            return false;
        }

        break;

    /**************************** OUTPUT_SVG && OUTPUT_PNG *************************************/
    case JFreeChartEngine.OUTPUT_SVG:
        // intentionally fall through to PNG

    case JFreeChartEngine.OUTPUT_PNG:

        // Don't include the map in a file if HTML_MAPPING_HTML is specified, as that
        // param sends the map back on the outputstream as a string
        boolean createMapFile = !isDefinedOutput(ChartComponent.HTML_MAPPING_HTML);
        boolean hasTemplate = urlTemplate != null && urlTemplate.length() > 0;

        File[] fileResults = createTempFile(outputType, hasTemplate, !keepTempFile);

        if (fileResults == null) {
            error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0003_CANT_CREATE_TEMP_FILES")); //$NON-NLS-1$
            return false;
        }

        String chartId = fileResults[ChartComponent.FILE_NAME].getName().substring(0,
                fileResults[ChartComponent.FILE_NAME].getName().indexOf('.'));
        String filePathWithoutExtension = ChartComponent.TEMP_DIRECTORY + chartId;
        PrintWriter printWriter = new PrintWriter(new StringWriter());
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

        JFreeChartEngine.saveChart(dataDefinition, title, "", filePathWithoutExtension, width, height, //$NON-NLS-1$
                outputType, printWriter, info, this);

        // Creating the image map
        boolean useBaseUrl = true;
        String urlTarget = "pentaho_popup"; //$NON-NLS-1$

        // Prepend the base url to the front of every drill through link
        if (chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG) != null) {
            Boolean booleanValue = new Boolean(
                    chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG).getText());
            useBaseUrl = booleanValue.booleanValue();
        }

        // What target for link? _parent, _blank, etc.
        if (chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG) != null) {
            urlTarget = chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG).getText();
        }

        String mapString = null;
        if (hasTemplate) {
            try {
                String mapId = fileResults[ChartComponent.MAP_NAME].getName().substring(0,
                        fileResults[ChartComponent.MAP_NAME].getName().indexOf('.'));
                mapString = ImageMapUtilities.getImageMap(mapId, info,
                        new StandardToolTipTagFragmentGenerator(),
                        new PentahoChartURLTagFragmentGenerator(urlTemplate, urlTarget, useBaseUrl,
                                dataDefinition, parameterName, outerParameterName));

                if (createMapFile) {
                    BufferedWriter out = new BufferedWriter(
                            new FileWriter(fileResults[ChartComponent.MAP_NAME]));
                    out.write(mapString);
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0001_CANT_WRITE_MAP", //$NON-NLS-1$
                        fileResults[ChartComponent.MAP_NAME].getPath()));
                return false;
            } catch (Exception e) {
                error(e.getLocalizedMessage(), e);
                return false;
            }

        }

        /*******************************************************************************************************
         * Legitimate outputs for the ChartComponent in an action sequence:
         * 
         * CHART_OUTPUT (chart-output) Stores the chart in the content repository as an IContentItem.
         * 
         * CHART_FILE_NAME_OUTPUT (chart-filename) Returns the name of the chart file, including the file extension
         * (with no path information) as a String.
         * 
         * HTML_MAPPING_OUTPUT (chart-mapping) Returns the name of the file that the map has been saved to, including
         * the file extension (with no path information) as a String. Will be empty if url-template is undefined
         * 
         * HTML_MAPPING_HTML (chart-map-html) Returns the chart image map HTML as a String. Will be empty if
         * url-template is undefined
         * 
         * BASE_URL_OUTPUT (base-url) Returns the web app's base URL (ie., http://localhost:8080/pentaho) as a String.
         * 
         * HTML_IMG_TAG (image-tag) Returns the HTML snippet including the image map, image (<IMG />) tag for the chart
         * image with src, width, height and usemap attributes defined. Usemap will not be included if url-template is
         * undefined.
         * 
         *******************************************************************************************************/

        // Now set the outputs
        Set outputs = getOutputNames();

        if ((outputs != null) && (outputs.size() > 0)) {

            Iterator iter = outputs.iterator();
            while (iter.hasNext()) {

                String outputName = (String) iter.next();
                String outputValue = null;

                if (outputName.equals(ChartComponent.CHART_FILE_NAME_OUTPUT)) {

                    outputValue = fileResults[ChartComponent.FILE_NAME].getName();

                } else if (outputName.equals(ChartComponent.HTML_MAPPING_OUTPUT)) {
                    if (hasTemplate) {
                        outputValue = fileResults[ChartComponent.MAP_NAME].getName();
                    }
                } else if (outputName.equals(ChartComponent.HTML_MAPPING_HTML)) {

                    outputValue = mapString;

                } else if (outputName.equals(ChartComponent.BASE_URL_OUTPUT)) {
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    outputValue = requestContext.getContextPath();

                } else if (outputName.equals(ChartComponent.CONTEXT_PATH_OUTPUT)) {
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    outputValue = requestContext.getContextPath();
                } else if (outputName.equals(ChartComponent.FULLY_QUALIFIED_SERVER_URL_OUTPUT)) {

                    IApplicationContext applicationContext = PentahoSystem.getApplicationContext();
                    if (applicationContext != null) {
                        outputValue = applicationContext.getFullyQualifiedServerURL();
                    } else {
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        outputValue = requestContext.getContextPath();
                    }
                } else if (outputName.equals(ChartComponent.HTML_IMG_TAG)) {

                    outputValue = hasTemplate ? mapString : ""; //$NON-NLS-1$

                    outputValue += "<img border=\"0\" "; //$NON-NLS-1$
                    outputValue += "width=\"" + width + "\" "; //$NON-NLS-1$//$NON-NLS-2$
                    outputValue += "height=\"" + height + "\" "; //$NON-NLS-1$//$NON-NLS-2$
                    if (hasTemplate) {
                        outputValue += "usemap=\"#" + fileResults[ChartComponent.MAP_NAME].getName().substring(
                                0, fileResults[ChartComponent.MAP_NAME].getName().indexOf('.')) + "\" "; //$NON-NLS-1$//$NON-NLS-2$
                    }
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    String contextPath = requestContext.getContextPath();
                    outputValue += "src=\"" + contextPath + "getImage?image=" //$NON-NLS-1$//$NON-NLS-2$
                            + fileResults[ChartComponent.FILE_NAME].getName() + "\"/>"; //$NON-NLS-1$

                }

                if (outputValue != null) {
                    setOutputValue(outputName, outputValue);
                }
            }
        }

        break;

    /************************** OUTPUT_CHART && DEFAULT *************************************/
    case JFreeChartEngine.OUTPUT_CHART:
        // intentionally fall through to default

    default:

        String chartName = ChartComponent.CHART_OUTPUT;
        if (isDefinedInput(ChartComponent.CHART_NAME_PROP)) {
            chartName = getInputStringValue(ChartComponent.CHART_NAME_PROP);
        }
        chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this); //$NON-NLS-1$
        setOutputValue(chartName, chart);

        break;
    }

    return true;
}

From source file:uk.ac.lkl.cram.ui.report.Report.java

private P createChart(JFreeChart chart, int width, int height) {
    P p = factory.createP();/*from  ww  w  .  ja  v  a2 s  .c o  m*/
    try {
        /* We don't want to create an intermediate file. So, we create a byte array output stream 
        /* Write chart as PNG to Output Stream */
        ByteArrayOutputStream chart_out = new ByteArrayOutputStream();
        ChartUtilities.writeChartAsPNG(chart_out, chart, width, height);
        chart_out.close();
        byte[] bytes = chart_out.toByteArray();
        BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
        Inline inline = imagePart.createImageInline(null, null, 0, 1, false);
        //Give the p a style
        PPr ppr = factory.createPPr();
        p.setPPr(ppr);
        PStyle pstyle = factory.createPPrBasePStyle();
        pstyle.setVal("NoSpacing");
        ppr.setPStyle(pstyle);
        // Now add the inline in w:p/w:r/w:drawing
        R run = factory.createR();
        p.getContent().add(run);
        org.docx4j.wml.Drawing drawing = factory.createDrawing();
        run.getContent().add(drawing);
        drawing.getAnchorOrInline().add(inline);
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Failed to create chart", ex);
    }
    return p;
}