Example usage for org.jfree.chart JFreeChart createBufferedImage

List of usage examples for org.jfree.chart JFreeChart createBufferedImage

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart createBufferedImage.

Prototype

public BufferedImage createBufferedImage(int width, int height) 

Source Link

Document

Creates and returns a buffered image into which the chart has been drawn.

Usage

From source file:org.ramadda.data.services.PointFormHandler.java

/**
 * _more_//from w ww.ja  v a  2  s.c o  m
 *
 * @param request _more_
 * @param outputType _more_
 * @param pointEntry _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public Result outputEntryWaveformImage(Request request, OutputType outputType, PointEntry pointEntry)
        throws Exception {

    int width = 300;
    int height = TIMESERIES_HEIGHT + 10;
    int pointIndex = request.get(ARG_POINTINDEX, 0);

    long numRecords = pointEntry.getNumRecords();
    if (pointIndex >= numRecords) {
        pointIndex = (int) (numRecords - 1);
    }
    PointRecord record = (PointRecord) pointEntry.getRecordFile().getRecord(pointIndex);
    String waveformName = request.getString(ARG_WAVEFORM_NAME, "");
    Waveform waveform = record.getWaveform(waveformName);
    boolean hasAltitude = waveform.hasAltitude();
    float[] values = waveform.getWaveform();
    double heightDiff = waveform.getAltitudeN() - waveform.getAltitude0();
    XYSeries series = new XYSeries("");
    //        System.err.println("idx: " + pointIndex + " alt:"
    //                           + waveform.getAltitude0() + " -- "
    //                           + waveform.getAltitudeN());
    //        record.print();
    for (int i = 0; i < values.length; i++) {
        double percent = i / (double) values.length;
        float b = values[i];
        if (hasAltitude) {
            double altitude = waveform.getAltitude0() + (heightDiff * percent);
            //                System.err.println(altitude +" " + b);
            series.add(altitude, b);
        } else {
            series.add(i, b);
        }
    }

    File f = getRepository().getStorageManager().getTmpFile(request, "waveform.png");
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = createWaveformChart(request, waveform, dataset);
    BufferedImage newImage = chart.createBufferedImage(width, height);
    ImageUtils.writeImageToFile(newImage, f);
    InputStream is = getStorageManager().getFileInputStream(f);

    return new Result("", is, "image/png");
}

From source file:org.cerberus.crud.service.impl.TestCaseExecutionwwwDetService.java

private BufferedImage bi(TimeSeriesCollection timeseriescollection, String xname, String name, int count) {
    BufferedImage bi = null;//from   w  w  w . j a va  2s  .  co m
    boolean fc = false;
    XYDataset xydataset = timeseriescollection;
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(name, xname, name, xydataset, true, true, false);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setDomainCrosshairVisible(true);
    xyplot.setRangeCrosshairVisible(false);
    XYItemRenderer xyitemrenderer = xyplot.getRenderer();
    if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
        Shape point = ShapeUtilities.createDiagonalCross(1, 1);
        String[] seriesColors = { "#FF0000", "#D7D6F6", "#0F07F3", "#EEFFBD", "#75C53E", "#FED7BA", "#FE6F01" };
        String[] seriesColors2 = { "#D7D6F6", "#0F07F3", "#EEFFBD", "#75C53E", "#FED7BA", "#FE6F01" };
        XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
        xylineandshaperenderer.setBaseShapesVisible(true);
        xylineandshaperenderer.setBaseShapesFilled(true);
        for (int a = 0; a < count; a++) {
            xylineandshaperenderer.setSeriesShape(a, point);
            xyitemrenderer.setSeriesStroke(a, new BasicStroke(1.0F));
            //TODO check this - fc is always false
            if (fc) {
                xylineandshaperenderer.setSeriesPaint(a, Color.decode(seriesColors[count - a - 1]));
            } else {
                xylineandshaperenderer.setSeriesPaint(a, Color.decode(seriesColors2[count - a - 1]));
            }
        }
    }
    DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
    dateaxis.setDateFormatOverride(new SimpleDateFormat("hh:mm"));
    bi = jfreechart.createBufferedImage(500, 270);
    return bi;
}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private File createImage(ApplicationGroup appgroup) throws IOException {

    Map<String, Double> costs = Maps.newHashMap();
    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    Interval interval = new Interval(end.minusWeeks(numWeeks), end);

    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appgroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }/*from www. j  a  v  a  2s .c  o  m*/
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        TagLists tagLists = new TagLists(accounts, regions, null, Lists.newArrayList(product), null, null,
                resourceGroups);
        Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Product, AggregateType.none,
                false);
        for (Tag tag : data.keySet()) {
            for (int week = 0; week < numWeeks; week++) {
                String key = tag + "|" + week;
                if (costs.containsKey(key))
                    costs.put(key, data.get(tag)[week] + costs.get(key));
                else
                    costs.put(key, data.get(tag)[week]);
            }
        }
    }

    boolean hasData = false;
    for (Map.Entry<String, Double> entry : costs.entrySet()) {
        if (!entry.getKey().contains("monitor") && entry.getValue() != null && entry.getValue() >= 0.1) {
            hasData = true;
            break;
        }
    }
    if (!hasData)
        return null;

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (Product product : products) {
        for (int week = 0; week < numWeeks; week++) {
            String weekStr = String.format("%s - %s week",
                    formatter.print(end.minusWeeks(numWeeks - week)).substring(5),
                    formatter.print(end.minusWeeks(numWeeks - week - 1)).substring(5));
            dataset.addValue(costs.get(product + "|" + week), product.name, weekStr);
        }
    }

    JFreeChart chart = ChartFactory.createBarChart3D(appgroup.getDisplayName() + " Weekly AWS Costs", "",
            "Costs", dataset, PlotOrientation.VERTICAL, true, false, false);
    CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
    BarRenderer3D renderer = (BarRenderer3D) categoryplot.getRenderer();
    renderer.setItemLabelAnchorOffset(10.0);
    TextTitle title = chart.getTitle();
    title.setFont(title.getFont().deriveFont((title.getFont().getSize() - 3)));

    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator() {
        public java.lang.String generateLabel(org.jfree.data.category.CategoryDataset dataset, int row,
                int column) {
            return costFormatter.format(dataset.getValue(row, column));
        }
    });
    renderer.setBaseItemLabelsVisible(true);
    renderer.setBasePositiveItemLabelPosition(
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));

    NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
    numberaxis.setNumberFormatOverride(costFormatter);

    BufferedImage image = chart.createBufferedImage(1200, 400);
    File outputfile = File.createTempFile("awscost", "png");
    ImageIO.write(image, "png", outputfile);

    return outputfile;
}

From source file:com.google.gwt.benchmarks.viewer.server.ReportImageServer.java

private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String uri = request.getRequestURI();
    String requestString = uri.split("test_images/")[1];
    String[] requestParams = requestString.split("/");

    String reportName = URLDecoder.decode(requestParams[0], charset);
    String categoryName = URLDecoder.decode(requestParams[1], charset);
    // String className = URLDecoder.decode(requestParams[2], charset);
    String testName = URLDecoder.decode(requestParams[3], charset);
    String agent = URLDecoder.decode(requestParams[4], charset);

    ReportDatabase db = ReportDatabase.getInstance();
    Report report = db.getReport(reportName);
    List<Category> categories = report.getCategories();
    Category category = getCategoryByName(categories, categoryName);
    List<Benchmark> benchmarks = category.getBenchmarks();
    Benchmark benchmark = getBenchmarkByName(benchmarks, testName);
    List<Result> results = benchmark.getResults();
    Result result = getResultsByAgent(results, agent);

    String title = BrowserInfo.getBrowser(agent);
    JFreeChart chart = createChart(testName, result, title, results);

    chart.getTitle().setFont(Font.decode("Verdana BOLD 12"));
    chart.setAntiAlias(true);//ww  w.jav a2 s.  co  m
    chart.setBorderVisible(true);
    chart.setBackgroundPaint(new Color(241, 241, 241));

    Plot plot = chart.getPlot();

    plot.setDrawingSupplier(getDrawingSupplier());
    plot.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 640, 480, new Color(200, 200, 200)));

    if (plot instanceof XYPlot) {
        XYPlot xyplot = (XYPlot) plot;
        Font labelFont = Font.decode("Verdana PLAIN");
        xyplot.getDomainAxis().setLabelFont(labelFont);
        xyplot.getRangeAxis().setLabelFont(labelFont);
        org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer();
        xyitemrenderer.setStroke(new BasicStroke(4));
        if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
            xylineandshaperenderer.setShapesVisible(true);
            xylineandshaperenderer.setShapesFilled(true);
        }
    }

    // Try to fit all the graphs into a 1024 window, with a min of 240 and a max
    // of 480
    final int graphWidth = Math.max(240, Math.min(480, (1024 - 10 * results.size()) / results.size()));
    BufferedImage img = chart.createBufferedImage(graphWidth, 240);
    byte[] image = EncoderUtil.encode(img, ImageFormat.PNG);

    // The images have unique URLs; might as well set them to never expire.
    response.setHeader("Cache-Control", "max-age=0");
    response.setHeader("Expires", "Fri, 2 Jan 1970 00:00:00 GMT");
    response.setContentType("image/png");
    response.setContentLength(image.length);

    OutputStream output = response.getOutputStream();
    output.write(image);
}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.ProjectResultsAction.java

/**
 * Action exportPDF pour StyleReport ou iText
 * //from w  ww. java2 s .  c  o m
 * @param mapping le actionMapping
 * @param form le form
 * @param request la request
 * @param response la response
 * @return l'actionForward
 * @throws ServletException exception pouvant etre levee
 */
public ActionForward exportPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException {
    Collection data = new ArrayList(1);
    ProjectSummaryForm theForm = (ProjectSummaryForm) form;
    data.add(theForm);
    try {
        HashMap parameters = new HashMap();
        // L'image du kiviat
        parameters.put("kiviat", (java.awt.Image) request.getSession().getAttribute("kiviatChart"));
        // L'image du scatterplot
        JFreeChart bubbleChart = new TopAction().getBubbleChart(request);
        parameters.put("scatterplot",
                bubbleChart.createBufferedImage(BubbleMaker.DEFAULT_WIDTH, BubbleMaker.DEFAULT_HEIGHT));
        // Le nom de l'utilisateur
        LogonBean logon = (LogonBean) request.getSession().getAttribute(WConstants.USER_KEY);
        parameters.put("userName", logon.getMatricule());
        // Pour chaque facteur, on rcupre la liste des critres et pratiques associs
        Collection factors = theForm.getFactors().getFactors();
        // Obtention des audits courants
        List auditsDTO = ActionUtils.getCurrentAuditsAsDTO(request);
        ComponentDTO project = new ComponentDTO();
        project.setID(Long.parseLong(theForm.getProjectId()));
        HashMap factorsResults = new HashMap();
        Map practicesResults = new HashMap();
        for (Iterator it = factors.iterator(); it.hasNext();) {
            ProjectFactorForm factor = (ProjectFactorForm) it.next();
            FactorRuleDTO factorRule = getFactorRule(factor.getId());
            ResultListForm criteria = getCriteriaList(factorRule, auditsDTO, project);
            factorsResults.put(new Long(factor.getId()), criteria.getList());
        }
        // Les critres associs aux facteurs
        parameters.put("factorsResults", factorsResults);
        // Les pratiques associes aux critres
        parameters.put("practicesResults", practicesResults.values());
        PDFDataJasperReports pdfData = new PDFDataJasperReports(request.getLocale(), getResources(request),
                data, "/org/squale/squaleweb/resources/jasperreport/ProjectSummary.jasper", false, parameters);
        PDFFactory.generatePDFToHTTPResponse(pdfData, response, "", PDFEngine.JASPERREPORTS);
    } catch (Exception e) {
        throw new ServletException(e);
    }
    return null;
}

From source file:weka.gui.beans.JFreeChartOffscreenChartRenderer.java

/**
 * Render histogram(s) (numeric attribute) or bar chart (nominal attribute).
 * Some implementations may not be able to render more than one histogram/bar
 * on the same chart - the implementation can either throw an exception or
 * just process the first series in this case.
 * /*from  w  ww . j ava  2s .  c om*/
 * @param width the width of the resulting chart in pixels
 * @param height the height of the resulting chart in pixels
 * @param series a list of Instances - one for each series to be plotted
 * @param attsToPlot the attribute to plot corresponding to the Instances in
 *          the series list
 * @param optionalArgs optional arguments to the renderer (may be null)
 * 
 * @return a BufferedImage containing the chart
 * @throws Exception if there is a problem rendering the chart
 */
public BufferedImage renderHistogram(int width, int height, List<Instances> series, String attToPlot,
        List<String> additionalArgs) throws Exception {

    String plotTitle = "Bar Chart";
    String userTitle = getOption(additionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;
    String colorAtt = getOption(additionalArgs, "-color");
    String pareto = getOption(additionalArgs, "-pareto");

    boolean doPareto = false;
    if (pareto != null && pareto.length() == 0 && series.size() == 1) {
        doPareto = true;
    }

    if (series.size() == 1 && colorAtt != null && colorAtt.length() > 0) {
        int colIndex = getIndexOfAttribute(series.get(0), colorAtt);

        if (colIndex >= 0 && series.get(0).attribute(colIndex).isNominal() && !doPareto) {
            // split single series out into multiple instances objects - one
            // per class
            series = splitToClasses(series.get(0), colIndex);
            for (Instances insts : series) {
                insts.setClassIndex(colIndex);
            }
        }
    }

    Instances masterInstances = series.get(0);
    int attIndex = getIndexOfAttribute(masterInstances, attToPlot);
    if (attIndex < 0) {
        attIndex = 0;
    }

    if (!(series.get(0).attribute(attIndex).isNominal()
            || series.get(0).attribute(attIndex).isRelationValued())) {
        doPareto = false;
    }

    // Do a pareto chart
    if (doPareto) {
        final DefaultKeyedValues data = new DefaultKeyedValues();
        AttributeStats attStats = masterInstances.attributeStats(attIndex);
        double[] attValFreqs = attStats.nominalWeights;
        for (int i = 0; i < attValFreqs.length; i++) {
            Number freq = new Double(attValFreqs[i]);
            data.addValue(masterInstances.attribute(attIndex).value(i), freq);
        }

        data.sortByValues(SortOrder.DESCENDING);
        final KeyedValues cumulative = DataUtilities.getCumulativePercentages(data);
        final CategoryDataset dataset = DatasetUtilities
                .createCategoryDataset(masterInstances.attribute(attIndex).name(), data);

        final JFreeChart chart = ChartFactory.createBarChart(plotTitle,
                masterInstances.attribute(attIndex).name(), "Fequency/weight mass", dataset,
                PlotOrientation.VERTICAL, true, false, false);

        final CategoryPlot plot = chart.getCategoryPlot();

        final CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.02);
        domainAxis.setUpperMargin(0.02);

        LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
        CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative", cumulative);
        final NumberAxis axis2 = new NumberAxis("Percent");
        axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
        // plot.
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        chart.setBackgroundPaint(java.awt.Color.white);
        BufferedImage image = chart.createBufferedImage(width, height);
        return image;
    }

    boolean seriesAreClasses = false;
    int classIndex = masterInstances.classIndex();

    if (classIndex >= 0 && !masterInstances.attribute(classIndex).isNumeric()
            && !masterInstances.attribute(classIndex).isRelationValued()
            && masterInstances.attributeStats(classIndex).distinctCount == 1) {
        // series correspond to class labels (assume that subsequent series only
        // contain instances of one class)...
        seriesAreClasses = true;
    }

    // bar chart for a nominal attribute
    if (masterInstances.attribute(attIndex).isNominal() || masterInstances.attribute(attIndex).isString()) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        // do the master series
        String masterSeriesTitle = masterInstances.relationName();
        if (seriesAreClasses) {
            for (int i = 0; i < masterInstances.numInstances(); i++) {
                Instance current = masterInstances.instance(i);
                if (!current.isMissing(classIndex)) {
                    masterSeriesTitle = current.stringValue(classIndex);
                    break;
                }
            }
        }

        AttributeStats attStats = masterInstances.attributeStats(attIndex);
        double[] attValFreqs = attStats.nominalWeights;
        for (int i = 0; i < attValFreqs.length; i++) {
            Number freq = new Double(attValFreqs[i]);
            dataset.addValue(freq, masterSeriesTitle, masterInstances.attribute(attIndex).value(i));
        }

        // any subsequent series
        for (int i = 1; i < series.size(); i++) {
            Instances nextSeries = series.get(i);

            String seriesTitle = nextSeries.relationName();

            if (seriesAreClasses) {
                for (int j = 0; j < nextSeries.numInstances(); j++) {
                    Instance current = nextSeries.instance(j);
                    if (!current.isMissing(classIndex)) {
                        seriesTitle = current.stringValue(classIndex);
                        break;
                    }
                }

                attStats = nextSeries.attributeStats(attIndex);
                attValFreqs = attStats.nominalWeights;
                for (int j = 0; j < attValFreqs.length; j++) {
                    Number freq = new Double(attValFreqs[j]);
                    dataset.addValue(freq, seriesTitle, nextSeries.attribute(attIndex).value(j));
                }
            }
        }

        JFreeChart chart = null;

        if (series.size() == 1) {
            chart = ChartFactory.createBarChart(plotTitle, masterInstances.attribute(attIndex).name(),
                    "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false);
        } else {
            chart = ChartFactory.createStackedBarChart(plotTitle, masterInstances.attribute(attIndex).name(),
                    "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false);
        }

        chart.setBackgroundPaint(java.awt.Color.white);
        BufferedImage image = chart.createBufferedImage(width, height);
        return image;

    } else {
        // histogram for numeric attributes
        HistogramDataset dataset = new HistogramDataset();

        // combine all series in order to get overall std dev, and range
        Instances temp = new Instances(masterInstances);
        for (int i = 1; i < series.size(); i++) {
            Instances additional = series.get(i);
            for (Instance tempI : additional) {
                temp.add(tempI);
            }
        }

        AttributeStats stats = temp.attributeStats(attIndex);
        Stats numericStats = stats.numericStats;
        double intervalWidth = 3.49 * numericStats.stdDev * StrictMath.pow(temp.numInstances(), (-1.0 / 3.0));
        double range = numericStats.max - numericStats.min;
        int numBins = StrictMath.max(1, (int) StrictMath.round(range / intervalWidth));

        // do the master series
        String masterSeriesTitle = masterInstances.relationName();
        if (seriesAreClasses) {
            for (int i = 0; i < masterInstances.numInstances(); i++) {
                Instance current = masterInstances.instance(i);
                if (!current.isMissing(current.classAttribute())) {
                    masterSeriesTitle = current.stringValue(current.classAttribute());
                    break;
                }
            }
        }

        // have to set min, max and num bins (using heuristic from AttSummPanel).
        // Make sure
        // to set series length to num instances - num missing values for att
        stats = masterInstances.attributeStats(attIndex);
        /*
         * numericStats = stats.numericStats; //numericStats.calculateDerived();
         * intervalWidth = StrictMath.max(1, 3.49 * numericStats.stdDev *
         * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0)));
         */

        double[] seriesVals = new double[masterInstances.numInstances() - stats.missingCount];
        int count = 0;
        for (int i = 0; i < masterInstances.numInstances(); i++) {
            Instance current = masterInstances.instance(i);
            if (!current.isMissing(attIndex)) {
                seriesVals[count++] = current.value(attIndex);
            }
        }

        dataset.addSeries(masterSeriesTitle, seriesVals, numBins, numericStats.min, numericStats.max);

        // any subsequent series
        for (int i = 1; i < series.size(); i++) {
            Instances nextSeries = series.get(i);

            String seriesTitle = nextSeries.relationName();

            if (seriesAreClasses) {
                for (int j = 0; j < nextSeries.numInstances(); j++) {
                    Instance current = nextSeries.instance(j);
                    if (!current.isMissing(nextSeries.classAttribute())) {
                        seriesTitle = current.stringValue(nextSeries.classAttribute());
                        break;
                    }
                }
            }

            stats = nextSeries.attributeStats(attIndex);
            /*
             * numericStats = stats.numericStats; //
             * numericStats.calculateDerived(); intervalWidth = StrictMath.max(1,
             * 3.49 * numericStats.stdDev *
             * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0))); range =
             * numericStats.max - numericStats.min; numBins = StrictMath.max(1,
             * (int) StrictMath.round(range / intervalWidth));
             */
            seriesVals = new double[nextSeries.numInstances() - stats.missingCount];
            count = 0;
            for (int j = 0; j < nextSeries.numInstances(); j++) {
                Instance current = nextSeries.instance(j);
                if (!current.isMissing(attIndex)) {
                    seriesVals[count++] = current.value(attIndex);
                }
            }

            dataset.addSeries(seriesTitle, seriesVals, numBins, numericStats.min, numericStats.max);
        }

        JFreeChart chart = ChartFactory.createHistogram(plotTitle, masterInstances.attribute(attIndex).name(),
                null, dataset, PlotOrientation.VERTICAL, true, false, false);

        // chart.setBackgroundPaint(java.awt.Color.white);
        XYPlot xyplot = (XYPlot) chart.getPlot();
        xyplot.setForegroundAlpha(0.50F);
        XYBarRenderer xybarrenderer = (XYBarRenderer) xyplot.getRenderer();
        xybarrenderer.setDrawBarOutline(false);
        xybarrenderer.setShadowVisible(false);

        BufferedImage image = chart.createBufferedImage(width, height);
        return image;
    }
}

From source file:org.pentaho.aggdes.ui.form.controller.AggListController.java

public void changeInAggregates() {

    // set dirty bit for workspace
    workspace.setWorkspaceUpToDate(false);

    // set the dirty bit for the schema publishing functionality

    if (getConnectionModel().getSchema() != null) {
        getConnectionModel().setSchemaUpToDate(false);
    }//from  w  w  w .jav a 2  s .c om

    // configure summary model and chart values

    int totalAggregatesSelected = 0;
    double totalRows = 0;
    double totalSpace = 0;
    double totalLoadTime = 0;

    //Fire event
    AggListController.this.firePropertyChange("aggList", null, aggList);

    List<Aggregate> algoAggregates = new ArrayList<Aggregate>();
    for (UIAggregate aggregate : getAggList()) {
        if (aggregate.getEnabled()) {
            totalAggregatesSelected++;
            totalRows += aggregate.estimateRowCount();
            totalSpace += aggregate.estimateSpace();
            algoAggregates
                    .add(algorithm.createAggregate(connectionModel.getSchema(), aggregate.getAttributes()));
        }
    }

    double[] xs = new double[algoAggregates.size()];
    double[] startx = new double[algoAggregates.size()];
    double[] endx = new double[algoAggregates.size()];

    double[] ys = new double[algoAggregates.size()];
    double[] starty = new double[algoAggregates.size()];
    double[] endy = new double[algoAggregates.size()];

    XYSeries series1 = new XYSeries("CostBenefit");
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series1);
    DefaultIntervalXYDataset datasetxy = new DefaultIntervalXYDataset();

    if (connectionModel.getSchema() != null) {

        Map<Parameter, Object> algorithmParams = ArgumentUtils.validateParameters(algorithm,
                algorithmUiExtension.getAlgorithmParameters());
        List<Algorithm.CostBenefit> costBenefit = algorithm.computeAggregateCosts(connectionModel.getSchema(),
                algorithmParams, algoAggregates);

        double totalbenefit = 0;
        double x = 0;
        int count = 0;
        for (Algorithm.CostBenefit cb : costBenefit) {
            Aggregate agg = algoAggregates.get(count);
            double estimateSpace = agg.estimateSpace();
            double hx = estimateSpace / 2;
            totalLoadTime += cb.getLoadTime();
            totalbenefit += cb.getSavedQueryRowCount();
            series1.add(x + hx, totalbenefit);

            xs[count] = x + hx;
            startx[count] = x;
            x += estimateSpace;
            endx[count] = x;

            ys[count] = totalbenefit;
            starty[count] = 0;
            endy[count] = 0;

            count++;
        }

        // update summary table

        aggregateSummaryModel.setSelectedAggregateCount(format.format(totalAggregatesSelected));
        aggregateSummaryModel.setSelectedAggregateRows(format.format(totalRows));
        aggregateSummaryModel.setSelectedAggregateSpace(format.format(totalSpace) + " bytes");
        aggregateSummaryModel.setSelectedAggregateLoadTime(format.format(totalLoadTime));
    } else {
        aggregateSummaryModel.setSelectedAggregateCount("");
        aggregateSummaryModel.setSelectedAggregateRows("");
        aggregateSummaryModel.setSelectedAggregateSpace("");
        aggregateSummaryModel.setSelectedAggregateLoadTime("");

    }
    // render cost benefit chart

    double[][] data = new double[][] { xs, startx, endx, ys, starty, endy };
    datasetxy.addSeries("", data);

    JFreeChart chart = ChartFactory.createXYBarChart("", // chart title
            "Cost", // x axis label
            false, "Benefit", // y axis label
            datasetxy, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            false, // tooltips?
            false // URLs?
    );

    ((XYPlot) chart.getPlot()).getDomainAxis().setTickLabelsVisible(false);
    ((XYPlot) chart.getPlot()).getRangeAxis().setTickLabelsVisible(false);
    ((XYPlot) chart.getPlot()).setDataset(1, dataset);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();

    chart.setBackgroundPaint(
            new Color(Integer.parseInt(Messages.getString("chart_background_color").toUpperCase(), 16)));

    renderer.setSeriesPaint(0,
            new Color(Integer.parseInt(Messages.getString("chart_line_color").toUpperCase(), 16)));

    ((XYPlot) chart.getPlot()).getRenderer(0).setSeriesPaint(0,
            new Color(Integer.parseInt(Messages.getString("chart_bar_color").toUpperCase(), 16)));

    ((XYPlot) chart.getPlot()).setRenderer(1, renderer);
    ((XYPlot) chart.getPlot()).setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    XulImage image = (XulImage) document.getElementById("chart");
    image.setSrc(chart.createBufferedImage(309, 168));
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] createWeeklyLoginChart(int width, int height) {
    IntervalXYDataset dataset1 = getWeeklyLoginsDataSet();
    IntervalXYDataset dataset2 = getWeeklySiteUserDataSet();

    if ((dataset1 == null) || (dataset2 == null)) {
        return generateNoDataChart(width, height);
    }//from   w  ww  . j a  v  a2 s  .com

    // create plot ...
    XYItemRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
    renderer1.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesPaint(0, Color.RED);
    renderer1.setSeriesPaint(0, Color.BLUE);

    DateAxis domainAxis = new DateAxis("");
    domainAxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 7, new SimpleDateFormat("yyyy-MM-dd")));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.START);
    domainAxis.setVerticalTickLabels(true);
    domainAxis.setLowerMargin(0.01);
    domainAxis.setUpperMargin(0.01);

    NumberAxis rangeAxis = new NumberAxis("count");
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYPlot plot1 = new XYPlot(dataset1, null, rangeAxis, renderer1);
    plot1.setBackgroundPaint(Color.lightGray);
    plot1.setDomainGridlinePaint(Color.white);
    plot1.setRangeGridlinePaint(Color.white);

    // add a second dataset and renderer...
    XYItemRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
    renderer2.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesStroke(2, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesPaint(0, Color.GREEN);
    renderer2.setSeriesPaint(1, Color.BLACK);
    renderer2.setSeriesPaint(2, Color.CYAN);

    rangeAxis = new NumberAxis("count");
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYPlot plot2 = new XYPlot(dataset2, null, rangeAxis, renderer2);
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);

    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
    cplot.add(plot1, 3);
    cplot.add(plot2, 2);
    cplot.setGap(8.0);
    cplot.setDomainGridlinePaint(Color.white);
    cplot.setDomainGridlinesVisible(true);

    // return a new chart containing the overlaid plot...
    JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
    LegendTitle legend = new LegendTitle(cplot);
    chart.addSubtitle(legend);

    // set background
    chart.setBackgroundPaint(parseColor(statsManager.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set anti alias
    chart.setAntiAlias(true);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] createDailyLoginChart(int width, int height) {
    IntervalXYDataset dataset1 = getDailyLoginsDataSet();
    IntervalXYDataset dataset2 = getDailySiteUserDataSet();

    if ((dataset1 == null) || (dataset2 == null)) {
        return generateNoDataChart(width, height);
    }/*from  w  ww .  j  a  v  a 2s. c  o m*/

    // create plot ...
    XYItemRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
    renderer1.setSeriesPaint(0, Color.RED);
    renderer1.setSeriesPaint(1, Color.BLUE);
    renderer1.setSeriesPaint(2, Color.RED);
    renderer1.setSeriesPaint(3, Color.BLUE);
    renderer1.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    BasicStroke dashLineStroke = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 0,
            new float[] { 4 }, 0);
    renderer1.setSeriesStroke(2, dashLineStroke);
    renderer1.setSeriesStroke(3, dashLineStroke);

    DateAxis domainAxis = new DateAxis("");
    domainAxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 7, new SimpleDateFormat("yyyy-MM-dd")));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.START);
    domainAxis.setVerticalTickLabels(true);
    domainAxis.setLowerMargin(0.01);
    domainAxis.setUpperMargin(0.01);

    NumberAxis rangeAxis = new NumberAxis("count");
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYPlot plot1 = new XYPlot(dataset1, null, rangeAxis, renderer1);
    plot1.setBackgroundPaint(Color.lightGray);
    plot1.setDomainGridlinePaint(Color.white);
    plot1.setRangeGridlinePaint(Color.white);

    // add a second dataset and renderer...
    XYItemRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
    renderer2.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesStroke(2, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesPaint(0, Color.GREEN);
    renderer2.setSeriesPaint(1, Color.BLACK);
    renderer2.setSeriesPaint(2, Color.CYAN);

    rangeAxis = new NumberAxis("count");
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYPlot plot2 = new XYPlot(dataset2, null, rangeAxis, renderer2);
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);

    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
    cplot.add(plot1, 3);
    cplot.add(plot2, 2);
    cplot.setGap(8.0);
    cplot.setDomainGridlinePaint(Color.white);
    cplot.setDomainGridlinesVisible(true);

    // return a new chart containing the overlaid plot...
    JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
    LegendTitle legend = new LegendTitle(cplot);
    chart.addSubtitle(legend);

    // set background
    chart.setBackgroundPaint(parseColor(statsManager.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set anti alias
    chart.setAntiAlias(true);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java

private byte[] createMonthlyLoginChart(int width, int height) {
    IntervalXYDataset dataset1 = getMonthlyLoginsDataSet();
    IntervalXYDataset dataset3 = getMonthlySiteUserDataSet();

    if ((dataset1 == null) || (dataset3 == null)) {
        return generateNoDataChart(width, height);
    }/*from  w w  w  .  j a  v a  2s . co m*/

    // create plot ...
    XYItemRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
    renderer1.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesPaint(0, Color.RED);

    DateAxis domainAxis = new DateAxis("");
    domainAxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1, new SimpleDateFormat("yyyy-MM")));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.START);
    domainAxis.setVerticalTickLabels(true);
    domainAxis.setLowerMargin(0.01);
    domainAxis.setUpperMargin(0.01);

    NumberAxis axis1 = new NumberAxis("Total Logins");
    axis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    axis1.setLabelPaint(Color.RED);
    axis1.setTickLabelPaint(Color.RED);

    XYPlot plot1 = new XYPlot(dataset1, null, axis1, renderer1);
    plot1.setBackgroundPaint(Color.lightGray);
    plot1.setDomainGridlinePaint(Color.white);
    plot1.setRangeGridlinePaint(Color.white);

    // AXIS 2
    /*
    NumberAxis axis2 = new NumberAxis("Total Unique Users");
    axis2.setStandardTickUnits (NumberAxis.createIntegerTickUnits ());
    axis2.setLabelPaint(Color.BLUE);
    axis2.setTickLabelPaint(Color.BLUE);
    plot1.setRangeAxis(1, axis2);
            
    plot1.setDataset(1, dataset2);
    plot1.mapDatasetToRangeAxis(1, 1);
    XYItemRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
    renderer2.setSeriesStroke(0, new BasicStroke(2.0f, 
        BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesPaint (0, Color.BLUE);
    plot1.setRenderer(1, renderer2);
    */

    // add a third dataset and renderer...
    XYItemRenderer renderer3 = new XYLineAndShapeRenderer(true, false);
    renderer3.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer3.setSeriesStroke(1, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer3.setSeriesStroke(2, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer3.setSeriesPaint(0, Color.GREEN);
    renderer3.setSeriesPaint(1, Color.BLACK);
    renderer3.setSeriesPaint(2, Color.CYAN);

    axis1 = new NumberAxis("count");
    axis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYPlot plot2 = new XYPlot(dataset3, null, axis1, renderer3);
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);

    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
    cplot.add(plot1, 3);
    cplot.add(plot2, 2);
    cplot.setGap(8.0);
    cplot.setDomainGridlinePaint(Color.white);
    cplot.setDomainGridlinesVisible(true);

    // return a new chart containing the overlaid plot...
    JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
    LegendTitle legend = new LegendTitle(cplot);
    chart.addSubtitle(legend);

    // set background
    chart.setBackgroundPaint(parseColor(statsManager.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set anti alias
    chart.setAntiAlias(true);

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        log.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}