List of usage examples for org.jfree.data.time TimeSeries add
public void add(RegularTimePeriod period, Number value)
From source file:de.fau.amos.ChartRenderer.java
/** * //from w w w.j a v a 2 s.c o m * Creates TimeSeriesCollection that provides the basis for a Chart. Is used for forecast. * * @param sYear Selected year. * @param plantId Selected plant. * @param method Is not used. * @param units Is not used. * @return Returns TimeSeriesCollection that provides the basis for a Chart. */ private TimeSeriesCollection createForecastCollection(String sYear, String plantId, String method, String units) { int year = 0; try { year = Integer.parseInt(sYear); } catch (NumberFormatException e) { return new TimeSeriesCollection(); } TimeSeriesCollection collection = new TimeSeriesCollection(); /* * get planned tnf */ TimeSeries planned = new TimeSeries("Planned"); double lastYearKwhPerTnf = 0; ResultSet rs = SQL.queryToResultSet( "select round((select sum(value)from measures where date_trunc('year',measure_time)='" + (year - 1) + "-1-1')/(select sum(amount)from productiondata " + "inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id " + "where date_trunc('year',measure_time)='" + (year - 1) + "-1-1' AND plant_id='" + plantId + "'),4);"); if (rs != null) { try { if (rs.next()) { lastYearKwhPerTnf = rs.getDouble(1); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } String months = ""; for (int i = 1; i <= 12; i++) { months += "sum(m_" + i + ")"; if (i != 12) { months += ", "; } } rs = SQL.queryToResultSet( "select " + months + " from planning_values where planning_year='" + year + "' AND plant_id='" + plantId + "';"); if (rs != null) { try { while (rs.next()) { for (int i = 1; i <= 12; i++) { planned.add(new Month((i), year), rs.getDouble(i) / (lastYearKwhPerTnf != 0 ? lastYearKwhPerTnf : 1)); } } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } collection.addSeries(planned); TimeSeries is = new TimeSeries("Is"); int passedMonths = 0; double lastVal = 0; rs = SQL.queryToResultSet( "select * from (select round((select sum(am) from(select sum(amount)as am,date_trunc('month',measure_time)as zeit " + "from productiondata inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id " + "where productiondata.measure_time >= '" + year + "-01-01 00:00:00' AND productiondata.measure_time < '" + (year + 1) + "-01-01 00:00:00' " + "AND reference_point='t' AND plant_id='" + plantId + "' group by measure_time)as wat where zeit=gruppenZeit group by zeit order by zeit),4), " + "gruppenZeit from(select sum(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from(" + "select sum(value)as wert,control_point_name,date_trunc('month',measure_time)as zeit1 from measures inner join controlpoints " + "on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '" + year + "-01-01 00:00:00' AND measure_time < '" + (year + 1) + "-01-01 00:00:00' AND plant_id='" + plantId + "' group by measure_time,control_point_name)as data group by zeit1,control_point_name) " + "as groupedByTime group by gruppenZeit)as result order by gruppenZeit;"); if (rs != null) { try { while (rs.next()) { passedMonths++; lastVal = rs.getDouble(1) / (lastYearKwhPerTnf != 0 ? lastYearKwhPerTnf : 1); is.add(new Month((passedMonths), year), lastVal); } } catch (SQLException e) { e.printStackTrace(); } } collection.addSeries(is); TimeSeries forecast = new TimeSeries("Forecast"); if (passedMonths != 0) { forecast.add(new Month(passedMonths, year), lastVal); } passedMonths++; double factor = calculateDifferenz(planned, is); for (int i = passedMonths; i <= 12; i++) { forecast.add(new Month((i), year), planned.getValue(i - 1).doubleValue() * factor); } collection.addSeries(forecast); return collection; }
From source file:ucar.unidata.idv.control.chart.TimeSeriesChartWrapper.java
/** * Create the charts/*from ww w . j a va2 s .c o m*/ * * @throws RemoteException On badness * @throws VisADException On badness */ public void loadDatax() throws VisADException, RemoteException { createChart(); times = null; List unitList = new ArrayList(); List dataChoiceWrappers = getDataChoiceWrappers(); datas.clear(); ranges.clear(); try { plot.setIgnoreDataSetChanges(true); plot.clearRangeAxes(); plot.setRangeAxis(0, new NumberAxis(""), false); for (int dataSetIdx = 0; dataSetIdx < plot.getDatasetCount(); dataSetIdx++) { TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(dataSetIdx); dataset.removeAllSeries(); } // plot.clearDatasets(); // dataset.setDomainIsPointsInTime(true); Hashtable props = new Hashtable(); props.put(TrackDataSource.PROP_TRACKTYPE, TrackDataSource.ID_TIMETRACE); AxisLocation lastSide = AxisLocation.BOTTOM_OR_RIGHT; for (int paramIdx = 0; paramIdx < dataChoiceWrappers.size(); paramIdx++) { DataChoiceWrapper wrapper = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx); DataChoice dataChoice = wrapper.getDataChoice(); FlatField data = getFlatField((FieldImpl) dataChoice.getData(null, props)); Set domainSet = data.getDomainSet(); double[][] domain = domainSet.getDoubles(false); double[][] samples = data.getValues(false); double[] var = samples[0]; Unit unit = ucar.visad.Util.getDefaultRangeUnits(data)[0]; Unit displayUnit = null; if (unit != null) { displayUnit = getDisplayControl().getDisplayConventions().getDisplayUnit(dataChoice.getName(), null); if ((displayUnit != null) && !displayUnit.equals(unit)) { var = displayUnit.toThis(var, unit); unit = displayUnit; } } unitList.add(unit); double[] timeValues = getTimeValues(samples, (FlatField) data); double[][] result = filterData(var, timeValues); var = result[0]; timeValues = result[1]; TimeSeries series = new TimeSeries(dataChoice.getName() + ((unit == null) ? "" : " [" + unit + "]"), FixedMillisecond.class); //TODO: Find the lat/lon/alt index in the domain times = timeValues; lats = domain[0]; lons = domain[1]; alts = domain[2]; datas.add(var); long t1 = System.currentTimeMillis(); double min = 0; double max = 0; for (int i = 0; i < var.length; i++) { Date dttm = new Date((long) (timeValues[i])); // series.addOrUpdate(new FixedMillisecond(dttm), var[i]); series.add(new FixedMillisecond(dttm), var[i]); if ((i == 0) || (var[i] < min)) { min = var[i]; } if ((i == 0) || (var[i] > max)) { max = var[i]; } } ranges.add(new ucar.unidata.util.Range(min, max)); long t2 = System.currentTimeMillis(); // System.err.println ("\t time to add:" + (t2-t1)); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.setDomainIsPointsInTime(true); dataset.addSeries(series); NumberAxis rangeAxis = new NumberAxis(wrapper.getLabel(unit)); plot.setRangeAxis(paramIdx, rangeAxis, false); plot.setDataset(paramIdx, dataset); XYItemRenderer renderer = doMakeRenderer(); plot.setRenderer(paramIdx, renderer); plot.mapDatasetToRangeAxis(paramIdx, paramIdx); Color c = wrapper.getColor(paramIdx); rangeAxis.setLabelPaint(c); renderer.setSeriesPaint(0, c); renderer.setSeriesStroke(0, wrapper.getLineState().getStroke()); AxisLocation side; if (wrapper.getSide() == wrapper.SIDE_UNDEFINED) { if (lastSide == AxisLocation.TOP_OR_LEFT) { side = AxisLocation.BOTTOM_OR_RIGHT; } else { side = AxisLocation.TOP_OR_LEFT; } } else if (wrapper.getSide() == wrapper.SIDE_LEFT) { side = AxisLocation.TOP_OR_LEFT; } else { side = AxisLocation.BOTTOM_OR_RIGHT; } lastSide = side; plot.setRangeAxisLocation(paramIdx, side); } } catch (Exception exc) { LogUtil.logException("Error creating data set", exc); return; } if (dataChoiceWrappers.size() == 0) { NumberAxis axis = new NumberAxis(""); plot.setRangeAxis(0, axis, false); ValueAxis timeAxis = doMakeDateAxis(); plot.setDomainAxis(0, timeAxis, false); } plot.setIgnoreDataSetChanges(false); try { setLocationPositions(); } catch (Exception exc) { LogUtil.logException("Error creating wayPoints", exc); } }
From source file:edu.ucla.stat.SOCR.chart.ChartGenerator_JTable.java
private XYDataset createXYDataset_Time(String time_type) { //System.out.println("timetype="+time_type); String[][] x = new String[xyLength][no_series]; double[][] y = new double[xyLength][no_series]; for (int index = 0; index < no_series; index++) for (int i = 0; i < xyLength; i++) x[i][index] = indepValues[i][index]; for (int index = 0; index < no_series; index++) for (int i = 0; i < xyLength; i++) y[i][index] = Double.parseDouble(depValues[i][index]); TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeries series; for (int i = 0; i < no_series; i++) { String serieName = independentHeaders[i].substring(0, independentHeaders[i].lastIndexOf(":")); if (time_type.equalsIgnoreCase("Day")) series = new TimeSeries(serieName, Day.class); else if (time_type.equalsIgnoreCase("Minute")) series = new TimeSeries(serieName, Minute.class); else if (time_type.equalsIgnoreCase("Month")) series = new TimeSeries(serieName, Month.class); else//from w ww . j av a2 s .co m series = new TimeSeries(serieName); for (int j = 0; j < xyLength; j++) { if (time_type.equalsIgnoreCase("Day")) series.add(DateParser.parseDay(x[j][i]), y[j][i]); else if (time_type.equalsIgnoreCase("Minute")) series.add(DateParser.parseMinute(x[j][i]), y[j][i]); else if (time_type.equalsIgnoreCase("Month")) series.add(DateParser.parseMonth(x[j][i]), y[j][i]); //System.out.println("adding :("+x[j][i]+","+y[j][i]+","+independentHeaders[i]+")" ); } dataset.addSeries(series); } return dataset; }
From source file:com.planetmayo.debrief.satc_rcp.views.MaintainContributionsView.java
protected void redoOwnshipStates() { if (legPlot == null) return;/* w ww . j a v a2 s.c o m*/ boolean showCourses = true; if (showOSCourse != null) showCourses = showOSCourse.getSelection(); java.awt.Color courseCol = java.awt.Color.blue.darker().darker(); java.awt.Color speedCol = java.awt.Color.blue.brighter().brighter(); // ok, now loop through and set them long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; // clear any datasets legPlot.setDataset(0, null); legPlot.setDataset(1, null); // hmm, actually we have to remove any target leg markers @SuppressWarnings("unchecked") Collection<IntervalMarker> markers = legPlot.getDomainMarkers(Layer.BACKGROUND); if (markers != null) { ArrayList<IntervalMarker> markersToDelete = new ArrayList<IntervalMarker>(markers); Iterator<IntervalMarker> mIter = markersToDelete.iterator(); while (mIter.hasNext()) { IntervalMarker im = mIter.next(); legPlot.removeDomainMarker(im); } } // hey, does it have any ownship legs? TimeSeriesCollection tscC = new TimeSeriesCollection(); TimeSeriesCollection tscS = new TimeSeriesCollection(); TimeSeriesCollection tscCLegs = new TimeSeriesCollection(); TimeSeriesCollection tscSLegs = new TimeSeriesCollection(); TimeSeries courses = new TimeSeries("Course"); TimeSeries bearings = new TimeSeries("Bearings"); TimeSeries speeds = new TimeSeries("Speed"); TimeSeries courseLegs = new TimeSeries("Course (leg)"); TimeSeries speedLegs = new TimeSeries("Speed (leg)"); Iterator<BaseContribution> conts = activeSolver.getContributions().iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; Iterator<LegOfData> lIter = null; LegOfData thisLeg = null; if (bmc.getOwnshipLegs() != null) { lIter = bmc.getOwnshipLegs().iterator(); thisLeg = lIter.next(); } List<HostState> hostStates = bmc.getHostState(); if (hostStates != null) { Iterator<HostState> stateIter = hostStates.iterator(); while (stateIter.hasNext()) { BearingMeasurementContribution.HostState hostState = stateIter.next(); long thisTime = hostState.time; double thisCourse = hostState.courseDegs; if (showCourses) courses.add(new FixedMillisecond(thisTime), thisCourse); double thisSpeed = hostState.speedKts; speeds.add(new FixedMillisecond(thisTime), thisSpeed); startTime = Math.min(thisTime, startTime); endTime = Math.max(thisTime, endTime); // sort out if this is in a leg or not if (thisLeg != null) { if (thisTime > thisLeg.getEnd() && lIter.hasNext()) { thisLeg = lIter.next(); } else { if (thisTime >= thisLeg.getStart()) { speedLegs.add(new FixedMillisecond(thisTime), thisSpeed); if (showCourses) courseLegs.add(new FixedMillisecond(thisTime), thisCourse); } } } } } // also, we wish to show the bearings from the BMC Iterator<BMeasurement> cuts = bmc.getMeasurements().iterator(); while (cuts.hasNext()) { BearingMeasurementContribution.BMeasurement measurement = cuts.next(); if (measurement.isActive()) { long thisT = measurement.getDate().getTime(); bearings.add(new FixedMillisecond(thisT), Math.toDegrees(Math.abs(measurement.getBearingRads()))); } } } } // HEY, also shade the ownship legs conts = activeSolver.getContributions().iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) { if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; Iterator<LegOfData> lIter = null; if (bmc.getOwnshipLegs() != null) { int ctr = 1; lIter = bmc.getOwnshipLegs().iterator(); while (lIter.hasNext()) { LegOfData thisL = lIter.next(); long thisStart = thisL.getStart(); long thisFinish = thisL.getEnd(); java.awt.Color transCol = new java.awt.Color(0, 0, 255, 12); final Marker bst = new IntervalMarker(thisStart, thisFinish, transCol, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel("O/S-" + ctr++); bst.setLabelAnchor(RectangleAnchor.TOP_LEFT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.TOP_LEFT); legPlot.addDomainMarker(bst, Layer.BACKGROUND); } } } } } tscS.addSeries(speeds); tscSLegs.addSeries(speedLegs); tscC.addSeries(bearings); if (showCourses) { tscC.addSeries(courses); tscCLegs.addSeries(courseLegs); } legPlot.setDataset(0, null); legPlot.setDataset(1, null); legPlot.setDataset(2, null); legPlot.setDataset(3, null); legPlot.setDataset(0, tscC); legPlot.setDataset(1, tscS); legPlot.setDataset(2, tscCLegs); legPlot.setDataset(3, tscSLegs); final NumberAxis axis2 = new NumberAxis("Speed (Kts)"); legPlot.setRangeAxis(1, axis2); legPlot.mapDatasetToRangeAxis(1, 1); legPlot.mapDatasetToRangeAxis(3, 1); legPlot.getRangeAxis(0).setLabel("Crse/Brg (Degs)"); legPlot.mapDatasetToRangeAxis(0, 0); legPlot.mapDatasetToRangeAxis(2, 0); final XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); lineRenderer1.setSeriesPaint(1, courseCol); lineRenderer1.setSeriesShape(1, ShapeUtilities.createDiamond(0.1f)); lineRenderer1.setSeriesPaint(0, java.awt.Color.RED); lineRenderer1.setSeriesShape(0, ShapeUtilities.createDiamond(2f)); final XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer(true, false); lineRenderer2.setSeriesPaint(0, speedCol); final XYLineAndShapeRenderer lineRenderer3 = new XYLineAndShapeRenderer(false, true); lineRenderer3.setSeriesPaint(0, courseCol); lineRenderer3.setSeriesShape(0, ShapeUtilities.createUpTriangle(2f)); final XYLineAndShapeRenderer lineRenderer4 = new XYLineAndShapeRenderer(false, true); lineRenderer4.setSeriesPaint(0, speedCol); lineRenderer4.setSeriesShape(0, ShapeUtilities.createDownTriangle(2f)); // ok, and store them legPlot.setRenderer(0, lineRenderer1); legPlot.setRenderer(1, lineRenderer2); legPlot.setRenderer(2, lineRenderer3); legPlot.setRenderer(3, lineRenderer4); if (startTime != Long.MAX_VALUE) legPlot.getDomainAxis().setRange(startTime, endTime); // ok - get the straight legs to sort themselves out // redoStraightLegs(); }
From source file:edu.ucla.stat.SOCR.chart.ChartGenerator_JTable.java
private IntervalXYDataset createIntervalXYDataset_Time(String timeType) { String[][] x = new String[xyLength][no_series]; double[][] y = new double[xyLength][no_series]; for (int index = 0; index < no_series; index++) { for (int i = 0; i < xyLength; i++) x[i][index] = indepValues[i][index]; }/*from www.j a va2 s. com*/ for (int index = 0; index < no_series; index++) for (int i = 0; i < xyLength; i++) y[i][index] = Double.parseDouble(depValues[i][index]); TimeSeriesCollection collection = new TimeSeriesCollection(); TimeSeries series; SimpleDateFormat df = new SimpleDateFormat(); for (int ind = 0; ind < no_series; ind++) { int start_ind = independentHeaders[ind].lastIndexOf(":"); if (start_ind < 0) start_ind = 0; int start_dep = dependentHeaders[ind].lastIndexOf(":"); if (start_dep < 0) start_dep = 0; String serieName = independentHeaders[ind].substring(0, start_ind); if (serieName.length() == 0) serieName = "Serie" + ind; String indName = independentHeaders[ind].substring(start_ind + 1); String depName = dependentHeaders[ind].substring(start_dep + 1); try { if (timeType.equalsIgnoreCase("year")) { series = new TimeSeries(serieName, Year.class); for (int i = 0; i < xyLength; i++) series.add(new Year(Integer.parseInt(x[i][ind])), y[i][ind]); //System.out.println("adding:"+serieName); // collection.setDomainIsPointsInTime(false); collection.addSeries(series); } else if (timeType.equalsIgnoreCase("month")) { series = new TimeSeries(serieName, Month.class); for (int i = 0; i < xyLength; i++) series.add(DateParser.parseMonth(x[i][ind]), y[i][ind]); // System.out.println("adding:"+serieName); //collection.setDomainIsPointsInTime(false); collection.addSeries(series); } else if (timeType.equalsIgnoreCase("day")) { series = new TimeSeries(serieName, Day.class); for (int i = 0; i < xyLength; i++) series.add(DateParser.parseDay(x[i][ind]), y[i][ind]); // System.out.println("adding:"+serieName); //collection.setDomainIsPointsInTime(false); collection.addSeries(series); } else if (timeType.equalsIgnoreCase("minute")) { series = new TimeSeries(serieName, Minute.class); for (int i = 0; i < xyLength; i++) series.add(DateParser.parseMinute(x[i][ind]), y[i][ind]); // System.out.println("adding:"+serieName); // collection.setDomainIsPointsInTime(false); collection.addSeries(series); } } catch (NumberFormatException e2) { System.out.println("Wrong data format, enter integer for Year please. Check the Mapping also."); return null; } } return collection; }
From source file:com.afunms.system.manage.equipManager.java
/** * Creates a sample dataset.//from www. ja v a2 s. c o m * * @param count * the item count. * * @return the dataset. */ private XYDataset createForceDataset(final int count) { final TimeSeriesCollection dataset = new TimeSeriesCollection(); final TimeSeries s1 = new TimeSeries("", Minute.class); RegularTimePeriod start = new Minute(); double force = 3.0; for (int i = 0; i < count; i++) { s1.add(start, force); start = start.next(); force = Math.max(0.5, force + (Math.random() - 0.5) * 0.5); } dataset.addSeries(s1); return dataset; }
From source file:com.afunms.system.manage.equipManager.java
/** * Creates a sample dataset.//from w w w.ja v a 2 s .c om * * @param count * the item count. * * @return the dataset. */ private XYDataset createDirectionDataset(final int count) { final TimeSeriesCollection dataset = new TimeSeriesCollection(); final TimeSeries s1 = new TimeSeries("", Minute.class); RegularTimePeriod start = new Minute(); double direction = 180.0; for (int i = 0; i < count; i++) { s1.add(start, direction); start = start.next(); direction = direction + (Math.random() - 0.5) * 15.0; if (direction < 0.0) { direction = direction + 360.0; } else if (direction > 360.0) { direction = direction - 360.0; } } dataset.addSeries(s1); return dataset; }
From source file:gov.llnl.lc.infiniband.opensm.plugin.gui.chart.SimpleXY_ChartPanel.java
private XYDataset createDeltaDataset(OSM_FabricDeltaCollection deltaHistory, Object userElement, String seriesName) {// www . j av a2 s.c om // PortCounterName portCounter = null; // MAD_Counter madCounter = null; // OsmEvent osmEvent = null; // // if((Port != null) && (userElement instanceof PortCounterName)) // portCounter = (PortCounterName)userElement; // // if((MAD_Stats != null) && (userElement instanceof MAD_Counter)) // madCounter = (MAD_Counter)userElement; // // if((EventStats != null) && (userElement instanceof OsmEvent)) // osmEvent = (OsmEvent)userElement; // TimeSeries series = new TimeSeries(seriesName); // iterate through the collection, and build up a time series for (int j = 0; j < deltaHistory.getSize(); j++) { OSM_FabricDelta delta = deltaHistory.getOSM_FabricDelta(j); // the dataset is a timeseries collection long lValue = 0; TimeStamp ts = null; RegularTimePeriod ms = null; if (Port != null) { // find the desired port counter, in this instance LinkedHashMap<String, PFM_PortChange> pcL = delta.getPortChanges(); PFM_PortChange pC = pcL.get(OSM_Port.getOSM_PortKey(Port)); lValue = pC.getDelta_port_counter(PortCounter); ts = pC.getCounterTimeStamp(); // correct for missing time periods int deltaSeconds = delta.getDeltaSeconds(); long sweepPeriod = delta.getFabric2().getPerfMgrSweepSecs(); if (sweepPeriod < deltaSeconds) { // graph is reported as counts per period, so if the period is too long, interpolate lValue *= sweepPeriod; lValue /= deltaSeconds; } } else if (MADCounter != null) { // find the desired MAD counter, in this instance OSM_Stats mStats = delta.getStatChanges(); lValue = MADCounter.getCounterValue(mStats); ts = delta.getTimeStamp(); // correct for missing time periods int deltaSeconds = delta.getDeltaSeconds(); long sweepPeriod = delta.getFabric2().getPerfMgrSweepSecs(); if (sweepPeriod < deltaSeconds) { // graph is reported as counts per period, so if the period is too long, interpolate lValue *= sweepPeriod; lValue /= deltaSeconds; } } else if (EventType != null) { // find the desired Event counter, in this instance OSM_EventStats eStats = delta.getEventChanges(); lValue = eStats.getCounter(EventType); ts = delta.getTimeStamp(); // correct for missing time periods int deltaSeconds = delta.getDeltaSeconds(); long sweepPeriod = delta.getFabric2().getPerfMgrSweepSecs(); if (sweepPeriod < deltaSeconds) { // graph is reported as counts per period, so if the period is too long, interpolate lValue *= sweepPeriod; lValue /= deltaSeconds; } } else continue; ms = new FixedMillisecond(ts.getTimeInMillis()); series.add(ms, (double) lValue); } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); return dataset; }
From source file:com.peterbochs.instrument.InstrumentPanel.java
private void runTimer() { if (interruptTimer != null) { interruptTimer.cancel();//from ww w . j a v a 2 s . c om } interruptTimer = new Timer(); interruptTimer.schedule(new TimerTask() { Hashtable<Long, Integer> oldInterruptRecords; public void run() { try { synchronized (allSeries) { ArrayList<Long> list = Collections.list(InterruptSocketServer.interruptRecords.keys()); Date d = new Date(); // int noOfFrame = getTimeframe() / getSpeed(); oldInterruptRecords = (Hashtable<Long, Integer>) InterruptSocketServer.interruptRecords .clone(); ((InterruptTableModel) jInterruptTable.getModel()).fireTableDataChanged(); for (int x = 0; x < list.size(); x++) { long interuptNoL = list.get(x); int interruptNo = (int) interuptNoL; if (allSeries.get(interruptNo) != null) { TimeSeries series = allSeries.get(interruptNo); List<TimeSeriesDataItem> items = series.getItems(); for (int z = items.size() - 1; z >= 0; z--) { RegularTimePeriod pd = items.get(z).getPeriod(); Calendar cal1 = Calendar.getInstance(); cal1.add(Calendar.MILLISECOND, -1 * getTimeframe()); Calendar cal2 = Calendar.getInstance(); cal2.setTime(pd.getEnd()); if (cal1.after(cal2)) { series.delete(pd); } } series.add(new Millisecond(d), InterruptSocketServer.interruptRecords.get(interuptNoL) - oldInterruptRecords.get(interuptNoL)); // InterruptSocketServer.interruptRecords.put(interuptNoL, 0); } else { TimeSeries newSeries = new TimeSeries("Int 0x" + Integer.toHexString(interruptNo)); interruptDataset.addSeries(newSeries); allSeries.put(interruptNo, newSeries); } } interruptChart.fireChartChanged(); } } catch (Exception ex) { ex.printStackTrace(); } } }, 0, getSpeed()); }
From source file:nu.nethome.home.items.web.GraphServlet.java
/** * This is the main enterence point of the class. This is called when a http request is * routed to this servlet.//from w w w .ja va2s .c o m */ public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream p = res.getOutputStream(); Date startTime = null; Date stopTime = null; // Analyse arguments String fileName = req.getParameter("file"); if (fileName != null) fileName = getFullFileName(fromURL(fileName)); String startTimeString = req.getParameter("start"); String stopTimeString = req.getParameter("stop"); try { if (startTimeString != null) { startTime = m_Format.parse(startTimeString); } if (stopTimeString != null) { stopTime = m_Format.parse(stopTimeString); } } catch (ParseException e1) { e1.printStackTrace(); } String look = req.getParameter("look"); if (look == null) look = ""; TimeSeries timeSeries = new TimeSeries("Data", Minute.class); // Calculate time window Calendar cal = Calendar.getInstance(); Date currentTime = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date startOfDay = cal.getTime(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date startOfWeek = cal.getTime(); cal.set(Calendar.DAY_OF_MONTH, 1); Date startOfMonth = cal.getTime(); cal.set(Calendar.MONTH, Calendar.JANUARY); Date startOfYear = cal.getTime(); // if (startTime == null) startTime = startOfWeek; if (stopTime == null) stopTime = currentTime; if (startTime == null) startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L); try { // Open the data file File logFile = new File(fileName); Scanner fileScanner = new Scanner(logFile); Long startTimeMs = startTime.getTime(); Long month = 1000L * 60L * 60L * 24L * 30L; boolean doOptimize = true; boolean justOptimized = false; try { while (fileScanner.hasNext()) { try { // Get next log entry String line = fileScanner.nextLine(); if (line.length() > 21) { // Adapt the time format String minuteTime = line.substring(0, 16).replace('.', '-'); // Parse the time stamp Minute min = Minute.parseMinute(minuteTime); // Ok, this is an ugly optimization. If the current time position in the file // is more than a month (30 days) ahead of the start of the time window, we // quick read two weeks worth of data, assuming that there is 4 samples per hour. // This may lead to scanning past start of window if there are holes in the data // series. if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) { for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) { fileScanner.nextLine(); } justOptimized = true; continue; } // Detect if we have scanned past the window start position just after an optimization scan. // If this is the case it may be because of the optimization. In that case we have to switch // optimization off and start over. if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) { logFile = new File(fileName); fileScanner = new Scanner(logFile); doOptimize = false; continue; } justOptimized = false; // Check if value is within time window if ((min.getFirstMillisecond() > startTimeMs) && (min.getFirstMillisecond() < stopTime.getTime())) { // Parse the value double value = Double.parseDouble((line.substring(20)).replace(',', '.')); // Add the entry timeSeries.add(min, value); doOptimize = false; } } } catch (SeriesException se) { // Bad entry, for example due to duplicates at daylight saving time switch } catch (NumberFormatException nfe) { // Bad number format in a line, try to continue } } } catch (Exception e) { System.out.println(e.toString()); } finally { fileScanner.close(); } } catch (FileNotFoundException f) { System.out.println(f.toString()); } // Create a collection for plotting TimeSeriesCollection data = new TimeSeriesCollection(); data.addSeries(timeSeries); JFreeChart chart; int xSize = 750; int ySize = 450; // Customize colors and look of the Graph. if (look.equals("mobtemp")) { // Look for the mobile GUI chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false); XYPlot plot = chart.getXYPlot(); ValueAxis timeAxis = plot.getDomainAxis(); timeAxis.setAxisLineVisible(false); ValueAxis valueAxis = plot.getRangeAxis(0); valueAxis.setAxisLineVisible(false); xSize = 175; ySize = 180; } else { // Create a Chart with time range as heading SimpleDateFormat localFormat = new SimpleDateFormat(); String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime); chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false); Paint background = new Color(0x9D8140); chart.setBackgroundPaint(background); TextTitle title = chart.getTitle(); // fix title Font titleFont = title.getFont(); titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0); title.setFont(titleFont); title.setPaint(Color.darkGray); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(background); plot.setDomainGridlinePaint(Color.darkGray); ValueAxis timeAxis = plot.getDomainAxis(); timeAxis.setAxisLineVisible(false); ValueAxis valueAxis = plot.getRangeAxis(0); valueAxis.setAxisLineVisible(false); plot.setRangeGridlinePaint(Color.darkGray); XYItemRenderer renderer = plot.getRenderer(0); renderer.setSeriesPaint(0, Color.darkGray); xSize = 750; ySize = 450; } try { res.setContentType("image/png"); res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "no-cache"); res.setStatus(HttpServletResponse.SC_OK); ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } p.flush(); p.close(); return; }