List of usage examples for org.jfree.data.time Millisecond Millisecond
public Millisecond(Date time)
From source file:pisco.batch.visu.BatchingChartFactory.java
public static TimeSeriesCollection createWFlowtimeDataset(Batch[] batches) { TimeSeries series = new TimeSeries("Cumulated Weighted Flowtime"); ICostAggregator globalCostFunction = CostFactory.makeSumCosts(); series.add(new Millisecond(new Date(0)), 0); for (int i = 0; i < batches.length; i++) { globalCostFunction.addCost(batches[i].getWeightedCompletionTime()); series.add(new Millisecond(new Date(batches[i].getCompletionTime())), globalCostFunction.getTotalCost()); }//from ww w .j av a 2s . c o m TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); return dataset; }
From source file:org.activequant.util.charting.Chart.java
/** * Deletes data points that are older than given time stamp from <em>all datasets</em>. * This allows to keep sliding window of the data with the given width. * //from ww w . ja v a 2 s. c om * @param datasetIndex index of the dataset to truncate. * * @param timeStamp truncation threshold. */ public void deleteBefore(TimeStamp timeStamp) { for (TimeSeries ts : datasets) { int index = ts.getIndex(new Millisecond(timeStamp.getDate())); if (index >= 0) { ts.delete(0, index); } } }
From source file:org.miloss.fgsms.services.rs.impl.reports.broker.QueueDepth.java
@Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try {/*w w w . j a v a 2 s . c o m*/ PreparedStatement cmd = null; ResultSet rs = null; DefaultCategoryDataset set = new DefaultCategoryDataset(); JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append(GetHtmlFormattedHelp() + "<br />"); data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Channel</th><th>Depth</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } String url = Utility.encodeHTML(getPolicyDisplayName(urls.get(i))); double average = 0; data.append("<tr><td>").append(url).append("</td>"); try { cmd = con.prepareStatement( "select avg(queuedepth), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td>"); TimeSeries ts = new TimeSeries(url, Millisecond.class); try { //ok now get the raw data.... cmd = con.prepareStatement( "select utcdatetime,queuedepth, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); while (rs.next()) { //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname")); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(1)); Millisecond m = new Millisecond(gcal.getTime()); //TimeSeriesDataItem t = new TimeSeriesDataItem(m, rs.getLong(2)); //ts.add(t); ts.addOrUpdate(m, rs.getLong(2)); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } col.addSeries(ts); } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col, true, false, false); data.append("</table>"); try { // if (set.getRowCount() != 0) { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, 400); data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); // } } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }
From source file:pt.lsts.neptus.util.bathymetry.TidCachedData.java
public static void test(String[] args) throws Exception { TidReader.main(args);/*from w ww. j a v a 2 s . co m*/ JFreeChart timeSeriesChart = null; TimeSeriesCollection tsc = new TimeSeriesCollection(); ValueMarker marker = new ValueMarker(System.currentTimeMillis()); ValueMarker levelMarker = new ValueMarker(0); String tmpFolder = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator", "/"); File tidFx = new File(tmpFolder + "tmp.tid"); TidCachedData tide = new TidCachedData(tidFx); TimeSeries ts = new TimeSeries(I18n.text("Tide level")); tsc.addSeries(ts); Date sDate = new GregorianCalendar(1993, 9, 28).getTime(); for (double i = -12; i < 12; i += 0.25) { Date d = new Date((long) (sDate.getTime() + (i * 6.45 * 1E3 * 60 * 60))); ts.addOrUpdate(new Millisecond(d), tide.getTidePrediction(d, false)); } JPanel panel = new JPanel(new BorderLayout()); timeSeriesChart = ChartFactory.createTimeSeriesChart(null, null, null, tsc, true, true, true); panel.add(new ChartPanel(timeSeriesChart), BorderLayout.CENTER); timeSeriesChart.getXYPlot().addDomainMarker(marker); levelMarker.setValue(TidePredictionFactory.getTideLevel(new Date())); timeSeriesChart.getXYPlot().addRangeMarker(levelMarker); GuiUtils.testFrame(panel); System.out.println("\n________________________________________"); long start = System.currentTimeMillis(); TidCachedData tcd = new TidCachedData(new File(ConfigFetch.getConfFolder() + "mra/Leixoes.tid")); System.out.println("Loading of " + tcd.getName() + " took " + MathMiscUtils.parseToEngineeringNotation((System.currentTimeMillis() - start) / 1E3, 2) + "s"); }
From source file:org.geoserver.wms.ncwms.GetTimeSeriesResponse.java
@SuppressWarnings("rawtypes") private void writeChart(GetFeatureInfoRequest request, FeatureCollectionType results, OutputStream output, String mimeType) throws IOException { final TimeSeries series = new TimeSeries("time", Millisecond.class); String valueAxisLabel = "Value"; String title = "Time series"; final String timeaxisLabel = "Date / time"; final List collections = results.getFeature(); if (collections.size() > 0) { SimpleFeatureCollection fc = (SimpleFeatureCollection) collections.get(0); title += " of " + fc.getSchema().getName().getLocalPart(); valueAxisLabel = fc.getSchema().getDescription().toString(); try (SimpleFeatureIterator fi = fc.features()) { while (fi.hasNext()) { SimpleFeature f = fi.next(); Date date = (Date) f.getAttribute("date"); Double value = (Double) f.getAttribute("value"); series.add(new Millisecond(date), value); }/*w w w . j a va 2 s. c o m*/ } } XYDataset dataset = new TimeSeriesCollection(series); JFreeChart chart = ChartFactory.createTimeSeriesChart(title, timeaxisLabel, valueAxisLabel, dataset, false, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRenderer(new XYLineAndShapeRenderer()); if (mimeType.startsWith("image/png")) { ChartUtilities.writeChartAsPNG(output, chart, IMAGE_WIDTH, IMAGE_HEIGHT); } else if (mimeType.equals("image/jpg") || mimeType.equals("image/jpeg")) { ChartUtilities.writeChartAsJPEG(output, chart, IMAGE_WIDTH, IMAGE_HEIGHT); } }
From source file:greenapi.ui.charts.LineChartPanelSupport.java
public void fakeEvents(int max) { long l = System.currentTimeMillis(); for (int i = 0; i < 2; i++) { TimeSeries localTimeSeries = (TimeSeries) this.getSeries().get(i); for (int j = 0; j < max; j++) { localTimeSeries.add(new Millisecond(new Date(l)), 0.0D); l -= 500L;/* w w w. j a v a2s. c o m*/ } this.getTimeSeries().addSeries(localTimeSeries); } }
From source file:com.algodefu.yeti.data.Pass.java
private void calculateEquityChartImg() throws IOException { int i = 0;/*from www.jav a 2s.c o m*/ double sum = 0; TimeSeries equity = new TimeSeries("Equity"); // save values in temp array first, then use System.arraycopy to copy non empty values to this.equityArray double[][] tempEquityArr = new double[this.getTrades().length][4]; for (Trade trade : this.getTrades()) { if (trade.getCloseDateTime() != null) { sum += trade.getProfit(); equity.add(new Millisecond(Date.from(trade.getCloseDateTime().toInstant(ZoneOffset.UTC))), sum); tempEquityArr[i][0] = (double) trade.getCloseDateTime().toInstant(ZoneOffset.UTC).toEpochMilli(); tempEquityArr[i][1] = sum; tempEquityArr[i][2] = trade.getTradeID(); tempEquityArr[i][3] = trade.getProfit(); i++; } } this.equityArray = new double[i][4]; System.arraycopy(tempEquityArr, 0, this.equityArray, 0, i); TimeSeriesCollection dataset = new TimeSeriesCollection(equity); JFreeChart chart = ChartFactory.createTimeSeriesChart("", "", "", dataset, false, false, false); chart.getXYPlot().getDomainAxis().setTickLabelsVisible(false); chart.setBorderVisible(true); chart.getXYPlot().setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT); chart.getXYPlot().getRenderer().setSeriesPaint(0, Color.blue); chart.getXYPlot().setBackgroundPaint(Color.white); chart.getXYPlot().setRangeGridlinePaint(Color.gray); chart.getXYPlot().setDomainGridlinePaint(Color.gray); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ChartUtilities.writeChartAsPNG(baos, chart, 320, 180); baos.flush(); this.equityChartByteArray = baos.toByteArray(); } catch (IOException e) { throw e; } }
From source file:in.BBAT.presenter.DualAxisDemo2.java
/** * Creates a sample dataset.// ww w . ja v a2s . co m * * @return The dataset. */ private XYDataset createDataset1() { final TimeSeries s2 = new TimeSeries("Memory", Millisecond.class); for (MemoryEntity ent : ScreenShotView.testCase.getMemoryUsageValues()) { s2.addOrUpdate(new Millisecond(new Date(ent.getTime())), ent.getPercent()); } final TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s2); return dataset; }
From source file:org.mwc.cmap.LiveDataMonitor.views.LiveDataMonitor.java
/** * The constructor./*from ww w. jav a2 s .co m*/ */ public LiveDataMonitor() { _attListener = new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { // aah, is this for the scenario we're watching if (_myIndexedAttr != null) if (evt.getSource() == _myIndexedAttr.index) { final DataDoublet newD = (DataDoublet) evt.getNewValue(); final long time = newD.getTime(); final Object newValue = newD.getValue(); if (newValue instanceof Number) { final Number value = (Number) newValue; // and store it final TimeSeriesCollection coll = (TimeSeriesCollection) _chart.getXYPlot() .getDataset(); TimeSeries tmpSeries; if (coll == null) { final TimeSeriesCollection dataset = new TimeSeriesCollection(); tmpSeries = new TimeSeries(_watchedAttr.getName()); dataset.addSeries(tmpSeries); // add to series in different thread... Display.getDefault().asyncExec(new Runnable() { public void run() { _chart.getXYPlot().setDataset(dataset); } }); } else { tmpSeries = coll.getSeries(0); } final TimeSeries series = tmpSeries; // add to series in current thread, accepting it will slow down // the // UI Display.getDefault().syncExec(new Runnable() { public void run() { // are we still open?i if (!_chartFrame.isDisposed()) { // sure, go for it, series.addOrUpdate(new Millisecond(new Date(time)), value); } } }); } } } }; }
From source file:it.marcoberri.mbmeteo.action.chart.Get.java
/** * Processes requests for both HTTP/* w w w . j a v a2 s.c o m*/ * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("start : " + this.getClass().getName()); final HashMap<String, String> params = getParams(request.getParameterMap()); final Integer dimy = Default.toInteger(params.get("dimy"), 600); final Integer dimx = Default.toInteger(params.get("dimx"), 800); final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00"); final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00"); final String field = Default.toString(params.get("field"), "outdoorTemperature"); request.getSession().setAttribute("from", params.get("from")); request.getSession().setAttribute("to", params.get("to")); final String cacheKey = getCacheKey(params); if (cacheReadEnable) { final Query q = ds.find(Cache.class); q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName()); final Cache c = (Cache) q.get(); if (c == null) { log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found"); } if (c != null) { log.debug("get file from cache id: " + c.getGridId()); final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS() .findOne(new ObjectId(c.getGridId())); if (imageForOutput != null) { ds.save(c); try { response.setHeader("Content-Length", "" + imageForOutput.getLength()); response.setHeader("Content-Disposition", "inline; filename=\"" + imageForOutput.getFilename() + "\""); final OutputStream out = response.getOutputStream(); final InputStream in = imageForOutput.getInputStream(); final byte[] content = new byte[(int) imageForOutput.getLength()]; in.read(content); out.write(content); in.close(); out.close(); return; } catch (final IOException e) { log.error(e); } } else { log.error("file not in db"); } } } final String titleChart = ChartEnumHelper.getByName(field).getTitle(); final String umChart = ChartEnumHelper.getByName(field).getUm(); final Query q = ds.createQuery(Meteolog.class); final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from); final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to); q.disableValidation().filter("time >=", dFrom).filter("time <=", dTo); final List<Meteolog> meteoLogList = q.asList(); final TimeSeries series = new TimeSeries(umChart); for (Meteolog m : meteoLogList) { final Millisecond t = new Millisecond(m.getTime()); try { //violenza di una reflection final Method method = m.getClass().getMethod(ChartEnumHelper.getByName(field).getMethod()); final Number n = (Number) method.invoke(m); series.add(t, n); } catch (final NoSuchMethodException ex) { log.error(ex); } catch (final InvocationTargetException ex) { log.error(ex); } catch (final IllegalAccessException ex) { log.error(ex); } catch (final SecurityException ex) { log.error(ex); } } final TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); final JFreeChart chart = ChartFactory.createTimeSeriesChart(titleChart, "", umChart, dataset, false, false, false); final XYPlot plot = (XYPlot) chart.getPlot(); final DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy HH:mm")); axis.setVerticalTickLabels(true); if (field.toUpperCase().indexOf("PRESSURE") != -1) { plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax); } final File f = File.createTempFile("mbmeteo", ".jpg"); ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy); try { if (cacheWriteEnable) { final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f); gfsFile.setFilename(f.getName()); gfsFile.save(); final Cache c = new Cache(); c.setServletName(this.getClass().getName()); c.setCacheKey(cacheKey); c.setGridId(gfsFile.getId().toString()); ds.save(c); } response.setContentType("image/jpeg"); response.setHeader("Content-Length", "" + f.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\""); final OutputStream out = response.getOutputStream(); final FileInputStream in = new FileInputStream(f.toString()); final int size = in.available(); final byte[] content = new byte[size]; in.read(content); out.write(content); in.close(); out.close(); } catch (final IOException e) { log.error(e); } finally { f.delete(); } }