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

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

Introduction

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

Prototype

public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value) 

Source Link

Document

Adds or updates an item in the times series and sends a SeriesChangeEvent to all registered listeners.

Usage

From source file:com.zimbra.perf.chart.ChartUtil.java

private List<JFreeChart> createJFReeChart(ChartSettings cs) {

    double minValue = Double.MAX_VALUE;
    double maxValue = Double.MIN_VALUE;
    double d = 0;
    double count = 0;
    double total = 0;
    TimeSeriesCollection data = new TimeSeriesCollection();

    ArrayList<ChartSettings> syntheticSettings = new ArrayList<ChartSettings>();
    for (GroupPlotSettings gps : cs.getGroupPlots()) {
        String groupBy = gps.getGroupBy();
        DataColumn dc = new DataColumn(gps.getInfile(), groupBy);
        StringSeries groupBySeries = mStringSeries.get(dc);
        dc = new DataColumn(gps.getInfile(), gps.getDataColumn());
        DataSeries ds = mDataSeries.get(dc);
        int idx = 0;
        Map<String, List<Integer>> groups = new HashMap<String, List<Integer>>();
        for (StringEntry e : groupBySeries.dataCollection) {
            String g = e.getVal();
            List<Integer> indices = groups.get(g);
            if (indices == null) {
                indices = new ArrayList<Integer>();
                groups.put(g, indices);/*w  w  w  .j  a  v  a2s. co  m*/
            }
            indices.add(idx);
            idx++;
        }
        for (Map.Entry<String, List<Integer>> g : groups.entrySet()) {
            String groupByValue = g.getKey();
            if (gps.getIgnoreSet().contains(groupByValue))
                continue;
            List<Integer> indices = g.getValue();
            DataSeries syntheticDS = new DataSeries();
            DataColumn c = new DataColumn(gps.getInfile(),
                    GROUP_PLOT_SYNTHETIC + groupByValue + ":" + gps.getDataColumn());
            for (int i : indices) {
                Entry e = ds.get(i);
                syntheticDS.AddEntry(e.getTimestamp(), e.getVal());
            }
            mDataSeries.put(c, syntheticDS);
            PlotSettings syntheticPlot = new PlotSettings(groupByValue, c.getInfile(), c.getColumn(),
                    gps.getShowRaw(), gps.getShowMovingAvg(), gps.getMovingAvgPoints(), gps.getMultiplier(),
                    gps.getDivisor(), gps.getNonNegative(), gps.getPercentTime(), gps.getDataFunction(),
                    gps.getAggregateFunction(), gps.getOptional(), null, null);
            cs.addPlot(syntheticPlot);
            if (cs.getOutDocument() != null) {
                ChartSettings s = new ChartSettings(String.format(cs.getTitle(), groupByValue),
                        cs.getCategory(), String.format(cs.getOutfile(), groupByValue), cs.getXAxis(),
                        cs.getYAxis(), cs.getAllowLogScale(), cs.getPlotZero(), cs.getWidth(), cs.getHeight(),
                        null, cs.getTopPlots(), cs.getTopPlotsType());
                s.addPlot(syntheticPlot);
                syntheticSettings.add(s);
            }
        }
    }
    if (cs.getOutDocument() != null && cs.getGroupPlots().size() != 0) {
        ArrayList<JFreeChart> charts = new ArrayList<JFreeChart>();
        for (ChartSettings c : syntheticSettings) {
            charts.addAll(createJFReeChart(c));
            c.setOutDocument(cs.getOutDocument());
        }
        mSyntheticChartSettings.addAll(syntheticSettings);
        return charts;
    }

    List<PlotSettings> plots = cs.getPlots();
    if (cs.getTopPlots() > 0 && plots.size() > cs.getTopPlots()) {
        String aggregateFunction = cs.getTopPlotsType().name().toLowerCase();
        System.out.println(String.format("Reducing %d to %d plots for chart '%s'", plots.size(),
                cs.getTopPlots(), cs.getTitle()));
        ArrayList<PlotAggregatePair> aggregates = new ArrayList<PlotAggregatePair>();
        for (PlotSettings ps : plots) {
            DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn());
            String key = ps.getInfile() + ":" + ps.getDataColumn() + ":" + ps.getAggregateFunction();
            PlotDataIterator pdIter = new PlotDataIterator(ps, mDataSeries.get(dc));
            double aggregate = mAggregator.compute(pdIter, aggregateFunction, mAggregateStartAt,
                    mAggregateEndAt, key);
            aggregates.add(new PlotAggregatePair(ps, aggregate));
        }
        Collections.sort(aggregates);
        while (aggregates.size() > cs.getTopPlots()) {
            PlotAggregatePair pair = aggregates.remove(0);
            plots.remove(pair.ps);
        }
    }
    for (PlotSettings ps : plots) {
        String columnName = ps.getDataColumn();
        if (columnName == null) {
            columnName = RATIO_PLOT_SYNTHETIC + ps.getRatioTop() + "/" + ps.getRatioBottom();
            String infile = ps.getInfile();

            String[] top = ps.getRatioTop().split("\\+");
            String[] bottom = ps.getRatioBottom().split("\\+");

            DataColumn[] ratioTop = new DataColumn[top.length];
            DataColumn[] ratioBottom = new DataColumn[bottom.length];

            for (int i = 0, j = top.length; i < j; i++)
                ratioTop[i] = new DataColumn(infile, top[i]);
            for (int i = 0, j = bottom.length; i < j; i++)
                ratioBottom[i] = new DataColumn(infile, bottom[i]);

            DataSeries[] topData = new DataSeries[ratioTop.length];
            DataSeries[] bottomData = new DataSeries[ratioBottom.length];

            for (int i = 0, j = ratioTop.length; i < j; i++)
                topData[i] = mDataSeries.get(ratioTop[i]);
            for (int i = 0, j = ratioBottom.length; i < j; i++)
                bottomData[i] = mDataSeries.get(ratioBottom[i]);

            DataSeries ds = new DataSeries();
            for (int i = 0, j = topData[0].size(); i < j; i++) {
                double topValue = 0.0;
                double bottomValue = 0.0;
                double ratio = 0.0;
                Entry lastEntry = null;
                for (int m = 0, n = topData.length; m < n; m++) {
                    Entry e = topData[m].get(i);
                    topValue += e.getVal();
                }
                for (int m = 0, n = bottomData.length; m < n; m++) {
                    Entry e = bottomData[m].get(i);
                    bottomValue += e.getVal();
                    lastEntry = e;
                }
                if (bottomValue != 0.0) {
                    ratio = topValue / bottomValue;
                }
                // should never be null
                assert lastEntry != null;
                ds.AddEntry(lastEntry.getTimestamp(), ratio);
            }
            mDataSeries.put(new DataColumn(infile, columnName), ds);
            ps.setDataColumn(columnName);
        }
        DataColumn dc = new DataColumn(ps.getInfile(), ps.getDataColumn());
        DataSeries ds = mDataSeries.get(dc);
        TimeSeries ts = new TimeSeries(ps.getLegend(), FixedMillisecond.class);
        int numSamples = 0;
        for (PlotDataIterator pdIter = new PlotDataIterator(ps, ds); pdIter.hasNext(); numSamples++) {
            Pair<Date, Double> entry = pdIter.next();
            Date tstamp = entry.getFirst();
            double val = entry.getSecond().doubleValue();
            if (val != 0 || cs.getPlotZero()) {
                if (d < minValue)
                    minValue = val;
                if (d > maxValue)
                    maxValue = val;
                count++;
                total += val;
                try {
                    ts.addOrUpdate(new FixedMillisecond(tstamp), val);
                } catch (SeriesException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
        if (numSamples == 0 && ps.getOptional()) {
            System.out.format("Skipping optional plot %s (no data sample found)\n\n", ps.getLegend());
            continue;
        }
        System.out.format("Adding %d %s points to %s.\n\n", ds.size(), ps.getLegend(), cs.getOutfile());
        if (ps.getShowRaw()) {
            data.addSeries(ts);
        }
        if (ps.getShowMovingAvg()) {
            int numPoints = ps.getMovingAvgPoints();
            if (numPoints == PlotSettings.DEFAULT_PLOT_MOVING_AVG_POINTS) {
                // Display 200 points for moving average.
                // Divide the total number of points by 200 to
                // determine the number of samples to average
                // for each point.
                numPoints = ts.getItemCount() / 200;
            }
            if (numPoints >= 2) {
                TimeSeries ma = MovingAverage.createPointMovingAverage(ts, ps.getLegend() + " (moving avg)",
                        numPoints);
                data.addSeries(ma);
            } else {
                System.out.println("Not enough data to display moving average for " + ps.getLegend());
                data.addSeries(ts);

            }
        }

    }
    // Create chart
    boolean legend = (data.getSeriesCount() > 1);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, cs.getXAxis(), cs.getYAxis(), data, legend,
            false, false);

    // Make Y-axis logarithmic if a spike was detected
    if (cs.getAllowLogScale() && (minValue > 0) && (maxValue > 0) && (maxValue > 20 * (total / count))) {
        if (maxValue / minValue > 100) {
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis oldAxis = plot.getRangeAxis();
            LogarithmicAxis newAxis = new LogarithmicAxis(oldAxis.getLabel());
            plot.setRangeAxis(newAxis);
        }
    }

    mChartMap.put(cs, chart);
    return Arrays.asList(chart);

}

From source file:com.jtstand.swing.StatsPanel.java

public JFreeChart getChartTime() {
    TreeMap<String, List<TestStepInstance>> s = getGroupedSteps(getFilteringIterator());
    if (s == null || s.size() == 0) {
        return null;
    }/*from   w w w  .  j ava 2 s  . c  o  m*/
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    for (Iterator<String> en = s.keySet().iterator(); en.hasNext();) {
        String groupName = en.next();
        List<TestStepInstance> stps = s.get(groupName);
        //            TimeSeries pop = new TimeSeries(groupName, Millisecond.class);
        TimeSeries pop = new TimeSeries(groupName);
        for (Iterator<TestStepInstance> it = stps.iterator(); it.hasNext();) {
            TestStepInstance step = it.next();
            Number num = getNumber(step);
            if (num != null) {
                switch (chartMode) {
                case STEP_TIME:
                    pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class,
                            new Date(step.getStartTime()), TimeZone.getDefault()), num);
                    break;
                case SEQUENCE_TIME:
                    //                            pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getTestSequenceInstance().getStartTime()), RegularTimePeriod.DEFAULT_TIME_ZONE), num);
                    pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class,
                            new Date(step.getTestSequenceInstance().getCreateTime()), TimeZone.getDefault()),
                            num);
                    break;
                }
            }
        }
        dataset.addSeries(pop);
    }
    JFreeChart chart = null;
    switch (chartMode) {
    case STEP_TIME:
        chart = ChartFactory.createTimeSeriesChart(null, "Step Started Time", getValueString(), dataset,
                isGrouping(), true, false);
        break;
    case SEQUENCE_TIME:
        chart = ChartFactory.createTimeSeriesChart(null, "Sequence Started Time", getValueString(), dataset,
                isGrouping(), true, false);
        break;
    }
    chart.setBackgroundPaint((Paint) UIManager.get("Panel.background"));

    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    XYLineAndShapeRenderer renderer5 = new XYLineAndShapeRenderer();
    renderer5.setBaseSeriesVisibleInLegend(false);
    plot.setRenderer(renderer5);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeCrosshairVisible(true);
    plot.setDomainCrosshairVisible(true);
    //        chart.setTitle(valueName);
    placeLimitMarkers(plot, true);

    //renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
    renderer5.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());

    /* coloring */
    if (isCategorization()) {
        //            TreeMap<String, Color> cmap = new TreeMap<String, Color>();
        int i = 0;
        for (Iterator<String> it = catstats.keySet().iterator(); it.hasNext(); i++) {
            String groupName = it.next();
            Color c = ChartCategories.getColor(i);
            for (int j = 0; j < dataset.getSeriesCount(); j++) {
                TimeSeries ts = dataset.getSeries(j);
                if (ts.getKey().equals(groupName)) {
                    renderer5.setSeriesPaint(j, c);
                }
            }
        }
    } else {
        renderer5.setSeriesPaint(0, ChartCategories.getColor(0));
    }

    //        chart.addProgressListener(new ChartProgressListener() {
    //
    //            public void chartProgress(final ChartProgressEvent progress) {
    //                SwingUtilities.invokeLater(
    //                        new Runnable() {
    //
    //                            @Override
    //                            public void run() {
    //
    //                                System.out.println("progress:" + progress + " " + progress.getType());
    //                                if (progress.getType() == ChartProgressEvent.DRAWING_FINISHED) {
    //                                    if (plot != null) {
    //                                        if (plot.isDomainCrosshairVisible() && plot.isDomainCrosshairLockedOnData()) {
    ////                            System.out.println("getDomainCrosshairValue:" + plot.getDomainCrosshairValue());
    //                                            double xx = plot.getDomainCrosshairValue();
    //                                            if (xx != 0.0) {
    //                                                long x = (long) xx;
    //                                                System.out.println(new Date(x));
    //                                                for (TestStepInstance step : testStepInstances.getSteps()) {
    //                                                    if (step.getStartTime() != null && step.getStartTime().equals(x)) {
    //                                                        testStepInstances.selectStep(step);
    //                                                    }
    //                                                }
    //                                                System.out.println(new Date(x));
    //                                            }
    //                                        }
    ////                        if (plot.isRangeCrosshairVisible()) {
    ////                            System.out.println("getRangeCrosshairValue:" + plot.getRangeCrosshairValue());
    ////                        }
    //                                    }
    //                                }
    //                            }
    //                        });
    //            }
    //        });

    //        chart.addChangeListener(new ChartChangeListener() {
    //
    //            public void chartChanged(ChartChangeEvent event) {
    //                System.out.println("event:" + event);
    //                if (event != null) {
    ////                    JFreeChart chart = event.getChart();
    ////                    System.out.println("chart:" + chart);
    ////                    if (chart != null) {
    ////                        System.out.println("title:" + event.getChart().getTitle());
    ////                    }
    //                    System.out.println("type:" + event.getType());
    //                    if (plot != null) {
    //                        if (plot.isDomainCrosshairVisible()) {
    //                            System.out.println("getDomainCrosshairValue:" + plot.getDomainCrosshairValue());
    //                            long x = (long) plot.getDomainCrosshairValue();
    //                            for (TestStepInstance step : testStepInstances.getSteps()) {
    //                                if (step.getStartTime() != null && step.getStartTime().equals(x)) {
    //                                    testStepInstances.selectStep(step);
    //                                }
    //                            }
    //                            System.out.println(new Date(x));
    //                        }
    //                        if (plot.isRangeCrosshairVisible()) {
    //                            System.out.println("getRangeCrosshairValue:" + plot.getRangeCrosshairValue());
    //                        }
    //                    }
    //                }
    //            }
    //        });
    chart.setTextAntiAlias(false);
    return chart;
}

From source file:org.openmrs.web.servlet.ShowGraphServlet.java

/**
 * The main method for this class. It will create a JFreeChart object to be written to the
 * response./*from  www  .  ja  v  a 2  s  .  c  o m*/
 *
 * @param request the current request will all the parameters needed
 * @return JFreeChart object to be rendered
 * @should set value axis label to given units
 * @should set value axis label to concept numeric units if given units is null
 */
protected JFreeChart getChart(HttpServletRequest request) {
    // All available GET parameters
    String patientId = request.getParameter("patientId"); // required
    String conceptId1 = request.getParameter("conceptId"); // required
    String conceptId2 = request.getParameter("conceptId2");
    String chartTitle = request.getParameter("chartTitle");
    String units = request.getParameter("units");

    String minRangeString = request.getParameter("minRange");
    String maxRangeString = request.getParameter("maxRange");

    String hideDate = request.getParameter("hideDate");

    Patient patient = Context.getPatientService().getPatient(Integer.parseInt(patientId));

    // Set date range to passed values, otherwise set a default date range to the last 12 months
    Calendar cal = Calendar.getInstance();
    Date fromDate = getFromDate(request.getParameter("fromDate"));
    Date toDate = getToDate(request.getParameter("toDate"));

    // Swap if fromDate is after toDate
    if (fromDate.getTime() > toDate.getTime()) {
        Long temp = fromDate.getTime();
        fromDate.setTime(toDate.getTime());
        toDate.setTime(temp);
    }

    // Graph parameters
    Double minRange = null;
    Double maxRange = null;
    Double normalLow = null;
    Double normalHigh = null;
    Double criticalLow = null;
    Double criticalHigh = null;
    String timeAxisTitle = null;
    String rangeAxisTitle = null;
    boolean userSpecifiedMaxRange = false;
    boolean userSpecifiedMinRange = false;

    // Fetching obs
    List<Obs> observations1 = new ArrayList<Obs>();
    List<Obs> observations2 = new ArrayList<Obs>();
    Concept concept1 = null, concept2 = null;
    if (conceptId1 != null) {
        concept1 = Context.getConceptService().getConcept(Integer.parseInt(conceptId1));
    }
    if (conceptId2 != null) {
        concept2 = Context.getConceptService().getConcept(Integer.parseInt(conceptId2));
    }
    if (concept1 != null) {
        observations1 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept1);
        chartTitle = concept1.getName().getName();
        rangeAxisTitle = ((ConceptNumeric) concept1).getUnits();
        minRange = ((ConceptNumeric) concept1).getLowAbsolute();
        maxRange = ((ConceptNumeric) concept1).getHiAbsolute();
        normalLow = ((ConceptNumeric) concept1).getLowNormal();
        normalHigh = ((ConceptNumeric) concept1).getHiNormal();
        criticalLow = ((ConceptNumeric) concept1).getLowCritical();
        criticalHigh = ((ConceptNumeric) concept1).getHiCritical();

        // Only get observations2 if both concepts share the same units; update chart title and ranges
        if (concept2 != null) {
            String concept2Units = ((ConceptNumeric) concept2).getUnits();
            if (concept2Units != null && concept2Units.equals(rangeAxisTitle)) {
                observations2 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept2);
                chartTitle += " + " + concept2.getName().getName();
                if (((ConceptNumeric) concept2).getHiAbsolute() != null
                        && ((ConceptNumeric) concept2).getHiAbsolute() > maxRange) {
                    maxRange = ((ConceptNumeric) concept2).getHiAbsolute();
                }
                if (((ConceptNumeric) concept2).getLowAbsolute() != null
                        && ((ConceptNumeric) concept2).getLowAbsolute() < minRange) {
                    minRange = ((ConceptNumeric) concept2).getLowAbsolute();
                }
            } else {
                log.warn("Units for concept id: " + conceptId2 + " don't match units for concept id: "
                        + conceptId1 + ". Only displaying " + conceptId1);
                concept2 = null; // nullify concept2 so that the legend isn't shown later
            }
        }
    } else {
        chartTitle = "Concept " + conceptId1 + " not found";
        rangeAxisTitle = "Value";
    }

    // Overwrite with user-specified values, otherwise use default values
    if (units != null && units.length() > 0) {
        rangeAxisTitle = units;
    }
    if (minRangeString != null) {
        minRange = Double.parseDouble(minRangeString);
        userSpecifiedMinRange = true;
    }
    if (maxRangeString != null) {
        maxRange = Double.parseDouble(maxRangeString);
        userSpecifiedMaxRange = true;
    }
    if (chartTitle == null) {
        chartTitle = "";
    }
    if (rangeAxisTitle == null) {
        rangeAxisTitle = "";
    }
    if (minRange == null) {
        minRange = 0.0;
    }
    if (maxRange == null) {
        maxRange = 200.0;
    }

    // Create data set
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series1, series2;

    // Interval-dependent units
    Class<? extends RegularTimePeriod> timeScale = null;
    if (toDate.getTime() - fromDate.getTime() <= 86400000) {
        // Interval <= 1 day: minutely
        timeScale = Minute.class;
        timeAxisTitle = "Time";
    } else if (toDate.getTime() - fromDate.getTime() <= 259200000) {
        // Interval <= 3 days: hourly
        timeScale = Hour.class;
        timeAxisTitle = "Time";
    } else {
        timeScale = Day.class;
        timeAxisTitle = "Date";
    }
    if (concept1 == null) {
        series1 = new TimeSeries("NULL", Hour.class);
    } else {
        series1 = new TimeSeries(concept1.getName().getName(), timeScale);
    }
    if (concept2 == null) {
        series2 = new TimeSeries("NULL", Hour.class);
    } else {
        series2 = new TimeSeries(concept2.getName().getName(), timeScale);
    }

    // Add data points for concept1
    for (Obs obs : observations1) {
        if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime()
                && obs.getObsDatetime().getTime() < toDate.getTime()) {
            cal.setTime(obs.getObsDatetime());
            if (timeScale == Minute.class) {
                Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                        cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series1.addOrUpdate(min, obs.getValueNumeric());
            } else if (timeScale == Hour.class) {
                Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH),
                        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series1.addOrUpdate(hour, obs.getValueNumeric());
            } else {
                Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
                        cal.get(Calendar.YEAR));
                series1.addOrUpdate(day, obs.getValueNumeric());
            }
        }
    }

    // Add data points for concept2
    for (Obs obs : observations2) {
        if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime()
                && obs.getObsDatetime().getTime() < toDate.getTime()) {
            cal.setTime(obs.getObsDatetime());
            if (timeScale == Minute.class) {
                Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                        cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series2.addOrUpdate(min, obs.getValueNumeric());
            } else if (timeScale == Hour.class) {
                Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH),
                        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series2.addOrUpdate(hour, obs.getValueNumeric());
            } else {
                Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
                        cal.get(Calendar.YEAR));
                series2.addOrUpdate(day, obs.getValueNumeric());
            }
        }
    }

    // Add series to dataset
    dataset.addSeries(series1);
    if (!series2.isEmpty()) {
        dataset.addSeries(series2);
    }

    // As of JFreeChart 1.0.11 the default background color is dark grey instead of white.
    // This line restores the original white background.
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());

    JFreeChart chart = null;

    // Show legend only if more than one series
    if (concept2 == null) {
        chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, false,
                false, false);
    } else {
        chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, true,
                false, false);
    }

    // Customize title font
    Font font = new Font("Arial", Font.BOLD, 12);
    TextTitle title = chart.getTitle();
    title.setFont(font);
    chart.setTitle(title);

    // Add subtitle, unless 'hideDate' has been passed
    if (hideDate == null) {
        TextTitle subtitle = new TextTitle(fromDate.toString() + " - " + toDate.toString());
        subtitle.setFont(font);
        chart.addSubtitle(subtitle);
    }

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setNoDataMessage("No Data Available");

    // Add abnormal/critical range background color (only for single-concept graphs)
    if (concept2 == null) {
        IntervalMarker abnormalLow, abnormalHigh, critical;
        if (normalHigh != null) {
            abnormalHigh = new IntervalMarker(normalHigh, maxRange, COLOR_ABNORMAL);
            plot.addRangeMarker(abnormalHigh);
        }
        if (normalLow != null) {
            abnormalLow = new IntervalMarker(minRange, normalLow, COLOR_ABNORMAL);
            plot.addRangeMarker(abnormalLow);
        }
        if (criticalHigh != null) {
            critical = new IntervalMarker(criticalHigh, maxRange, COLOR_CRITICAL);
            plot.addRangeMarker(critical);
        }
        if (criticalLow != null) {
            critical = new IntervalMarker(minRange, criticalLow, COLOR_CRITICAL);
            plot.addRangeMarker(critical);
        }

        // there is data outside of the absolute lower limits for this concept (or of what the user specified as minrange)
        if (plot.getRangeAxis().getLowerBound() < minRange) {
            IntervalMarker error = new IntervalMarker(plot.getRangeAxis().getLowerBound(), minRange,
                    COLOR_ERROR);
            plot.addRangeMarker(error);
        }

        if (plot.getRangeAxis().getUpperBound() > maxRange) {
            IntervalMarker error = new IntervalMarker(maxRange, plot.getRangeAxis().getUpperBound(),
                    COLOR_ERROR);
            plot.addRangeMarker(error);
        }

    }

    // Visuals
    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesFilled(true);
        renderer.setBaseShapesVisible(true);
    }

    // Customize the plot (range and domain axes)

    // Modify x-axis (datetime)
    DateAxis timeAxis = (DateAxis) plot.getDomainAxis();
    if (timeScale == Day.class) {
        timeAxis.setDateFormatOverride(new SimpleDateFormat("dd-MMM-yyyy"));
    }

    timeAxis.setRange(fromDate, toDate);

    // Set y-axis range (values)
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (userSpecifiedMinRange) {
        minRange = (rangeAxis.getLowerBound() < minRange) ? rangeAxis.getLowerBound() : minRange;
    }

    if (userSpecifiedMaxRange) {
        // otherwise we just use default range
        maxRange = (rangeAxis.getUpperBound() > maxRange) ? rangeAxis.getUpperBound() : maxRange;
    }

    rangeAxis.setRange(minRange, maxRange);

    return chart;
}

From source file:beproject.MainGUI.java

void getTimeLineData(TimeSeriesCollection t) throws SQLException {
    Statement stmt = Initializer.inConn2.createStatement();
    ResultSet rs1 = stmt.executeQuery("select max(ts) from tweets");
    rs1.first();//ww w  . jav  a  2 s .co  m
    Timestamp ts1 = rs1.getTimestamp(1);
    for (String tmp : ScheduledMoviesList.getMovieNames()) {
        TimeSeries t1 = new TimeSeries(tmp, Hour.class);
        Timestamp ts = (Timestamp) ts1.clone();
        for (int i = 0; i < 6; i++) {
            Date d1 = new java.util.Date(ts.getTime());
            Date d2 = new java.util.Date(ts.getTime() + 3600000);
            ResultSet rs = stmt
                    .executeQuery("select count(*) from tweets where moviename='" + tmp + "' and ts between '"
                            + Regression.sdf.format(d1) + "' and '" + Regression.sdf.format(d2) + "'");
            rs.first();
            //if(!rs.first())
            //  t1.addOrUpdate(new Hour(d1), 0);
            //else
            t1.addOrUpdate(new Hour(d1), rs.getInt(1));
            ts.setTime(ts.getTime() - 3600000);
        }
        t.addSeries(t1);
    }

}

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

/**
 * Function to update charts with the newly received value 
 * @param fullPath the full-name of the changed {@link StatusVariable}
 * @param value the value of a {@link StatusVariable} received via event
 *///  ww  w.  ja  va2s  .c  om
private void updateValue(String fullPath, Object value) {
    final TimeSeries series = this.seriesMap.get(fullPath);
    if (series != null) {
        Number num = null;

        /* 
         * According to the MA spec the values 
         * must be delivered as String 
         */
        if (value instanceof String) {
            Integer type = this.typeList.get(fullPath);
            if (type != null) {
                switch (type.intValue()) {
                case StatusVariable.TYPE_FLOAT:
                    num = Float.valueOf((String) value);
                    break;

                case StatusVariable.TYPE_INTEGER:
                    num = Integer.valueOf((String) value);
                    break;

                // these types are not supported by the chart-servlet for now
                /*
                case StatusVariable.TYPE_BOOLEAN:                     
                case StatusVariable.TYPE_STRING:
                */

                default:
                    break;
                }
            }

        }
        /* 
         * XXX: this is a bug of the apache felix implementation.
         * As defined in the OSGi spec, the value should be delivered
         * as String
         */
        else if (value instanceof Number) {
            num = (Number) value;
        } else {
            this.logger.warn(String.format("Unexpected type of monitoring variable '%s': %s",
                    value.getClass().getSimpleName(), fullPath));
        }

        if (num != null) {
            if (fullPath.equalsIgnoreCase(TSERIES_MEMORY_USAGE)) {
                /* 
                 * the memory-usage value is in KB.
                 * See org.paxle.core.monitorable.provider.impl.RuntimeMemoryMonitoring for details
                 */

                num = Integer.valueOf(num.intValue() / 1024);
            } else if (fullPath.startsWith(CPU_MONITORABLE_ID)) {
                num = new Double(num.doubleValue() * 100f);
            }
            series.addOrUpdate(new Minute(new Date()), num);
        }
    }
}

From source file:com.android.ddmuilib.log.event.DisplayGraph.java

/**
* Updates the chart with the {@link EventContainer} by adding the values/occurrences defined
* by the {@link ValueDisplayDescriptor} and {@link OccurrenceDisplayDescriptor} objects from
* the two lists./*  w ww  .j a  va2  s.c  o m*/
* <p/>This method is only called when at least one of the descriptor list is non empty.
* @param event
* @param logParser
* @param valueDescriptors
* @param occurrenceDescriptors
*/
private void updateChart(EventContainer event, EventLogParser logParser,
        ArrayList<ValueDisplayDescriptor> valueDescriptors,
        ArrayList<OccurrenceDisplayDescriptor> occurrenceDescriptors) {
    Map<Integer, String> tagMap = logParser.getTagMap();

    Millisecond millisecondTime = null;
    long msec = -1;

    // If the event container is a cpu container (tag == 2721), and there is no descriptor
    // for the total CPU load, then we do accumulate all the values.
    boolean accumulateValues = false;
    double accumulatedValue = 0;

    if (event.mTag == 2721) {
        accumulateValues = true;
        for (ValueDisplayDescriptor descriptor : valueDescriptors) {
            accumulateValues &= (descriptor.valueIndex != 0);
        }
    }

    for (ValueDisplayDescriptor descriptor : valueDescriptors) {
        try {
            // get the hashmap for this descriptor
            HashMap<Integer, TimeSeries> map = mValueDescriptorSeriesMap.get(descriptor);

            // if it's not there yet, we create it.
            if (map == null) {
                map = new HashMap<Integer, TimeSeries>();
                mValueDescriptorSeriesMap.put(descriptor, map);
            }

            // get the TimeSeries for this pid
            TimeSeries timeSeries = map.get(event.pid);

            // if it doesn't exist yet, we create it
            if (timeSeries == null) {
                // get the series name
                String seriesFullName = null;
                String seriesLabel = getSeriesLabel(event, descriptor);

                switch (mValueDescriptorCheck) {
                case EVENT_CHECK_SAME_TAG:
                    seriesFullName = String.format("%1$s / %2$s", seriesLabel, descriptor.valueName);
                    break;
                case EVENT_CHECK_SAME_VALUE:
                    seriesFullName = String.format("%1$s", seriesLabel);
                    break;
                default:
                    seriesFullName = String.format("%1$s / %2$s: %3$s", seriesLabel,
                            tagMap.get(descriptor.eventTag), descriptor.valueName);
                    break;
                }

                // get the data set for this ValueType
                TimeSeriesCollection dataset = getValueDataset(
                        logParser.getEventInfoMap().get(event.mTag)[descriptor.valueIndex].getValueType(),
                        accumulateValues);

                // create the series
                timeSeries = new TimeSeries(seriesFullName, Millisecond.class);
                if (mMaximumChartItemAge != -1) {
                    timeSeries.setMaximumItemAge(mMaximumChartItemAge * 1000);
                }

                dataset.addSeries(timeSeries);

                // add it to the map.
                map.put(event.pid, timeSeries);
            }

            // update the timeSeries.

            // get the value from the event
            double value = event.getValueAsDouble(descriptor.valueIndex);

            // accumulate the values if needed.
            if (accumulateValues) {
                accumulatedValue += value;
                value = accumulatedValue;
            }

            // get the time
            if (millisecondTime == null) {
                msec = (long) event.sec * 1000L + (event.nsec / 1000000L);
                millisecondTime = new Millisecond(new Date(msec));
            }

            // add the value to the time series
            timeSeries.addOrUpdate(millisecondTime, value);
        } catch (InvalidTypeException e) {
            // just ignore this descriptor if there's a type mismatch
        }
    }

    for (OccurrenceDisplayDescriptor descriptor : occurrenceDescriptors) {
        try {
            // get the hashmap for this descriptor
            HashMap<Integer, TimeSeries> map = mOcurrenceDescriptorSeriesMap.get(descriptor);

            // if it's not there yet, we create it.
            if (map == null) {
                map = new HashMap<Integer, TimeSeries>();
                mOcurrenceDescriptorSeriesMap.put(descriptor, map);
            }

            // get the TimeSeries for this pid
            TimeSeries timeSeries = map.get(event.pid);

            // if it doesn't exist yet, we create it.
            if (timeSeries == null) {
                String seriesLabel = getSeriesLabel(event, descriptor);

                String seriesFullName = String.format("[%1$s:%2$s]", tagMap.get(descriptor.eventTag),
                        seriesLabel);

                timeSeries = new TimeSeries(seriesFullName, Millisecond.class);
                if (mMaximumChartItemAge != -1) {
                    timeSeries.setMaximumItemAge(mMaximumChartItemAge);
                }

                getOccurrenceDataSet().addSeries(timeSeries);

                map.put(event.pid, timeSeries);
            }

            // update the series

            // get the time
            if (millisecondTime == null) {
                msec = (long) event.sec * 1000L + (event.nsec / 1000000L);
                millisecondTime = new Millisecond(new Date(msec));
            }

            // add the value to the time series
            timeSeries.addOrUpdate(millisecondTime, 0); // the value is unused
        } catch (InvalidTypeException e) {
            // just ignore this descriptor if there's a type mismatch
        }
    }

    // go through all the series and remove old values.
    if (msec != -1 && mMaximumChartItemAge != -1) {
        Collection<HashMap<Integer, TimeSeries>> pidMapValues = mValueDescriptorSeriesMap.values();

        for (HashMap<Integer, TimeSeries> pidMapValue : pidMapValues) {
            Collection<TimeSeries> seriesCollection = pidMapValue.values();

            for (TimeSeries timeSeries : seriesCollection) {
                timeSeries.removeAgedItems(msec, true);
            }
        }

        pidMapValues = mOcurrenceDescriptorSeriesMap.values();
        for (HashMap<Integer, TimeSeries> pidMapValue : pidMapValues) {
            Collection<TimeSeries> seriesCollection = pidMapValue.values();

            for (TimeSeries timeSeries : seriesCollection) {
                timeSeries.removeAgedItems(msec, true);
            }
        }
    }
}

From source file:de.citec.csra.allocation.vis.MovingChart.java

public void updateDataPoints(String id, String label, String resource, long start, long end, State state,
        Priority prio, boolean token) {
    synchronized (this.dataset) {
        TimeSeries series = this.dataset.getSeries(id);
        if (series == null) {
            series = new TimeSeries(id);
            this.dataset.addSeries(series);
        }/* ww w. j av a2  s . c o m*/

        series.setDomainDescription(label);
        int stroke = -1;
        Color c = null;

        boolean randomcolor = false;
        if (!randomcolor) {
            switch (prio) {
            case EMERGENCY:
                c = Color.RED;
                break;
            case URGENT:
                c = Color.ORANGE;
                break;
            case HIGH:
                c = Color.YELLOW;
                break;
            case NORMAL:
                c = Color.GREEN;
                break;
            case LOW:
                c = Color.BLUE;
                break;
            case NO:
                c = Color.BLACK;
                break;
            }
        }

        switch (state) {
        case REQUESTED:
            stroke = 1;
            break;
        case SCHEDULED:
            stroke = 3;
            break;
        case ALLOCATED:
            stroke = 9;
            break;
        case RELEASED:
            stroke = 1;
            break;
        case REJECTED:
        case CANCELLED:
        case ABORTED:
            c = Color.GRAY;
            stroke = 1;
            break;
        }

        XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) this.chart.getXYPlot()
                .getRendererForDataset(dataset);

        int number = -1;
        for (int i = 0; i < this.dataset.getSeries().size(); i++) {
            TimeSeries t = this.dataset.getSeries(i);
            if (t.getKey().equals(id)) {
                number = i;
            }
        }
        if (number > 0) {
            if (stroke > 0) {
                if (token) {
                    r.setSeriesStroke(number,
                            new BasicStroke(stroke, CAP_BUTT, JOIN_BEVEL, 1, new float[] { 1.5f, .5f }, .5f));
                } else {
                    r.setSeriesStroke(number, new BasicStroke(stroke, CAP_BUTT, JOIN_BEVEL, 1));
                }
            }
            if (c != null) {
                r.setSeriesPaint(number, c);
            }
        }

        long channel;
        String key = resource; //prio
        if (values.containsKey(key)) {
            channel = values.get(key);
        } else {
            channel = events++;
            values.put(key, channel);
        }

        if (!series.isEmpty()) {
            series.clear();
        }
        series.addOrUpdate(new Millisecond(new Date(start)), channel);
        series.addOrUpdate(new Millisecond(new Date(end)), channel);
    }
}

From source file:oscar.form.study.hsfo2.pageUtil.ManageHSFOAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.info("ContextPath: " + request.getContextPath());
    logger.info("pathInfo: " + request.getPathInfo());
    Map<String, String[]> params = request.getParameterMap();

    Hsfo2Visit latestHsfo2Visit = new Hsfo2Visit();
    PatientList historyList = new PatientList();
    // RecordList record = new RecordList();
    List recordList = new LinkedList();

    String patientId = (String) request.getAttribute("demographic_no");
    if (patientId == null) {
        patientId = request.getParameter("demographic_no");
    }//from www . j  a v a  2s .  c  o m
    String isfirstrecord = "";
    boolean isFirstRecord = false;
    String user = (String) request.getSession().getAttribute("user");

    HSFODAO hsfoDAO = new HSFODAO();
    isFirstRecord = hsfoDAO.isFirstRecord(patientId);

    DemographicData demoData = new DemographicData();
    //DemographicData.Demographic de = demoData.getDemographic( patientId );
    Demographic de = demoData.getDemographic(patientId);

    boolean isDisplayGraphs = "displayGraphs".equalsIgnoreCase(request.getParameter("operation"));

    boolean isFromRegistrationForm = false;
    if ("true".equalsIgnoreCase(request.getParameter("isFromRegistrationForm"))) {
        //true means the request is from registration form, should goto followup form
        isFromRegistrationForm = true;
    }

    FORM forwardToForm = null;
    int patientHistorySize = 0;
    boolean isFirstVisitRecordForThePatient = false;
    //    boolean isFromRegistrationForm = false;  

    Integer formId = getFormIdFromRequest(request);
    Hsfo2Visit formHsfo2Visit = null;
    if (formId != null)
        formHsfo2Visit = hsfoDAO.retrieveSelectedRecord(formId);
    boolean isHistoryForm = !isFromRegistrationForm && (formId != null && formHsfo2Visit != null);

    if (formId != null)
        isFirstVisitRecordForThePatient = hsfoDAO.isFirstVisitRecordForThePatient(patientId, formId);
    boolean isRegistForm = !isDisplayGraphs && !isFromRegistrationForm
            && (isFirstRecord || isFirstVisitRecordForThePatient);

    //prepare data
    Hsfo2Patient hsfo2Patient = hsfoDAO.retrievePatientRecord(patientId);
    if (hsfo2Patient == null)
        hsfo2Patient = new Hsfo2Patient();
    List patientHistory = hsfoDAO.retrieveVisitRecord(patientId);

    //save only or submit, it's for registration form and stay in that form
    boolean isSaveOnly = "Save".equalsIgnoreCase(request.getParameter("Save"));
    if (!isSaveOnly && !isFirstRecord) {
        isSaveOnly = !hsfo2Patient.isSubmitted();
    }

    if (isSaveOnly) {
        //stay in regist form and treat as history
        isRegistForm = true;
        isHistoryForm = true;
        if (patientHistory.size() > 0)
            formHsfo2Visit = (Hsfo2Visit) patientHistory.get(patientHistory.size() - 1);
    }

    if (isHistoryForm) {
        latestHsfo2Visit = formHsfo2Visit;
    } else // create new form
    {
        patientHistorySize = patientHistory.size();

        if (patientHistorySize >= 1) {
            latestHsfo2Visit = (Hsfo2Visit) patientHistory.get(patientHistorySize - 1);
            latestHsfo2Visit.setVisitDateIdToday();
            latestHsfo2Visit.setId(hsfoDAO.getMaxVisitId() + 1);
            cleanNonePrefilledData(latestHsfo2Visit);
            getLabWork(latestHsfo2Visit, hsfo2Patient, ConvertUtil.toInt(patientId));

            //If it's followup form, BP should not be prepopulated. Clean again.
            latestHsfo2Visit.setSBP(0);
            latestHsfo2Visit.setDBP(0);
        } else {
            latestHsfo2Visit = new Hsfo2Visit();
            latestHsfo2Visit.setVisitDateIdToday();
            getLabWork(latestHsfo2Visit, hsfo2Patient, ConvertUtil.toInt(patientId));
        }

    }

    if (isRegistForm) {
        // registration, get data from DemographicData;
        isfirstrecord = "true";

        hsfo2Patient.setPatient_Id(patientId);

        if (!isHistoryForm) {
            hsfo2Patient.setFName(de.getFirstName());
            hsfo2Patient.setLName(de.getLastName());
            hsfo2Patient.setBirthDate(oscar.util.DateUtils.toDate(de.getFormattedDob()));
            hsfo2Patient.setSex(de.getSex());
            hsfo2Patient.setPostalCode(de.getPostal());

            hsfo2Patient.setRegistrationId(HsfoUtil.getRegistrationId());
            latestHsfo2Visit.setVisitDateIdToday();
        }

        request.setAttribute("EmrHCPId1", user);
        request.setAttribute("EmrHCPId2", de.getProviderNo()); // TODO: may need to convert to provider name

        forwardToForm = FORM.registration;
    } else {
        //populate graphy data for followup form. the latestHsfo2Visit already keep the information of last visit.
        isfirstrecord = "false";

        if (!isDisplayGraphs)
            forwardToForm = FORM.flowsheet;
        else {
            // If patientHistory is greater than 1 than fill the graphing arrays
            TimeSeries sbpSeries = new TimeSeries("Systolic Blood Pressure", Day.class);
            TimeSeries dbpSeries = new TimeSeries("Diastolic Blood Pressure", Day.class);
            TimeSeries bmiSeries = new TimeSeries("BMI", Day.class);
            TimeSeries waistSeries = new TimeSeries("Waist", Day.class);
            TimeSeries ldlSeries = new TimeSeries("LDL", Day.class);
            TimeSeries tcHdlSeries = new TimeSeries("TC/HDL", Day.class);
            TimeSeries importanceSeries = new TimeSeries("Importance", Day.class);
            TimeSeries confidenceSeries = new TimeSeries("Confidence", Day.class);

            Map<GraphDesc, TimeSeries> graphDescSeriesMap = new HashMap<GraphDesc, TimeSeries>();
            graphDescSeriesMap.put(new GraphDesc("Systolic Blood Pressure", "Dates", "SBP(mmHg)"), sbpSeries);
            graphDescSeriesMap.put(new GraphDesc("Diastolic Blood Pressure", "Dates", "DBP(mmHg)"), dbpSeries);
            graphDescSeriesMap.put(new GraphDesc("BMI", "Dates", "BMI(kg/m2)"), bmiSeries);
            graphDescSeriesMap.put(new GraphDesc("Waist", "Dates", "Waist(cm)"), waistSeries);
            graphDescSeriesMap.put(new GraphDesc("LDL", "Dates", "LDL(mmol/L)"), ldlSeries);
            {
                GraphDesc tcHdlDesc = new GraphDesc("TC/HDL", "Dates", "TC/HDL(ratio)");
                tcHdlDesc.setFileName("TC_HDL");
                graphDescSeriesMap.put(tcHdlDesc, tcHdlSeries);
            }
            graphDescSeriesMap.put(new GraphDesc("Importance", "Dates", "Importance(1-10)"), importanceSeries);
            graphDescSeriesMap.put(new GraphDesc("Confidence", "Dates", "Confidence(1-10)"), confidenceSeries);

            if (patientHistorySize >= 1) {

                ListIterator patientHistoryIt = patientHistory.listIterator();
                //        int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
                while (patientHistoryIt.hasNext()) {
                    Hsfo2Visit Hsfo2Visit = (Hsfo2Visit) patientHistoryIt.next();
                    //          visitDateArray.add( setDateFull( Hsfo2Visit.getVisitDate_Id() ) );
                    //          visitIdArray.add( "" + Hsfo2Visit.getID() );

                    // ////////
                    final Date visitDate = Hsfo2Visit.getVisitDate_Id();
                    if (visitDate != null) {
                        final Day visitDay = new Day(visitDate);
                        if (Hsfo2Visit.getSBP() != 0) {
                            sbpSeries.addOrUpdate(visitDay, Hsfo2Visit.getSBP());
                        }

                        if (Hsfo2Visit.getDBP() != 0) {
                            dbpSeries.addOrUpdate(visitDay, Hsfo2Visit.getDBP());
                        }

                        if (Hsfo2Visit.getWeight() != 0) {
                            Double bmi = getBmi(Hsfo2Visit, hsfo2Patient);
                            if (bmi > 0)
                                bmiSeries.addOrUpdate(visitDay, bmi);
                        }
                        // modified by victor for waist_unit null bug,2007
                        // if (Hsfo2Visit.getWaist() != 0{
                        if (Hsfo2Visit.getWaist() != 0 && Hsfo2Visit.getWaist_unit() != null) {
                            double waistv = Hsfo2Visit.getWaist();
                            String waistunit = Hsfo2Visit.getWaist_unit();
                            double waist = 0.0;
                            if (waistunit.equals("cm")) {
                                waist = waistv;
                            } else {
                                // 1 inch = 2.54 cm
                                waist = waistv * 2.54;
                            }
                            waistSeries.addOrUpdate(visitDay, waist);
                        }

                        if (Hsfo2Visit.getChange_importance() != 0) {
                            importanceSeries.addOrUpdate(visitDay, Hsfo2Visit.getChange_importance());
                        }

                        if (Hsfo2Visit.getChange_confidence() != 0) {
                            confidenceSeries.addOrUpdate(visitDay, Hsfo2Visit.getChange_confidence());
                        }
                    }

                    final Date labResultDate = Hsfo2Visit.getTC_HDL_LabresultsDate();
                    if (labResultDate != null) {
                        final Day labResultDay = new Day(labResultDate);
                        if (Hsfo2Visit.getTC_HDL() != 0) {
                            tcHdlSeries.addOrUpdate(labResultDay, Hsfo2Visit.getTC_HDL());
                        }

                        if (Hsfo2Visit.getLDL() != 0) {
                            ldlSeries.addOrUpdate(labResultDay, Hsfo2Visit.getLDL());
                        }
                    }

                }

            }

            //generate the graph and export as picture.
            generateGraphs(request, response, graphDescSeriesMap);
            forwardToForm = FORM.graphs;
            ;
        }

    }

    historyList.setPatientHistory(patientHistory);

    // set request attributes to forward to jsp
    request.setAttribute("siteId", OscarProperties.getInstance().getProperty("hsfo2.loginSiteCode", "xxx"));

    request.setAttribute("Hsfo2Patient", hsfo2Patient);
    request.setAttribute("historyList", historyList);
    request.setAttribute("Hsfo2Visit", latestHsfo2Visit); //getDay() is date of week
    request.setAttribute("isFirstRecord", isfirstrecord);

    return mapping.findForward(forwardToForm.name());
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowChartJDialog.java

private void updateROITimeSeries() {
    final Currency localCurrency = org.yccheok.jstock.portfolio.Utils.getLocalCurrency();
    final boolean noCodeAddedToMonitor = this.realTimeStockMonitor.isEmpty();
    final List<Code> codesNeedToAddToRealTimeStockMonitor = new ArrayList<>();

    // Use local variables for thread safe.
    // I don't think we need local variables for thread safe purpose,
    // as we already have synchronized keyword. However, it gives no harm
    // for using local variables. We will just leave them.
    final ActivitySummary _ROISummary = this.ROISummary;
    final TimeSeries _ROITimeSeries = this.ROITimeSeries;

    double _totalROIValue = 0.0;
    for (int i = 0, count = _ROISummary.size(); i < count; i++) {
        final Activities activities = _ROISummary.get(i);
        double amount = 0.0;
        for (int j = 0, count2 = activities.size(); j < count2; j++) {
            final Activity activity = activities.get(j);
            final Activity.Type type = activity.getType();

            final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo);
            double exchangeRate = org.yccheok.jstock.portfolio.Utils.getExchangeRate(
                    this.portfolioManagementJPanel.getPortfolioRealTimeInfo(), localCurrency, stockInfo.code);

            if (type == Activity.Type.Buy) {
                final double quantity = (Double) activity.get(Activity.Param.Quantity);
                if (noCodeAddedToMonitor) {
                    // We might already have last price information in
                    // PortfolioManagementJPanel, we will still request
                    // stock monitor to provide continuous update.
                    codesNeedToAddToRealTimeStockMonitor.add(stockInfo.code);
                    // If PortfolioManagementJPanel already has last price
                    // information, just get it from there.
                    final double lastPrice = this.portfolioManagementJPanel.getStockPrice(stockInfo.code);
                    if (lastPrice != 0.0) {
                        this.codeToPrice.put(stockInfo.code, lastPrice);
                    } else {
                        this.lookUpCodes.add(stockInfo.code);
                    }//from   w  w  w . j a  v a  2 s .c om
                }
                final Double price = this.codeToPrice.get(stockInfo.code);
                if (price != null) {
                    amount += (price * quantity * exchangeRate);
                }
            } else if (type == Activity.Type.Sell) {
                amount += (activity.getAmount() * exchangeRate);
            } else if (type == Activity.Type.Dividend) {
                double dividend = (activity.getAmount() * exchangeRate);
                final Currency stockCurrency = org.yccheok.jstock.portfolio.Utils.getStockCurrency(
                        this.portfolioManagementJPanel.getPortfolioRealTimeInfo(), stockInfo.code);
                if (stockCurrency.isGBX() || stockCurrency.isZAC()) {
                    // Use will input dividend cash in GBP/ZAR instead of GBX/ZAC.
                    dividend = dividend * 100.0;
                }

                amount += dividend;
            } else {
                assert (false);
            }
        } // for (int j = 0, count2 = activities.size(); j < count2; j++)

        _totalROIValue += amount;

        final SimpleDate date = activities.getDate();
        final Date d = date.getTime();
        _ROITimeSeries.addOrUpdate(new Day(d), _totalROIValue);
    } // for (int i = 0, count = _ROISummary.size(); i < count; i++)

    this.totalROIValue = _totalROIValue;

    // We cannot iterate over this.lookUpCodes.
    // realTimeStockMonitor's callback may remove lookUpCodes item during
    // iterating process.
    if (noCodeAddedToMonitor) {
        for (Code code : codesNeedToAddToRealTimeStockMonitor) {
            this.realTimeStockMonitor.addStockCode(code);
        }
        this.realTimeStockMonitor.startNewThreadsIfNecessary();
        this.realTimeStockMonitor.refresh();

        if (this.lookUpCodes.isEmpty()) {
            this.finishLookUpPrice = true;
        }
    }
}

From source file:skoa.helpers.Graficos.java

/******************************************************************
 * Funcion obtenerSerieEvolucion(): obtiene la serie de un fichero*
 ******************************************************************/
private TimeSeries obtenerSerieEvolucion() {
    String naux = "";
    //si la longitud es 20 o 21, se trata de un fichero directo de una consulta A.
    //porque la df puede ser x.x.x o x.x.xx
    if (nombreFichero.length() == 20 || nombreFichero.length() == 21)
        naux = nombreFichero.substring(nombreFichero.indexOf("-") + 3, nombreFichero.indexOf(".txt")); //Saca la DG del nombre del fich.
    //si la longitud es 22, se trata de un fichero de una consulta A previa.
    else if (nombreFichero.length() == 22)
        naux = nombreFichero.substring(nombreFichero.indexOf("-") + 5, nombreFichero.indexOf(".txt"));
    //si la longitud es 23, se trata de un fichero (sin unificar) de una consulta D previa.
    else if (nombreFichero.length() == 23)
        naux = nombreFichero.substring(nombreFichero.indexOf("-") + 6, nombreFichero.indexOf(".txt"));
    //si se trata de un fichero de una consulta B o C previa.
    else if (nombreFichero.indexOf("h") >= 0)
        naux = nombreFichero.substring(nombreFichero.indexOf("h") + 2, nombreFichero.indexOf(".txt"));
    naux = naux.replaceAll("-", "/"); //Para que las DGs sea x/xx/xx en vez de x-xx-xx
    TimeSeries serie = new TimeSeries(naux);
    File archivo = new File(ruta + nombreFichero);
    FileReader fr = null;//from w  w w .j  a  v  a2 s. c o m
    BufferedReader linea = null;
    String line;
    try {
        fr = new FileReader(archivo);
        linea = new BufferedReader(fr); //Se crea para leer las lineas
        int d = 0, m = 0, a = 0, a1 = 0, m1 = 0, d1 = 0, j, h1, h2, h3;
        double e = 0;
        String aux, h, minutos, segundos;
        int min_ant = 0, sec_ant = 0, vez1 = 0; //min_prim mira si es el primero, para comparar ant y act.
        Day day1 = null;
        while ((line = linea.readLine()) != null) { //Lectura del fichero
            int i = line.indexOf("\t");
            String f = line.substring(0, i);
            String valor = line.substring(i + 1);
            //Obtencion del dia, mes y ao de la fecha.
            j = f.indexOf("-");
            aux = f.substring(0, j);
            a = Integer.parseInt(aux);
            f = f.substring(j + 1);
            j = f.indexOf("-");
            aux = f.substring(0, j);
            m = Integer.parseInt(aux);
            f = f.substring(j + 1);
            j = f.indexOf(" ");
            aux = f.substring(0, j);
            d = Integer.parseInt(aux);
            //Obtencion de la hora de la fecha.
            f = f.substring(j + 1);
            if (fechaInicial.contentEquals(""))
                fechaInicial = d + "/" + m + "/" + a + " " + f; //Variable para la grfica
            fechaFinal = d + "/" + m + "/" + a + " " + f;
            j = f.indexOf(":");
            h = f.substring(0, j);
            f = f.substring(j + 1);
            j = f.indexOf(":");
            minutos = f.substring(0, j);
            segundos = f.substring(j + 1);
            if (a1 == 0 & m1 == 0 & d1 == 0) { //Inicializacin: Primera fecha.
                a1 = a;
                m1 = m;
                d1 = d;
                day1 = new Day(d1, m1, a1);
            } else {
                if (a1 != a) {
                    a1 = a;
                    if (m1 != m)
                        m1 = m;
                    if (d1 != d)
                        d1 = d;
                    day1 = new Day(d1, m1, a1);
                } else if (m1 != m) {
                    m1 = m;
                    if (d1 != d)
                        d1 = d;
                    day1 = new Day(d1, m1, a1);
                } else if (d1 != d) {
                    d1 = d;
                    day1 = new Day(d1, m1, a1);
                }
            }
            //Comprueba si es boolean. Si lo es, se le asigna 0 o 1
            //para poder representarlo en la grfica. Si no, su <<valor>>.
            if (posiblesBooleanos(valor, 1))
                e = 1;
            else if (posiblesBooleanos(valor, 0))
                e = 0;
            else { //NO ES UN BOOLEANO.
                int u = valor.indexOf(" ");
                valor = valor.substring(0, u);
                e = Double.parseDouble(valor);
            }
            //Comprobamos que la hora no coincida, para que si coincide, introducir en la serie slo
            //la primera aparicin de la fecha con su valor, por ser este ms representativo segn lo visto.
            if (vez1 == 0) {
                min_ant = h1 = Integer.parseInt(minutos); //minutos
                h2 = Integer.parseInt(h); //hora
                sec_ant = h3 = Integer.parseInt(segundos); //segundos
                serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                vez1 = 1;
            } else {
                h1 = Integer.parseInt(minutos); //minutos
                h2 = Integer.parseInt(h); //hora
                h3 = Integer.parseInt(segundos); //segundos
                if (min_ant == h1) { //Si el minuto es =, comprobamos los segundos
                    if (sec_ant == h3) {
                    } //Si los segundos son =, no se introduce nada en la serie.
                    else { //Si los segundos son !=, se introduce en la serie.
                        serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                        sec_ant = h3;
                    }
                } else { //Si el minuto es !=, se introduce en la serie.
                    serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                    min_ant = h1;
                    sec_ant = h3;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr)
                fr.close(); //Se cierra si todo va bien.
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
    return serie;
}