Example usage for org.jfree.data.time TimeSeries setKey

List of usage examples for org.jfree.data.time TimeSeries setKey

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeries setKey.

Prototype

public void setKey(Comparable key) 

Source Link

Document

Sets the key for the series and sends a VetoableChangeEvent (with the property name "Key") to all registered listeners.

Usage

From source file:org.jfree.data.time.junit.TimeSeriesTest.java

/**
 * Check that cloning works./*from ww w. ja  v a2s .c om*/
 */
public void testClone() {

    TimeSeries series = new TimeSeries("Test Series");

    RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002);
    try {
        series.add(jan1st2002, new Integer(42));
    } catch (SeriesException e) {
        System.err.println("Problem adding to series.");
    }

    TimeSeries clone = null;
    try {
        clone = (TimeSeries) series.clone();
        clone.setKey("Clone Series");
        try {
            clone.update(jan1st2002, new Integer(10));
        } catch (SeriesException e) {
            e.printStackTrace();
        }
    } catch (CloneNotSupportedException e) {
        assertTrue(false);
    }

    int seriesValue = series.getValue(jan1st2002).intValue();
    int cloneValue = Integer.MAX_VALUE;
    if (clone != null) {
        cloneValue = clone.getValue(jan1st2002).intValue();
    }

    assertEquals(42, seriesValue);
    assertEquals(10, cloneValue);
    assertEquals("Test Series", series.getKey());
    if (clone != null) {
        assertEquals("Clone Series", clone.getKey());
    } else {
        assertTrue(false);
    }

}

From source file:org.jfree.data.time.TimeSeriesTest.java

@Test
public void testSetKey() {
    TimeSeries s1 = new TimeSeries("S");
    s1.setKey("S1");
    assertEquals("S1", s1.getKey());

    TimeSeriesCollection c = new TimeSeriesCollection();
    c.addSeries(s1);/*www . j  av a 2 s .  co  m*/
    TimeSeries s2 = new TimeSeries("S2");
    c.addSeries(s2);

    // now we should be allowed to change s1's key to anything but "S2"
    s1.setKey("OK");
    assertEquals("OK", s1.getKey());

    try {
        s1.setKey("S2");
        fail("Expect an exception here.");
    } catch (IllegalArgumentException e) {
        // OK
    }

    // after s1 is removed from the collection, we should be able to set
    // the key to anything we want...
    c.removeSeries(s1);
    s1.setKey("S2");

    // check that removing by index also works
    s1.setKey("S1");
    c.addSeries(s1);
    c.removeSeries(1);
    s1.setKey("S2");
}

From source file:org.jfree.data.time.junit.TimeSeriesTest.java

/**
 * Tests the equals method.//from   w ww  . j  av a  2 s  .  c  om
 */
public void testEquals() {
    TimeSeries s1 = new TimeSeries("Time Series 1");
    TimeSeries s2 = new TimeSeries("Time Series 2");
    boolean b1 = s1.equals(s2);
    assertFalse("b1", b1);

    s2.setKey("Time Series 1");
    boolean b2 = s1.equals(s2);
    assertTrue("b2", b2);

    RegularTimePeriod p1 = new Day();
    RegularTimePeriod p2 = p1.next();
    s1.add(p1, 100.0);
    s1.add(p2, 200.0);
    boolean b3 = s1.equals(s2);
    assertFalse("b3", b3);

    s2.add(p1, 100.0);
    s2.add(p2, 200.0);
    boolean b4 = s1.equals(s2);
    assertTrue("b4", b4);

    s1.setMaximumItemCount(100);
    boolean b5 = s1.equals(s2);
    assertFalse("b5", b5);

    s2.setMaximumItemCount(100);
    boolean b6 = s1.equals(s2);
    assertTrue("b6", b6);

    s1.setMaximumItemAge(100);
    boolean b7 = s1.equals(s2);
    assertFalse("b7", b7);

    s2.setMaximumItemAge(100);
    boolean b8 = s1.equals(s2);
    assertTrue("b8", b8);
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Check that cloning works./*from ww  w  . jav  a  2 s  .  c o m*/
 */
@Test
public void testClone() throws CloneNotSupportedException {
    TimeSeries series = new TimeSeries("Test Series");
    RegularTimePeriod jan1st2002 = new Day(1, MonthConstants.JANUARY, 2002);
    series.add(jan1st2002, new Integer(42));

    TimeSeries clone;
    clone = (TimeSeries) series.clone();
    clone.setKey("Clone Series");
    clone.update(jan1st2002, new Integer(10));

    int seriesValue = series.getValue(jan1st2002).intValue();
    int cloneValue = clone.getValue(jan1st2002).intValue();

    assertEquals(42, seriesValue);
    assertEquals(10, cloneValue);
    assertEquals("Test Series", series.getKey());
    assertEquals("Clone Series", clone.getKey());
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.MeasurementGraphAction2.java

JFreeChart actualLabChartRef(String demographicNo, String labType, String identifier, String testName,
        String patientName, String chartTitle) {
    org.jfree.data.time.TimeSeriesCollection dataset = new org.jfree.data.time.TimeSeriesCollection();

    ArrayList<Map<String, Serializable>> list = CommonLabTestValues.findValuesForTest(labType, demographicNo,
            testName, identifier);//from w w  w.  jav  a  2s .  c om

    String typeYAxisName = "";
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();

    String typeLegendName = "Lab Value";
    typeYAxisName = "type Y";

    boolean nameSet = false;
    TimeSeries newSeries = new TimeSeries(typeLegendName, Day.class);
    for (Map mdb : list) {
        if (!nameSet) {
            typeYAxisName = (String) mdb.get("units");
            typeLegendName = (String) mdb.get("testName");
            newSeries.setKey(typeLegendName);
            nameSet = true;
        }
        newSeries.addOrUpdate(new Day((Date) mdb.get("collDateDate")),
                Double.parseDouble("" + mdb.get("result")));
        log.debug("RANGE " + mdb.get("range"));

        if (mdb.get("range") != null) {
            String range = (String) mdb.get("range");
            if (range.indexOf("-") != -1) {
                String[] sp = range.split("-");
                double open = Double.parseDouble(sp[0]);
                double high = Double.parseDouble(sp[1]);
                double low = Double.parseDouble(sp[0]);
                double close = Double.parseDouble(sp[1]);
                double volume = 1045;
                dataItems.add(new OHLCDataItem(new Day((Date) mdb.get("collDateDate")).getStart(), open, high,
                        low, close, volume));
            }
        }

    }
    dataset.addSeries(newSeries);

    JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, "Days", typeYAxisName, dataset, true,
            true, true);

    XYPlot plot = chart.getXYPlot();
    plot.getDomainAxis().setAutoRange(true);

    log.debug("LEN " + plot.getDomainAxis().getLowerBound() + " ddd " + plot.getDomainAxis().getUpperMargin()
            + " eee " + plot.getDomainAxis().getLowerMargin());
    plot.getDomainAxis().setUpperMargin(plot.getDomainAxis().getUpperMargin() * 6);
    plot.getDomainAxis().setLowerMargin(plot.getDomainAxis().getLowerMargin() * 6);
    plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 1.7);

    plot.getDomainAxis().setUpperMargin(0.9);
    plot.getDomainAxis().setLowerMargin(0.9);
    plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 4);

    ValueAxis va = plot.getRangeAxis();
    va.setAutoRange(true);
    XYItemRenderer renderer = plot.getRenderer(); //DateFormat.getInstance()
    XYItemLabelGenerator generator = new StandardXYItemLabelGenerator("{1} \n {2}",
            new SimpleDateFormat("yyyy.MM.dd"), new DecimalFormat("0.00"));
    renderer.setSeriesItemLabelGenerator(0, generator);//setLabelGenerator(generator);

    renderer.setBaseItemLabelsVisible(true);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainCrosshairPaint(Color.GRAY);

    if (renderer instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) renderer;
        rend.setBaseShapesVisible(true);
        rend.setBaseShapesFilled(true);
    }

    plot.setRenderer(renderer);

    if (dataItems != null && dataItems.size() > 0) {
        OHLCDataItem[] ohlc = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
        XYDataset referenceRangeDataset = new DefaultOHLCDataset("Normal Reference Range", ohlc);
        plot.setDataset(1, referenceRangeDataset);
        plot.mapDatasetToRangeAxis(1, 0);
        plot.setRenderer(1, new HighLowRenderer());

    }

    return chart;
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Tests the equals method.//from w ww. j  a v a2  s. co  m
 */
@Test
public void testEquals() {
    TimeSeries s1 = new TimeSeries("Time Series 1");
    TimeSeries s2 = new TimeSeries("Time Series 2");
    boolean b1 = s1.equals(s2);
    assertFalse("b1", b1);

    s2.setKey("Time Series 1");
    boolean b2 = s1.equals(s2);
    assertTrue("b2", b2);

    RegularTimePeriod p1 = new Day();
    RegularTimePeriod p2 = p1.next();
    s1.add(p1, 100.0);
    s1.add(p2, 200.0);
    boolean b3 = s1.equals(s2);
    assertFalse("b3", b3);

    s2.add(p1, 100.0);
    s2.add(p2, 200.0);
    boolean b4 = s1.equals(s2);
    assertTrue("b4", b4);

    s1.setMaximumItemCount(100);
    boolean b5 = s1.equals(s2);
    assertFalse("b5", b5);

    s2.setMaximumItemCount(100);
    boolean b6 = s1.equals(s2);
    assertTrue("b6", b6);

    s1.setMaximumItemAge(100);
    boolean b7 = s1.equals(s2);
    assertFalse("b7", b7);

    s2.setMaximumItemAge(100);
    boolean b8 = s1.equals(s2);
    assertTrue("b8", b8);
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.MeasurementGraphAction2.java

JFreeChart actualLabChartRefPlusMeds(String demographicNo, String labType, String identifier, String testName,
        String patientName, String chartTitle, String[] drugs) {
    org.jfree.data.time.TimeSeriesCollection dataset = new org.jfree.data.time.TimeSeriesCollection();

    ArrayList<Map<String, Serializable>> list = null;
    MiscUtils.getLogger().debug(/*ww  w . j  a  va2 s.c o  m*/
            " lab type >" + labType + "< >" + labType.equals("loinc") + "<" + testName + " " + identifier);
    if (labType.equals("loinc")) {
        try {

            Connection conn = DbConnectionFilter.getThreadLocalDbConnection();
            list = CommonLabTestValues.findValuesByLoinc2(demographicNo, identifier, conn);
            MiscUtils.getLogger().debug("List ->" + list.size());
            conn.close();
        } catch (Exception ed) {
            MiscUtils.getLogger().error("Error", ed);
        }
    } else {
        list = CommonLabTestValues.findValuesForTest(labType, demographicNo, testName, identifier);
    }
    String typeYAxisName = "";
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();

    String typeLegendName = "Lab Value";
    typeYAxisName = "type Y";

    boolean nameSet = false;
    TimeSeries newSeries = new TimeSeries(typeLegendName, Day.class);
    for (Map mdb : list) {
        if (!nameSet) {
            typeYAxisName = (String) mdb.get("units");
            typeLegendName = (String) mdb.get("testName");
            if (typeLegendName == null) {
                typeLegendName = testName;
            }

            newSeries.setKey(typeLegendName);
            nameSet = true;
        }
        newSeries.addOrUpdate(new Day((Date) mdb.get("collDateDate")),
                Double.parseDouble("" + mdb.get("result")));
        log.debug("RANGE " + mdb.get("range"));

        if (mdb.get("range") != null) {
            String range = (String) mdb.get("range");
            if (range.indexOf("-") != -1) {
                String[] sp = range.split("-");
                double open = Double.parseDouble(sp[0]);
                double high = Double.parseDouble(sp[1]);
                double low = Double.parseDouble(sp[0]);
                double close = Double.parseDouble(sp[1]);
                double volume = 1045;
                dataItems.add(new OHLCDataItem(new Day((Date) mdb.get("collDateDate")).getStart(), open, high,
                        low, close, volume));
            }
        }

    }
    dataset.addSeries(newSeries);

    JFreeChart chart = ChartFactory.createTimeSeriesChart(chartTitle, "Days", typeYAxisName, dataset, true,
            true, true);

    XYPlot plot = chart.getXYPlot();
    plot.getDomainAxis().setAutoRange(true);

    log.debug("LEN " + plot.getDomainAxis().getLowerBound() + " ddd " + plot.getDomainAxis().getUpperMargin()
            + " eee " + plot.getDomainAxis().getLowerMargin());
    plot.getDomainAxis().setUpperMargin(plot.getDomainAxis().getUpperMargin() * 6);
    plot.getDomainAxis().setLowerMargin(plot.getDomainAxis().getLowerMargin() * 6);
    plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 1.7);

    plot.getDomainAxis().setUpperMargin(0.9);
    plot.getDomainAxis().setLowerMargin(0.9);
    plot.getRangeAxis().setUpperMargin(plot.getRangeAxis().getUpperMargin() * 4);

    ValueAxis va = plot.getRangeAxis();
    va.setAutoRange(true);
    XYItemRenderer renderer = plot.getRenderer(); //DateFormat.getInstance()
    XYItemLabelGenerator generator = new StandardXYItemLabelGenerator("{1} \n {2}",
            new SimpleDateFormat("yyyy.MM.dd"), new DecimalFormat("0.00"));
    renderer.setSeriesItemLabelGenerator(0, generator);//setLabelGenerator(generator);

    renderer.setBaseItemLabelsVisible(true);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainCrosshairPaint(Color.GRAY);

    if (renderer instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) renderer;
        rend.setBaseShapesVisible(true);
        rend.setBaseShapesFilled(true);
    }

    plot.setRenderer(renderer);

    if (dataItems != null && dataItems.size() > 0) {
        OHLCDataItem[] ohlc = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
        XYDataset referenceRangeDataset = new DefaultOHLCDataset("Normal Reference Range", ohlc);
        plot.setDataset(1, referenceRangeDataset);
        plot.mapDatasetToRangeAxis(1, 0);
        plot.setRenderer(1, new HighLowRenderer());

    }

    XYTaskDataset drugDataset = getDrugDataSet(demographicNo, drugs);

    //DateAxis xAxis = new DateAxis("Date/Time");
    //DateAxis xAxis = plot.getRangeAxis();
    SymbolAxis yAxis = new SymbolAxis("Meds", getDrugSymbol(demographicNo, drugs));
    yAxis.setGridBandsVisible(false);
    XYBarRenderer xyrenderer = new XYBarRenderer();
    xyrenderer.setUseYInterval(true);
    xyrenderer.setBarPainter(new StandardXYBarPainter());

    //XYPlot xyplot = new XYPlot(drugDataset, xAxis, yAxis, xyrenderer);
    XYPlot xyplot = new XYPlot(drugDataset, plot.getDomainAxis(), yAxis, xyrenderer);

    xyplot.getDomainAxis().setUpperMargin(0.9);
    xyplot.getDomainAxis().setLowerMargin(0.9);

    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(new DateAxis("Date/Time"));
    cplot.add(plot);
    cplot.add(xyplot);

    ///////
    chart = new JFreeChart(chartTitle, cplot);
    chart.setBackgroundPaint(Color.white);

    return chart;
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java

/***********************************************************************************************
 * Update those items on the Chart which are taken from the DAO Metadata,
 * i.e./*  w  ww .  j  a  v a 2s . com*/
 *      Title
 *      Axis.X
 *      Axis.Y.0
 *      Series Keys (from Channel.Name)
 *      Channel.Colour
 *
 * @param chartui
 * @param dao
 * @param channelselector
 * @param debug
 */

private static void updateChartFromDAOMetadata(final ChartUIComponentPlugin chartui,
        final ObservatoryInstrumentDAOInterface dao, final ChannelSelectorUIComponentInterface channelselector,
        final boolean debug) {
    final String SOURCE = "ChartHelper.updateChartFromDAOMetadata() ";

    if ((chartui != null) && (chartui.getChartPanel() != null) && (chartui.getChartPanel().getChart() != null)
            && (dao != null) && (dao.getXYDataset() != null) && (dao.getObservationMetadata() != null)
            && (channelselector != null)) {
        // The set of Metadata available should include the Instrument
        // and any items from the current observation
        MetadataHelper.showDAOMetadata(dao, SOURCE, debug);

        if (chartui.getChartPanel().getChart().getTitle() != null) {
            final String strTitle;

            // Update Title
            strTitle = MetadataHelper.getMetadataValueByKey(dao.getObservationMetadata(),
                    MetadataDictionary.KEY_OBSERVATION_TITLE.getKey());
            chartui.getChartPanel().getChart().getTitle().setText(strTitle);

            LOGGER.debug(debug, SOURCE + "Set new Chart Title [title=" + strTitle + "]");
        } else {
            LOGGER.error(SOURCE + "Chart Title is NULL");
        }

        if (chartui.getChartPanel().getChart().getXYPlot() != null) {
            final String strLabelX;
            final String strLabelY;
            final XYItemRenderer renderer;

            // Update Axis labels
            strLabelX = MetadataHelper.getMetadataValueByKey(dao.getObservationMetadata(),
                    MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_X.getKey());
            // Axis.Y.0 only in this version
            strLabelY = MetadataHelper.getMetadataValueByKey(dao.getObservationMetadata(),
                    MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey()
                            + MetadataDictionary.SUFFIX_SERIES_ZERO);

            // Assume the axes are not NULL
            chartui.getChartPanel().getChart().getXYPlot().getDomainAxis().setLabel(strLabelX);
            chartui.getChartPanel().getChart().getXYPlot().getRangeAxis().setLabel(strLabelY);

            //---------------------------------------------------------------------------------
            // Re-synchronise the ChannelNames with the Series Keys, in case of edits

            if ((DatasetType.XY.equals(chartui.getDatasetType()))
                    && (dao.getXYDataset() instanceof XYSeriesCollection)) {
                try {
                    final List<XYSeries> listXYSeries;

                    // JFreeChart doesn't do Generics!
                    listXYSeries = ((XYSeriesCollection) dao.getXYDataset()).getSeries();

                    for (int intSeriesIndex = 0; intSeriesIndex < listXYSeries.size(); intSeriesIndex++) {
                        final XYSeries xySeries;
                        final String strChannelName;

                        xySeries = listXYSeries.get(intSeriesIndex);

                        // Get the channel names from the ObservationMetadata
                        strChannelName = MetadataHelper.getChannelName(dao.getObservationMetadata(),
                                intSeriesIndex, dao.hasTemperatureChannel());

                        // Set the Series Key to be the same as the Channel.Name
                        // This will appear on the Chart Legend
                        LOGGER.debug(debug, SOURCE + "Set XY Series Key [series.index=" + intSeriesIndex
                                + "] [key=" + strChannelName + "]");
                        xySeries.setKey(strChannelName);
                    }
                }

                catch (final UnknownKeyException exception) {
                    LOGGER.error(SOURCE + "XYSeries has an unknown key");
                    exception.printStackTrace();
                }
            } else if ((DatasetType.TIMESTAMPED.equals(chartui.getDatasetType()))
                    && (dao.getXYDataset() instanceof TimeSeriesCollection)) {
                try {
                    final List<TimeSeries> listTimeSeries;

                    // JFreeChart doesn't do Generics!
                    listTimeSeries = ((TimeSeriesCollection) dao.getXYDataset()).getSeries();

                    for (int intSeriesIndex = 0; intSeriesIndex < listTimeSeries.size(); intSeriesIndex++) {
                        final TimeSeries timeSeries;
                        final String strChannelName;

                        timeSeries = listTimeSeries.get(intSeriesIndex);

                        // Get the channel names from the ObservationMetadata
                        strChannelName = MetadataHelper.getChannelName(dao.getObservationMetadata(),
                                intSeriesIndex, dao.hasTemperatureChannel());

                        // Set the Series Key to be the same as the Channel.Name
                        // This will appear on the Chart Legend
                        LOGGER.debug(debug, SOURCE + "Set TIMESTAMPED Series Key [series.index="
                                + intSeriesIndex + "] [key=" + strChannelName + "]");
                        timeSeries.setKey(strChannelName);
                    }
                }

                catch (final UnknownKeyException exception) {
                    LOGGER.error(SOURCE + "TimeSeries has an unknown key");
                    exception.printStackTrace();
                }
            } else {
                LOGGER.error(SOURCE + "Unexpected Chart DatasetType [type=" + chartui.getDatasetType() + "]");
            }

            //---------------------------------------------------------------------------------
            // Update ChannelColours
            renderer = chartui.getChartPanel().getChart().getXYPlot().getRenderer();

            if ((renderer != null) && (renderer instanceof XYLineAndShapeRenderer)) {
                final XYLineAndShapeRenderer xyItemRenderer;
                int intSeriesCount;

                xyItemRenderer = (XYLineAndShapeRenderer) renderer;

                // Colour only as many Series as we know about
                intSeriesCount = 0;

                // Examine the state of each channel's selection
                // Chart updates occur last, so we can use any changes in the ChannelSelector state
                for (int intChannelIndex = 0; intChannelIndex < channelselector
                        .getChannelCount(); intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    if ((channelselector.getChannelSelectionModes() != null) && (channelselector
                            .getChannelSelectionModes().size() == channelselector.getChannelCount())) {
                        // If there is a ChannelSelector, get the gain setting, or OFF
                        selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);
                    } else if (!channelselector.showChannels()) {
                        // If there is no ChannelSelector, we assume that all Channels are ON, at X1
                        selectionMode = ChannelSelectionMode.X1;
                    } else {
                        // Not sure what to do, so just show all
                        selectionMode = ChannelSelectionMode.X1;
                    }

                    // Colour all visible channels
                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final ColourInterface colour;

                        colour = MetadataHelper.getChannelColour(dao.getObservationMetadata(), intChannelIndex,
                                channelselector.hasTemperatureChannel());
                        if (colour != null) {
                            // Map the Colour to the Series
                            xyItemRenderer.setSeriesPaint(intSeriesCount, colour.getColor());
                        } else {
                            // Use the default colour if the metadata doesn't have it
                            LOGGER.error(SOURCE
                                    + "The channel colour was missing or incorrectly specified in the Metadata, using default colour"
                                    + " [channel=" + intChannelIndex + "]");
                            xyItemRenderer.setSeriesPaint(intSeriesCount,
                                    ChartUIHelper.getStandardColour(intChannelIndex).getColor());
                        }

                        // Prepare for the next Series
                        intSeriesCount++;
                    }
                }
            }
        }

        chartui.getChartPanel().getChart().fireChartChanged();
    } else {
        LOGGER.error(SOURCE + "Unable to update Chart");
    }
}