Example usage for org.jfree.data.category CategoryDataset getColumnKey

List of usage examples for org.jfree.data.category CategoryDataset getColumnKey

Introduction

In this page you can find the example usage for org.jfree.data.category CategoryDataset getColumnKey.

Prototype

public Comparable getColumnKey(int column);

Source Link

Document

Returns the column key for a given index.

Usage

From source file:gov.nih.nci.ispy.ui.graphing.chart.plot.ISPYCategoricalCorrelationPlot.java

private void createChart() {

    String title = "Categorical Plot";

    CategoryDataset chartData = createChartData();

    CategoryAxis domainAxis = new CategoryAxis(null);
    NumberAxis rangeAxis = new NumberAxis(yLabel);
    //BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();

    BoxAndWhiskerCoinPlotRenderer renderer = new BoxAndWhiskerCoinPlotRenderer();
    renderer.setDisplayAllOutliers(true);
    CategoryPlot plot = new CategoryPlot(chartData, domainAxis, rangeAxis, renderer);

    domainAxis.setCategoryLabelPositions(
            CategoryLabelPositions.createUpRotationLabelPositions(45.0 * Math.PI / 180.0));
    catCorrChart = new JFreeChart(title, plot);
    catCorrChart.removeLegend();/*from  w  w  w  . j av a  2 s.  c o  m*/
    //renderer.setFillBox(false);
    String cat = (String) chartData.getColumnKey(0);

    //renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
    renderer.setToolTipGenerator(new CategoryToolTipGenerator() {
        public String generateToolTip(CategoryDataset dataset, int series, int item) {
            String tt = "";
            NumberFormat formatter = new DecimalFormat(".####");
            String key = "";
            //String s = formatter.format(-1234.567);  // -001235
            if (dataset instanceof DefaultBoxAndWhiskerCategoryDataset) {
                DefaultBoxAndWhiskerCategoryDataset ds = (DefaultBoxAndWhiskerCategoryDataset) dataset;
                try {
                    String med = formatter.format(ds.getMedianValue(series, item));
                    tt += "Median: " + med + "<br/>";
                    tt += "Mean: " + formatter.format(ds.getMeanValue(series, item)) + "<br/>";
                    tt += "Q1: " + formatter.format(ds.getQ1Value(series, item)) + "<br/>";
                    tt += "Q3: " + formatter.format(ds.getQ3Value(series, item)) + "<br/>";
                    tt += "Max: "
                            + formatter.format(
                                    FaroutOutlierBoxAndWhiskerCalculator.getMaxFaroutOutlier(ds, series, item))
                            + "<br/>";
                    tt += "Min: "
                            + formatter.format(
                                    FaroutOutlierBoxAndWhiskerCalculator.getMinFaroutOutlier(ds, series, item))
                            + "<br/>";
                    //tt += "<br/><br/>Please click on the box and whisker to view a plot for this reporter.<br/>";
                    //tt += "X: " + ds.getValue(series, item).toString()+"<br/>";
                    //tt += "<br/><a href=\\\'#\\\' id=\\\'"+ds.getRowKeys().get(series)+"\\\' onclick=\\\'alert(this.id);return false;\\\'>"+ds.getRowKeys().get(series)+" plot</a><br/><br/>";
                    key = ds.getRowKeys().get(series).toString();
                } catch (Exception e) {
                }
            }

            return tt;
        }

    });

    //        renderer.setToolTipGenerator(new CategoryToolTipGenerator() {
    //           
    //         public String generateToolTip(CategoryDataset dataset,int series, int item) {
    //            String tt="";
    //            NumberFormat formatter = new DecimalFormat(".####");
    //            String key = "";
    //             //String s = formatter.format(-1234.567);  // -001235
    //            StringBuffer sb = new StringBuffer();
    //             if(dataset instanceof DefaultBoxAndWhiskerCategoryDataset){
    //                DefaultBoxAndWhiskerCategoryDataset ds = (DefaultBoxAndWhiskerCategoryDataset)dataset;
    //                try   {
    //                   
    //                   String str;
    //                   str = (String) ds.getColumnKey(item);
    //                   sb.append(str).append(" N=");
    //                   BoxAndWhiskerItem bwitem = ds.getItem(series,item);
    //                   
    //                  str = formatter.format(ds.getMedianValue(series, item));
    //                  sb.append("Median: ").append(str);
    //                  str = formatter.format(ds.getMeanValue(series, item));
    //                  sb.append(" Mean: ").append(str);
    //                  str = formatter.format(ds.getMinRegularValue(series, item));
    //                  sb.append(" Min: ").append(str);
    //                  str = formatter.format(ds.getMaxRegularValue(series, item));
    //                  sb.append(" Max: ").append(str);
    //                  str = formatter.format(ds.getQ1Value(series, item));
    //                  sb.append(" Q1: ").append(str);   
    //                  str = formatter.format(ds.getQ3Value(series, item));
    //                  sb.append(" Q3: ").append(str);
    //                  
    //                }
    //                catch(Exception e) {}
    //             }
    //             
    //            return sb.toString();
    //            
    //         }
    //
    //      });

    plot.setNoDataMessage(null);
}

From source file:com.att.aro.ui.view.waterfalltab.WaterfallPanel.java

/**
 * Refreshes the waterfall display with the specified analysis data
 * @param Analyzed data from aro core./*  w  ww .  j a v a  2 s.c  o  m*/
 */
public void refresh(AROTraceData aModel) {

    this.popup.refresh(null, 0);
    this.popup.setVisible(false);

    double range = DEFAULT_TIMELINE;

    // Create sorted list of request/response pairs
    List<WaterfallCategory> categoryList = new ArrayList<WaterfallCategory>();

    if (aModel != null && aModel.getAnalyzerResult() != null) {
        this.traceDuration = aModel.getAnalyzerResult().getTraceresult().getTraceDuration();

        // add 20% to make sure labels close to the right edge of the screen are visible
        this.traceDuration *= 1.2;
        range = Math.min(this.traceDuration, DEFAULT_TIMELINE);

        for (Session tcpSession : aModel.getAnalyzerResult().getSessionlist()) {
            Session thisSession = tcpSession;
            if (!tcpSession.isUDP()) {
                for (HttpRequestResponseInfo reqResInfo : tcpSession.getRequestResponseInfo()) {
                    if (reqResInfo.getDirection() == HttpDirection.REQUEST
                            && reqResInfo.getWaterfallInfos() != null) {
                        categoryList.add(new WaterfallCategory(reqResInfo, thisSession));
                    }
                }

            }

        }

        // Sort and set index
        Collections.sort(categoryList);
        int index = 0;
        for (WaterfallCategory wCategory : categoryList) {
            wCategory.setIndex(++index);
        }

    }

    // Horizontal scroll bar used to scroll through trace duration
    JScrollBar hScrollBar = getHorizontalScroll();
    hScrollBar.setMaximum((int) Math.ceil(this.traceDuration));

    // Set the visible time range
    setTimeRange(0, range);

    CategoryAxis cAxis = getCategoryAxis();
    cAxis.clearCategoryLabelToolTips();

    // Build the dataset
    DefaultCategoryDataset underlying = new DefaultCategoryDataset();
    for (WaterfallCategory wfc : categoryList) {
        RequestResponseTimeline rrTimeLine = wfc.getReqResp().getWaterfallInfos();

        underlying.addValue(rrTimeLine.getStartTime(), Waterfall.BEFORE, wfc);
        underlying.addValue(rrTimeLine.getDnsLookupDuration(), Waterfall.DNS_LOOKUP, wfc);
        underlying.addValue(rrTimeLine.getInitialConnDuration(), Waterfall.INITIAL_CONNECTION, wfc);
        underlying.addValue(rrTimeLine.getSslNegotiationDuration(), Waterfall.SSL_NEGOTIATION, wfc);
        underlying.addValue(rrTimeLine.getRequestDuration(), Waterfall.REQUEST_TIME, wfc);
        underlying.addValue(rrTimeLine.getTimeToFirstByte(), Waterfall.TIME_TO_FIRST_BYTE, wfc);
        underlying.addValue(rrTimeLine.getContentDownloadDuration(), Waterfall.CONTENT_DOWNLOAD, wfc);
        underlying.addValue(null, Waterfall.HTTP_3XX_REDIRECTION, wfc);
        underlying.addValue(null, Waterfall.HTTP_4XX_CLIENTERROR, wfc);

        int code = wfc.getReqResp().getAssocReqResp().getStatusCode();
        double endTime = this.traceDuration - rrTimeLine.getStartTime() - rrTimeLine.getTotalTime();
        if (code >= 300 && code < 400) {
            underlying.addValue(endTime, Waterfall.AFTER_3XX, wfc);
        } else if (code >= 400) {
            underlying.addValue(endTime, Waterfall.AFTER_4XX, wfc);
        } else {
            underlying.addValue(endTime, Waterfall.AFTER, wfc);
        }

        cAxis.addCategoryLabelToolTip(wfc, wfc.getTooltip());
    }

    // Vertical scroll bar is used to scroll through data
    JScrollBar vScrollBar = getVerticalScroll();
    int count = underlying.getColumnCount();
    vScrollBar.setValue(0);
    vScrollBar.setMaximum(count);
    vScrollBar.setVisibleAmount(count > 0 ? this.dataset.getMaximumCategoryCount() - 1 / count : 1);

    // Add the dataset to the plot
    CategoryPlot plot = getChartPanel().getChart().getCategoryPlot();
    this.dataset = new SlidingCategoryDataset(underlying, 0, CATEGORY_MAX_COUNT);
    plot.setDataset(this.dataset);

    // Place proper colors on renderer for waterfall states
    final CategoryItemRenderer renderer = plot.getRenderer();
    for (Object obj : underlying.getRowKeys()) {
        Waterfall wFall = (Waterfall) obj;
        int index = underlying.getRowIndex(wFall);

        Color paint;
        switch (wFall) {
        case DNS_LOOKUP:
            paint = dnsLoolupColor;
            break;
        case INITIAL_CONNECTION:
            paint = initiaConnColor;
            break;
        case SSL_NEGOTIATION:
            paint = sslNegColor;
            break;
        case REQUEST_TIME:
            paint = requestTimeColor;
            break;
        case TIME_TO_FIRST_BYTE:
            paint = firstByteTimeColor;
            break;
        case CONTENT_DOWNLOAD:
            paint = contentDownloadColor;
            break;
        case AFTER_3XX:
            paint = noneColor;
            renderer.setSeriesItemLabelPaint(index, threexColor);
            renderer.setSeriesVisibleInLegend(index, false);
            break;
        case AFTER_4XX:
            paint = noneColor;
            renderer.setSeriesItemLabelPaint(index, fourxColor);
            renderer.setSeriesVisibleInLegend(index, false);
            break;
        case HTTP_3XX_REDIRECTION:
            paint = threexColor;
            break;
        case HTTP_4XX_CLIENTERROR:
            paint = fourxColor;
            break;
        default:
            renderer.setSeriesItemLabelPaint(index, Color.black);
            renderer.setSeriesVisibleInLegend(index, false);
            paint = noneColor;
        }
        renderer.setSeriesPaint(index, paint);
    }

    // Adding the label at the end of bars
    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator() {
        private static final long serialVersionUID = 1L;

        @Override
        public String generateLabel(CategoryDataset dataset, int row, int column) {
            if (Waterfall.AFTER == dataset.getRowKey(row) || Waterfall.AFTER_3XX == dataset.getRowKey(row)
                    || Waterfall.AFTER_4XX == dataset.getRowKey(row)) {
                WaterfallCategory waterfallItem = (WaterfallCategory) dataset.getColumnKey(column);

                RequestResponseTimeline waterfallInfos = waterfallItem.getReqResp().getWaterfallInfos();
                DecimalFormat formatter = new DecimalFormat("#.##");
                int code = waterfallItem.getReqResp().getAssocReqResp().getStatusCode();
                return MessageFormat.format(ResourceBundleHelper.getMessageString("waterfall.totalTime"),
                        formatter.format(waterfallInfos.getTotalTime()),
                        code > 0 ? waterfallItem.getReqResp().getScheme() + " " + code
                                : ResourceBundleHelper.getMessageString("waterfall.unknownCode"));
            }

            return null;
        }
    });

}

From source file:org.tap4j.plugin.util.GraphHelper.java

public static JFreeChart createChart(StaplerRequest req, CategoryDataset dataset) {

    final JFreeChart chart = ChartFactory.createStackedAreaChart("TAP Tests", // chart title
            null, // unused
            "TAP Tests Count", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );/* w ww.  j  a v  a  2  s  .  c  o m*/

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    final LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.RIGHT);

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setForegroundAlpha(0.8f);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    StackedAreaRenderer ar = new StackedAreaRenderer2() {
        private static final long serialVersionUID = 331915263367089058L;

        @Override
        public String generateURL(CategoryDataset dataset, int row, int column) {
            NumberOnlyBuildLabel label = (NumberOnlyBuildLabel) dataset.getColumnKey(column);
            return label.build.getNumber() + "/" + AbstractTapProjectAction.URL_NAME + "/";
        }

        @Override
        public String generateToolTip(CategoryDataset dataset, int row, int column) {
            NumberOnlyBuildLabel label = (NumberOnlyBuildLabel) dataset.getColumnKey(column);
            TapBuildAction build = label.build.getAction(TapBuildAction.class);
            TapResult report = build.getResult();
            report.tally();

            switch (row) {
            case 0:
                return String.valueOf(report.getFailed()) + " Failure(s)";
            case 1:
                return String.valueOf(report.getPassed()) + " Pass";
            case 2:
                return String.valueOf(report.getSkipped()) + " Skip(s)";
            default:
                return "";
            }
        }

    };

    plot.setRenderer(ar);
    ar.setSeriesPaint(0, ColorPalette.RED); // Failures
    ar.setSeriesPaint(1, ColorPalette.BLUE); // Pass
    ar.setSeriesPaint(2, ColorPalette.YELLOW); // Skips

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));

    return chart;
}

From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java

private void initCategoryPlot(JFreeChart chart, ChartModel chartModel,
        final IChartLinkGenerator linkGenerator) {
    initPlot(chart, chartModel);//from ww  w.  ja  v  a  2 s.  c  o m

    org.pentaho.chart.model.TwoAxisPlot twoAxisPlot = (org.pentaho.chart.model.TwoAxisPlot) chartModel
            .getPlot();
    CategoryPlot categoryPlot = chart.getCategoryPlot();

    Grid grid = twoAxisPlot.getGrid();
    if (twoAxisPlot.getOrientation() != Orientation.HORIZONTAL) {
        Color color = (grid.getVerticalLineColor() != null ? new Color(0x00FFFFFF & grid.getVerticalLineColor())
                : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR));
        categoryPlot.setDomainGridlinesVisible(grid.getVerticalLinesVisible());
        categoryPlot.setDomainGridlinePaint(color);

        color = (grid.getHorizontalLineColor() != null ? new Color(0x00FFFFFF & grid.getHorizontalLineColor())
                : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR));
        categoryPlot.setRangeGridlinesVisible(grid.getHorizontalLinesVisible());
        categoryPlot.setRangeGridlinePaint(color);
    } else {
        Color color = (grid.getHorizontalLineColor() != null
                ? new Color(0x00FFFFFF & grid.getHorizontalLineColor())
                : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR));
        categoryPlot.setDomainGridlinesVisible(grid.getHorizontalLinesVisible());
        categoryPlot.setDomainGridlinePaint(color);

        color = (grid.getVerticalLineColor() != null ? new Color(0x00FFFFFF & grid.getVerticalLineColor())
                : new Color(0x00FFFFFF & Grid.DEFAULT_GRID_COLOR));
        categoryPlot.setRangeGridlinesVisible(grid.getVerticalLinesVisible());
        categoryPlot.setRangeGridlinePaint(color);
    }

    categoryPlot.setDomainGridlineStroke(new BasicStroke(1));
    categoryPlot.setRangeGridlineStroke(new BasicStroke(1));

    List<Integer> colors = getPlotColors(twoAxisPlot);

    for (int j = 0; j < categoryPlot.getDatasetCount(); j++) {
        if (linkGenerator != null) {
            categoryPlot.getRenderer(j).setBaseItemURLGenerator(new CategoryURLGenerator() {
                public String generateURL(CategoryDataset dataset, int series, int category) {
                    return linkGenerator.generateLink(dataset.getRowKey(series).toString(),
                            dataset.getColumnKey(category).toString(), dataset.getValue(series, category));
                }
            });
        }
        for (int i = 0; i < colors.size(); i++) {
            categoryPlot.getRenderer(j).setSeriesPaint(i, new Color(0x00FFFFFF & colors.get(i)));
        }
    }

    Font domainAxisFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getFontFamily(),
            twoAxisPlot.getDomainAxis().getFontStyle(), twoAxisPlot.getDomainAxis().getFontWeight(),
            twoAxisPlot.getDomainAxis().getFontSize());
    Font rangeAxisFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getFontFamily(),
            twoAxisPlot.getRangeAxis().getFontStyle(), twoAxisPlot.getRangeAxis().getFontWeight(),
            twoAxisPlot.getRangeAxis().getFontSize());
    Font rangeTitleFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getLegend().getFontFamily(),
            twoAxisPlot.getRangeAxis().getLegend().getFontStyle(),
            twoAxisPlot.getRangeAxis().getLegend().getFontWeight(),
            twoAxisPlot.getRangeAxis().getLegend().getFontSize());
    Font domainTitleFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getLegend().getFontFamily(),
            twoAxisPlot.getDomainAxis().getLegend().getFontStyle(),
            twoAxisPlot.getDomainAxis().getLegend().getFontWeight(),
            twoAxisPlot.getDomainAxis().getLegend().getFontSize());

    CategoryAxis domainAxis = categoryPlot.getDomainAxis();
    ValueAxis rangeAxis = categoryPlot.getRangeAxis();

    AxesLabels axesLabels = getAxesLabels(chartModel);
    if ((axesLabels.rangeAxisLabel.length() > 0) && (rangeTitleFont != null)) {
        rangeAxis.setLabelFont(rangeTitleFont);
    }

    if ((axesLabels.domainAxisLabel.length() > 0) && (domainTitleFont != null)) {
        domainAxis.setLabelFont(domainTitleFont);
    }

    LabelOrientation labelOrientation = twoAxisPlot.getHorizontalAxis().getLabelOrientation();
    if ((labelOrientation != null) && (labelOrientation != LabelOrientation.HORIZONTAL)) {
        if (twoAxisPlot.getOrientation() == Orientation.HORIZONTAL) {
            if (labelOrientation == LabelOrientation.VERTICAL) {
                rangeAxis.setVerticalTickLabels(true);
            }
        } else {
            switch (labelOrientation) {
            case VERTICAL:
                domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
                break;
            case DIAGONAL:
                domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
                break;
            }
        }
    }

    if (domainAxisFont != null) {
        domainAxis.setTickLabelFont(domainAxisFont);
    }
    if (rangeAxisFont != null) {
        rangeAxis.setTickLabelFont(rangeAxisFont);
    }

    Number rangeMin = twoAxisPlot.getRangeAxis().getMinValue();
    if (rangeMin != null) {
        rangeAxis.setLowerBound(rangeMin.doubleValue());
    }
    Number rangeMax = twoAxisPlot.getRangeAxis().getMaxValue();
    if (rangeMax != null) {
        rangeAxis.setUpperBound(rangeMax.doubleValue());
    }
}

From source file:com.android.ddmuilib.HeapPanel.java

/**
 * Creates the chart below the statistics table
 *///from   w w w.ja  v a  2 s.  c  o m
private void createChart() {
    mAllocCountDataSet = new DefaultCategoryDataset();
    mChart = ChartFactory.createBarChart(null, "Size", "Count", mAllocCountDataSet, PlotOrientation.VERTICAL,
            false, true, false);

    // get the font to make a proper title. We need to convert the swt font,
    // into an awt font.
    Font f = mStatisticsBase.getFont();
    FontData[] fData = f.getFontData();

    // event though on Mac OS there could be more than one fontData, we'll only use
    // the first one.
    FontData firstFontData = fData[0];

    java.awt.Font awtFont = SWTUtils.toAwtFont(mStatisticsBase.getDisplay(), firstFontData,
            true /* ensureSameSize */);

    mChart.setTitle(new TextTitle("Allocation count per size", awtFont));

    Plot plot = mChart.getPlot();
    if (plot instanceof CategoryPlot) {
        // get the plot
        CategoryPlot categoryPlot = (CategoryPlot) plot;

        // set the domain axis to draw labels that are displayed even with many values.
        CategoryAxis domainAxis = categoryPlot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

        CategoryItemRenderer renderer = categoryPlot.getRenderer();
        renderer.setBaseToolTipGenerator(new CategoryToolTipGenerator() {
            @Override
            public String generateToolTip(CategoryDataset dataset, int row, int column) {
                // get the key for the size of the allocation
                ByteLong columnKey = (ByteLong) dataset.getColumnKey(column);
                String rowKey = (String) dataset.getRowKey(row);
                Number value = dataset.getValue(rowKey, columnKey);

                return String.format("%1$d %2$s of %3$d bytes", value.intValue(), rowKey, columnKey.getValue());
            }
        });
    }
    mChartComposite = new ChartComposite(mStatisticsBase, SWT.BORDER, mChart, ChartComposite.DEFAULT_WIDTH,
            ChartComposite.DEFAULT_HEIGHT, ChartComposite.DEFAULT_MINIMUM_DRAW_WIDTH,
            ChartComposite.DEFAULT_MINIMUM_DRAW_HEIGHT, 3000, // max draw width. We don't want it to zoom, so we put a big number
            3000, // max draw height. We don't want it to zoom, so we put a big number
            true, // off-screen buffer
            true, // properties
            true, // save
            true, // print
            false, // zoom
            true); // tooltips

    mChartComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
}

From source file:de.fhbingen.wbs.wpOverview.tabs.APCalendarPanel.java

/**
 * Initialize the work package calendar panel inclusive the listeners.
 *//*from   ww w  .j  a  va 2  s  .  c  o m*/
private void init() {
    List<Workpackage> userWp = new ArrayList<Workpackage>(WpManager.getUserWp(WPOverview.getUser()));

    Collections.sort(userWp, new APLevelComparator());

    dataset = createDataset(userWp);
    chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);

    final JPopupMenu popup = new JPopupMenu();
    JMenuItem miSave = new JMenuItem(LocalizedStrings.getButton().save(LocalizedStrings.getWbs().timeLine()));
    miSave.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent arg0) {

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new ExtensionAndFolderFilter("jpg", "jpeg")); //NON-NLS
            chooser.setSelectedFile(new File("chart-" //NON-NLS
                    + System.currentTimeMillis() + ".jpg"));
            int returnVal = chooser.showSaveDialog(reference);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    File outfile = chooser.getSelectedFile();
                    ChartUtilities.saveChartAsJPEG(outfile, chart, chartPanel.getWidth(),
                            chartPanel.getWidth());
                    Controller.showMessage(
                            LocalizedStrings.getMessages().timeLineSaved(outfile.getCanonicalPath()));
                } catch (IOException e) {
                    Controller.showError(LocalizedStrings.getErrorMessages().timeLineExportError());
                }
            }
        }

    });
    popup.add(miSave);

    chartPanel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    });
    chartPanel.setMinimumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawWidth(9999);
    chartPanel.setPreferredSize(
            new Dimension((int) chartPanel.getPreferredSize().getWidth(), 50 + 15 * userWp.size()));

    chartPanel.setPopupMenu(null);

    this.setLayout(new BorderLayout());

    this.removeAll();

    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    panel.add(chartPanel, constraints);

    panel.setBackground(Color.white);
    this.add(panel, BorderLayout.CENTER);

    GanttRenderer.setDefaultShadowsVisible(false);
    GanttRenderer.setDefaultBarPainter(new BarPainter() {

        @Override
        public void paintBar(final Graphics2D g, final BarRenderer arg1, final int row, final int col,
                final RectangularShape rect, final RectangleEdge arg5) {

            String wpName = (String) dataset.getColumnKey(col);
            int i = 0;
            int spaceCount = 0;
            while (wpName.charAt(i++) == ' ' && spaceCount < 17) {
                spaceCount++;
            }

            g.setColor(new Color(spaceCount * 15, spaceCount * 15, spaceCount * 15));
            g.fill(rect);
            g.setColor(Color.black);
            g.setStroke(new BasicStroke());
            g.draw(rect);
        }

        @Override
        public void paintBarShadow(final Graphics2D arg0, final BarRenderer arg1, final int arg2,
                final int arg3, final RectangularShape arg4, final RectangleEdge arg5, final boolean arg6) {

        }

    });

    ((CategoryPlot) chart.getPlot()).setRenderer(new GanttRenderer() {
        private static final long serialVersionUID = -6078915091070733812L;

        public void drawItem(final Graphics2D g2, final CategoryItemRendererState state,
                final Rectangle2D dataArea, final CategoryPlot plot, final CategoryAxis domainAxis,
                final ValueAxis rangeAxis, final CategoryDataset dataset, final int row, final int column,
                final int pass) {
            super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass);
        }
    });

}

From source file:org.jfree.data.general.DatasetUtilities.java

/**
 * Creates a pie dataset from a table dataset by taking all the values
 * for a single row./*  w  ww  . ja  v a2s. c o  m*/
 *
 * @param dataset  the dataset (<code>null</code> not permitted).
 * @param row  the row (zero-based index).
 *
 * @return A pie dataset.
 */
public static PieDataset createPieDatasetForRow(CategoryDataset dataset, int row) {
    DefaultPieDataset result = new DefaultPieDataset();
    int columnCount = dataset.getColumnCount();
    for (int current = 0; current < columnCount; current++) {
        Comparable columnKey = dataset.getColumnKey(current);
        result.setValue(columnKey, dataset.getValue(row, current));
    }
    return result;
}

From source file:com.google.jenkins.flakyTestHandler.plugin.TestFlakyStatsOverRevision.java

private JFreeChart createChart(CategoryDataset dataset) {

    final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart title
            null, // unused
            "count", // range axis label*/master
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips
            false // urls
    );//from  w w w .  j  a  v  a2  s  .  c o  m

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();

    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setForegroundAlpha(0.8f);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    StackedAreaRenderer ar = new StackedAreaRenderer2() {

        @Override
        public String generateToolTip(CategoryDataset dataset, int row, int column) {
            RevisionLabel label = (RevisionLabel) dataset.getColumnKey(column);
            Number value = dataset.getValue(row, column);
            switch (row) {
            case 0:
                return label.revision + ": " + value + " fails";
            case 1:
                return label.revision + ": " + value + " passes";
            default:
                return label.revision;
            }
        }
    };
    plot.setRenderer(ar);
    ar.setSeriesPaint(0, ColorPalette.RED); // Fails.
    ar.setSeriesPaint(1, ColorPalette.BLUE); // Passes.

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));

    return chart;
}

From source file:com.mentor.questa.vrm.jenkins.QuestaVrmHostAction.java

private JFreeChart createChart(StaplerRequest req, CategoryDataset dataset) {

    final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart title
            "Relative time", // unused
            "count", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips
            false // urls
    );/*from   w  w  w .ja v  a 2s . c om*/

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();

    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setForegroundAlpha(0.8f);

    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    StackedAreaRenderer ar = new StackedAreaRenderer2() {
        private long getTime(CategoryDataset dataset, int column) {
            Long offset = (Long) dataset.getColumnKey(column);
            return getRegressionResult().getRegressionBegin().getTime() + offset * 1000;

        }

        @Override
        public String generateURL(CategoryDataset dataset, int row, int column) {
            return "javascript:getSummary(" + getTime(dataset, column) + ");";
        }

        @Override
        public String generateToolTip(CategoryDataset dataset, int row, int column) {
            String host = (String) dataset.getRowKey(row);
            Date date = new Date(getTime(dataset, column));
            int value = (Integer) dataset.getValue(row, column);
            return value + " on " + host + "@" + date.toString();
        }
    };
    plot.setRenderer(ar);

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));

    return chart;
}

From source file:org.tap4j.plugin.util.GraphHelper.java

/**
 * Creates the graph displayed on Method results page to compare execution
 * duration and status of a test method across builds.
 * //  w  ww  .jav a 2s  .c  o  m
 * At max, 9 older builds are displayed.
 * 
 * @param req
 *            request
 * @param dataset
 *            data set to be displayed on the graph
 * @param statusMap
 *            a map with build as key and the test methods execution status
 *            (result) as the value
 * @param methodUrl
 *            URL to get to the method from a build test result page
 * @return the chart
 */
public static JFreeChart createMethodChart(StaplerRequest req, final CategoryDataset dataset,
        final Map<NumberOnlyBuildLabel, String> statusMap, final String methodUrl) {

    final JFreeChart chart = ChartFactory.createBarChart(null, // chart
            // title
            null, // unused
            " Duration (secs)", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            true // urls
    );

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    chart.setBackgroundPaint(Color.white);
    chart.removeLegend();

    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setForegroundAlpha(0.8f);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    BarRenderer br = new BarRenderer() {

        private static final long serialVersionUID = 961671076462240008L;
        Map<String, Paint> statusPaintMap = new HashMap<String, Paint>();

        {
            statusPaintMap.put("PASS", ColorPalette.BLUE);
            statusPaintMap.put("SKIP", ColorPalette.YELLOW);
            statusPaintMap.put("FAIL", ColorPalette.RED);
        }

        /**
         * Returns the paint for an item. Overrides the default behavior
         * inherited from AbstractSeriesRenderer.
         * 
         * @param row
         *            the series.
         * @param column
         *            the category.
         * 
         * @return The item color.
         */
        public Paint getItemPaint(final int row, final int column) {
            NumberOnlyBuildLabel label = (NumberOnlyBuildLabel) dataset.getColumnKey(column);
            Paint paint = statusPaintMap.get(statusMap.get(label));
            // when the status of test method is unknown, use gray color
            return paint == null ? Color.gray : paint;
        }
    };

    br.setBaseToolTipGenerator(new CategoryToolTipGenerator() {
        public String generateToolTip(CategoryDataset dataset, int row, int column) {
            NumberOnlyBuildLabel label = (NumberOnlyBuildLabel) dataset.getColumnKey(column);
            if ("UNKNOWN".equals(statusMap.get(label))) {
                return "unknown";
            }
            // values are in seconds
            return dataset.getValue(row, column) + " secs";
        }
    });

    br.setBaseItemURLGenerator(new CategoryURLGenerator() {
        public String generateURL(CategoryDataset dataset, int series, int category) {
            NumberOnlyBuildLabel label = (NumberOnlyBuildLabel) dataset.getColumnKey(category);
            if ("UNKNOWN".equals(statusMap.get(label))) {
                // no link when method result doesn't exist
                return null;
            }
            // return label.build.getUpUrl() + label.build.getNumber() + "/" + PluginImpl.URL + "/" + methodUrl;
            return label.build.getUpUrl() + label.build.getNumber() + "/tap/" + methodUrl;
        }
    });

    br.setItemMargin(0.0);
    br.setMinimumBarLength(5);
    // set the base to be 1/100th of the maximum value displayed in the
    // graph
    br.setBase(br.findRangeBounds(dataset).getUpperBound() / 100);
    plot.setRenderer(br);

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
    return chart;
}