Search in sources :

Example 66 with TimeSeriesCollection

use of org.jfree.data.time.TimeSeriesCollection in project pentaho-platform by pentaho.

the class TimeSeriesCollectionChartComponent method getXmlContent.

@Override
public Document getXmlContent() {
    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("baseUrl", requestContext.getContextPath());
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("fullyQualifiedServerUrl", PentahoSystem.getApplicationContext().getFullyQualifiedServerURL());
    // $NON-NLS-1$
    String mapName = "chart" + AbstractChartComponent.chartCount++;
    Document chartDefinition = jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);
    if (chartDefinition == null) {
        // $NON-NLS-1$
        Element errorElement = result.addElement("error");
        errorElement.addElement("title").setText(// $NON-NLS-1$ //$NON-NLS-2$
        Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART"));
        // $NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", definitionPath);
        // $NON-NLS-1$
        errorElement.addElement("message").setText(message);
        error(message);
        return result;
    }
    // create a pie definition from the XML definition
    dataDefinition = createChart(chartDefinition);
    if (dataDefinition == null) {
        // $NON-NLS-1$
        Element errorElement = result.addElement("error");
        errorElement.addElement("title").setText(// $NON-NLS-1$ //$NON-NLS-2$
        Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART"));
        // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0002_CHART_DATA_MISSING", actionPath);
        // $NON-NLS-1$
        errorElement.addElement("message").setText(message);
        // System .out.println( result.asXML() );
        return result;
    }
    // create an image for the dial using the JFreeChart engine
    PrintWriter printWriter = new PrintWriter(new StringWriter());
    // we'll dispay the title in HTML so that the dial image does not have
    // to
    // accommodate it
    // $NON-NLS-1$
    String chartTitle = "";
    try {
        if (width == -1) {
            // $NON-NLS-1$
            width = Integer.parseInt(chartDefinition.selectSingleNode("/chart/width").getText());
        }
        if (height == -1) {
            // $NON-NLS-1$
            height = Integer.parseInt(chartDefinition.selectSingleNode("/chart/height").getText());
        }
    } catch (Exception e) {
    // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) != null) {
        // $NON-NLS-1$
        urlTemplate = // $NON-NLS-1$
        chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME).getText();
    }
    if (chartDefinition.selectSingleNode("/chart/paramName") != null) {
        // $NON-NLS-1$
        // $NON-NLS-1$
        paramName = chartDefinition.selectSingleNode("/chart/paramName").getText();
    }
    // $NON-NLS-1$
    Element root = result.addElement("charts");
    TimeSeriesCollection chartDataDefinition = (TimeSeriesCollection) dataDefinition;
    if (chartDataDefinition.getSeriesCount() > 0) {
        // create temporary file names
        String[] tempFileInfo = createTempFile();
        String fileName = tempFileInfo[AbstractChartComponent.FILENAME_INDEX];
        String filePathWithoutExtension = tempFileInfo[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX];
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        JFreeChartEngine.saveChart(chartDataDefinition, chartTitle, "", filePathWithoutExtension, width, height, JFreeChartEngine.OUTPUT_PNG, printWriter, info, // $NON-NLS-1$
        this);
        applyOuterURLTemplateParam();
        populateInfo(info);
        // $NON-NLS-1$
        Element chartElement = root.addElement("chart");
        // $NON-NLS-1$
        chartElement.addElement("mapName").setText(mapName);
        // $NON-NLS-1$
        chartElement.addElement("width").setText(Integer.toString(width));
        // $NON-NLS-1$
        chartElement.addElement("height").setText(Integer.toString(height));
        for (int row = 0; row < chartDataDefinition.getSeriesCount(); row++) {
            for (int column = 0; column < chartDataDefinition.getItemCount(row); column++) {
                Number value = chartDataDefinition.getY(row, column);
                Comparable rowKey = chartDataDefinition.getSeriesKey(row);
                RegularTimePeriod columnKey = chartDataDefinition.getSeries(row).getTimePeriod(column);
                // $NON-NLS-1$
                Element valueElement = chartElement.addElement("value2D");
                // $NON-NLS-1$
                valueElement.addElement("value").setText(value.toString());
                // $NON-NLS-1$
                valueElement.addElement("row-key").setText(rowKey.toString());
                // $NON-NLS-1$
                valueElement.addElement("column-key").setText(columnKey.toString());
            }
        }
        String mapString = ImageMapUtilities.getImageMap(mapName, info);
        // $NON-NLS-1$
        chartElement.addElement("imageMap").setText(mapString);
        // $NON-NLS-1$
        chartElement.addElement("image").setText(fileName);
    }
    return result;
}
Also used : Element(org.dom4j.Element) Document(org.dom4j.Document) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) StandardEntityCollection(org.jfree.chart.entity.StandardEntityCollection) StringWriter(java.io.StringWriter) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) ChartRenderingInfo(org.jfree.chart.ChartRenderingInfo) RegularTimePeriod(org.jfree.data.time.RegularTimePeriod) PrintWriter(java.io.PrintWriter)

Example 67 with TimeSeriesCollection

use of org.jfree.data.time.TimeSeriesCollection in project MtgDesktopCompanion by nicho92.

the class SealedHistoryPricesPanel method getDataSet.

@Override
public TimeSeriesCollection getDataSet() {
    var dataset = new TimeSeriesCollection();
    var series1 = new TimeSeries(title);
    if (cpVariations != null)
        for (Entry<Date, Double> d : cpVariations.entrySet()) series1.add(new Day(d.getKey()), d.getValue().doubleValue());
    dataset.addSeries(series1);
    return dataset;
}
Also used : Entry(java.util.Map.Entry) TimeSeries(org.jfree.data.time.TimeSeries) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) Day(org.jfree.data.time.Day)

Example 68 with TimeSeriesCollection

use of org.jfree.data.time.TimeSeriesCollection in project Stock-Ticker-Project by IsaiahL12.

the class DynamicDataDemo method graph2.

/**
 * Constructs a new demonstration application.
 *
 * @param title  the frame title.
 */
public JPanel graph2(String title, Vector<Double> avgV, Vector<String> time) {
    final TimeSeries high = new TimeSeries("High");
    final TimeSeries average = new TimeSeries("Price");
    final TimeSeries low = new TimeSeries("Low");
    double hold = 0;
    double hold1 = -1;
    double hold2 = 100000000;
    int spacing = 20;
    for (int i = 0; i < avgV.size(); i++) {
        if (avgV.get(i) != -1 && avgV.get(i) != 0) {
            if (hold1 < avgV.get(i)) {
                hold1 = avgV.get(i);
            }
            if (hold2 > avgV.get(i)) {
                hold2 = avgV.get(i);
            // System.out.println(hold2);
            }
            // Date day = new SimpleDateFormat("HH:MM").parse("9:30");
            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse(time.get(i));
                hold = avgV.get(i);
                average.addOrUpdate(new Day(date), round(hold, 2));
                // average.add( null, round(hold,2));
                high.addOrUpdate(new Day(date), round(hold1, 2));
                low.addOrUpdate(new Day(date), round(hold2, 2));
            // high.add(spacing*i, round(hold1,2));
            // low.add(spacing*i, round(hold2,2));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection(high);
    dataset.addSeries(low);
    dataset.addSeries(average);
    JFreeChart chart;
    chart = createChart2(dataset, title);
    chart.getPlot().setBackgroundPaint(Color.BLACK);
    ChartPanel chartPanel = new ChartPanel(chart);
    // chartPanel.overlayChanged(event);
    JPanel content = new JPanel(new BorderLayout());
    content.add(chartPanel);
    // content.add(button, BorderLayout.SOUTH);
    chartPanel.setPreferredSize(new java.awt.Dimension(375, 320));
    // this.add(content);
    return content;
/*
        final XYSeries high = new XYSeries("High");
  	  final XYSeries average = new XYSeries("Price");
  	  final XYSeries low = new XYSeries("Low");
  	  double hold = 0;
  	  double hold1 = -1;
  	  double hold2 = 100000000;
  	  int spacing = 20;
  	  
  	 for (int i =0; i< avgV.size(); i++) {
  		   if (avgV.get(i) != -1 && avgV.get(i) != 0) {
  			   if (hold1 < avgV.get(i)) {
  				   hold1 =  avgV.get(i);
  			   }
  		 
  			   if (hold2 > avgV.get(i)) {
  				   hold2 =  avgV.get(i);
  				   //System.out.println(hold2);
  			   }
  			   
  			  
  			   
  		// Date day = new SimpleDateFormat("HH:MM").parse("9:30");
  		 
  			 hold =  avgV.get(i);
  			average.add(spacing*i, round(hold,2));
  			 high.add(spacing*i, round(hold1,2));
  		 low.add(spacing*i, round(hold2,2));
  		  }
  		  
  	  }
  	  
  	  
  	XYSeriesCollection dataset = new XYSeriesCollection(high); 
    	dataset.addSeries(low);
    	dataset.addSeries(average);
    	JFreeChart chart;
    
    	chart = createChart2(dataset, title);
    	chart.getPlot().setBackgroundPaint( Color.BLACK );
      ChartPanel chartPanel = new ChartPanel(chart);
     // chartPanel.overlayChanged(event);
      
      JPanel content = new JPanel(new BorderLayout());
      content.add(chartPanel);
      //content.add(button, BorderLayout.SOUTH);
      chartPanel.setPreferredSize(new java.awt.Dimension(375, 320));
      //setContentPane(content)
      //this.add(content);
      return content;
      */
}
Also used : JPanel(javax.swing.JPanel) TimeSeries(org.jfree.data.time.TimeSeries) ChartPanel(org.jfree.chart.ChartPanel) Date(java.util.Date) JFreeChart(org.jfree.chart.JFreeChart) BorderLayout(java.awt.BorderLayout) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) Day(org.jfree.data.time.Day)

Example 69 with TimeSeriesCollection

use of org.jfree.data.time.TimeSeriesCollection in project jpsonic by tesshucom.

the class StatusChartController method handleRequest.

// (Millisecond, Date) Not reusable
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
@Override
@GetMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String type = request.getParameter(Attributes.Request.TYPE.value());
    int index = ServletRequestUtils.getIntParameter(request, Attributes.Request.INDEX.value(), 0);
    List<TransferStatus> statuses = Collections.emptyList();
    if ("stream".equals(type)) {
        statuses = statusService.getAllStreamStatuses();
    } else if ("download".equals(type)) {
        statuses = statusService.getAllDownloadStatuses();
    } else if ("upload".equals(type)) {
        statuses = statusService.getAllUploadStatuses();
    }
    if (index < 0 || index >= statuses.size()) {
        return null;
    }
    TransferStatus status = statuses.get(index);
    TimeSeries series = new TimeSeries("Kbps");
    TransferStatus.SampleHistory history = status.getHistory();
    long to = System.currentTimeMillis();
    long from = to - status.getHistoryLengthMillis();
    if (!history.isEmpty()) {
        TransferStatus.Sample previous = history.get(0);
        for (int i = 1; i < history.size(); i++) {
            TransferStatus.Sample sample = history.get(i);
            long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp();
            long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered());
            double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0);
            series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps);
            previous = sample;
        }
    }
    // Compute moving average.
    series = MovingAverage.createMovingAverage(series, "Kbps", 20_000, 5000);
    // Find min and max values.
    double min = 100;
    double max = 250;
    for (Object obj : series.getItems()) {
        TimeSeriesDataItem item = (TimeSeriesDataItem) obj;
        double value = item.getValue().doubleValue();
        if (item.getPeriod().getFirstMillisecond() > from) {
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
    }
    // Add 10% to max value.
    max *= 1.1D;
    // Subtract 10% from min value.
    min *= 0.9D;
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);
    StandardChartTheme theme = (StandardChartTheme) StandardChartTheme.createJFreeTheme();
    Font font = fontLoader.getFont(12F);
    theme.setExtraLargeFont(font);
    theme.setLargeFont(font);
    theme.setRegularFont(font);
    theme.setSmallFont(font);
    theme.apply(chart);
    Color bgColor = getBackground(request);
    chart.setBackgroundPaint(bgColor);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(bgColor);
    Color fgColor = getForeground(request);
    plot.setOutlinePaint(fgColor);
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    plot.setRangeGridlinePaint(fgColor);
    plot.setRangeGridlineStroke(new BasicStroke(0.2f));
    plot.setDomainGridlinePaint(fgColor);
    plot.setDomainGridlineStroke(new BasicStroke(0.2f));
    XYItemRenderer renderer = plot.getRendererForDataset(dataset);
    Color stColor = getStroke(request);
    renderer.setSeriesPaint(0, stColor);
    renderer.setSeriesStroke(0, new BasicStroke(4.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setRange(new DateRange(from, to));
    domainAxis.setTickLabelPaint(fgColor);
    domainAxis.setTickMarkPaint(fgColor);
    domainAxis.setAxisLinePaint(fgColor);
    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setRange(new Range(min, max));
    rangeAxis.setTickLabelPaint(fgColor);
    rangeAxis.setTickMarkPaint(fgColor);
    rangeAxis.setAxisLinePaint(fgColor);
    synchronized (LOCK) {
        ChartUtils.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT);
    }
    return null;
}
Also used : BasicStroke(java.awt.BasicStroke) TimeSeries(org.jfree.data.time.TimeSeries) StandardChartTheme(org.jfree.chart.StandardChartTheme) Color(java.awt.Color) TimeSeriesDataItem(org.jfree.data.time.TimeSeriesDataItem) DateRange(org.jfree.data.time.DateRange) Range(org.jfree.data.Range) Date(java.util.Date) JFreeChart(org.jfree.chart.JFreeChart) Font(java.awt.Font) Millisecond(org.jfree.data.time.Millisecond) DateRange(org.jfree.data.time.DateRange) XYPlot(org.jfree.chart.plot.XYPlot) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) ValueAxis(org.jfree.chart.axis.ValueAxis) TransferStatus(com.tesshu.jpsonic.domain.TransferStatus) XYItemRenderer(org.jfree.chart.renderer.xy.XYItemRenderer) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 70 with TimeSeriesCollection

use of org.jfree.data.time.TimeSeriesCollection in project projectforge by micromata.

the class LiquidityChartBuilder method createBarChart.

/**
 * @param forecast
 * @param settings (next days)
 * @return
 */
public JFreeChart createBarChart(final LiquidityForecast forecast, final LiquidityForecastSettings settings) {
    if (!(settings.getNextDays() > 0 && settings.getNextDays() <= LiquidityForecastSettings.MAX_FORECAST_DAYS)) {
        settings.setNextDays(LiquidityForecastSettings.DEFAULT_FORECAST_DAYS);
    }
    final LiquidityForecastCashFlow cashFlow = new LiquidityForecastCashFlow(forecast, settings.getNextDays());
    final TimeSeries accumulatedSeriesExpected = new TimeSeries(I18n.getString("plugins.liquidityplanning.forecast.expected"));
    final TimeSeries creditSeries = new TimeSeries(I18n.getString("plugins.liquidityplanning.common.credit"));
    final TimeSeries debitSeries = new TimeSeries(I18n.getString("plugins.liquidityplanning.common.debit"));
    double accumulatedExpected = settings.getStartAmount().doubleValue();
    PFDay dt = PFDay.fromOrNow(forecast.getBaseDate());
    final Date lower = dt.getUtilDate();
    for (int i = 0; i < settings.getNextDays(); i++) {
        final Day day = new Day(dt.getDayOfMonth(), dt.getMonthValue(), dt.getYear());
        if (i > 0) {
            accumulatedExpected += cashFlow.getDebitsExpected()[i - 1].doubleValue() + cashFlow.getCreditsExpected()[i - 1].doubleValue();
        }
        accumulatedSeriesExpected.add(day, accumulatedExpected);
        creditSeries.add(day, cashFlow.getCreditsExpected()[i].doubleValue());
        debitSeries.add(day, cashFlow.getDebitsExpected()[i].doubleValue());
        dt = dt.plusDays(1);
    }
    dt = dt.minusDays(1);
    final XYChartBuilder cb = new XYChartBuilder(ChartFactory.createXYBarChart(null, null, false, null, null, PlotOrientation.VERTICAL, false, false, false));
    int counter = 0;
    final TimeSeriesCollection xyDataSeries = new TimeSeriesCollection();
    xyDataSeries.addSeries(accumulatedSeriesExpected);
    final XYLineAndShapeRenderer lineRenderer = new XYLineAndShapeRenderer(true, true);
    lineRenderer.setSeriesPaint(0, cb.getRedMarker());
    lineRenderer.setSeriesVisibleInLegend(0, true);
    cb.setRenderer(counter, lineRenderer).setDataset(counter++, xyDataSeries).setStrongStyle(lineRenderer, false, accumulatedSeriesExpected);
    final TimeSeriesCollection cashflowSet = new TimeSeriesCollection();
    cashflowSet.addSeries(debitSeries);
    cashflowSet.addSeries(creditSeries);
    final XYBarRenderer barRenderer = new XYBarRenderer(.2);
    barRenderer.setSeriesPaint(0, cb.getGreenFill());
    barRenderer.setSeriesPaint(1, cb.getRedFill());
    barRenderer.setShadowVisible(false);
    cb.setRenderer(counter, barRenderer).setDataset(counter++, cashflowSet);
    cb.setDateXAxis(true).setDateXAxisRange(lower, dt.getUtilDate()).setYAxis(true, null);
    return cb.getChart();
}
Also used : TimeSeries(org.jfree.data.time.TimeSeries) TimeSeriesCollection(org.jfree.data.time.TimeSeriesCollection) XYLineAndShapeRenderer(org.jfree.chart.renderer.xy.XYLineAndShapeRenderer) Day(org.jfree.data.time.Day) PFDay(org.projectforge.framework.time.PFDay) XYChartBuilder(org.projectforge.charting.XYChartBuilder) PFDay(org.projectforge.framework.time.PFDay) Date(java.util.Date) XYBarRenderer(org.jfree.chart.renderer.xy.XYBarRenderer)

Aggregations

TimeSeriesCollection (org.jfree.data.time.TimeSeriesCollection)90 TimeSeries (org.jfree.data.time.TimeSeries)66 JFreeChart (org.jfree.chart.JFreeChart)35 XYPlot (org.jfree.chart.plot.XYPlot)25 Date (java.util.Date)23 Day (org.jfree.data.time.Day)20 DateAxis (org.jfree.chart.axis.DateAxis)17 Month (org.jfree.data.time.Month)14 SimpleDateFormat (java.text.SimpleDateFormat)13 NumberAxis (org.jfree.chart.axis.NumberAxis)12 XYLineAndShapeRenderer (org.jfree.chart.renderer.xy.XYLineAndShapeRenderer)12 RegularTimePeriod (org.jfree.data.time.RegularTimePeriod)11 Map (java.util.Map)9 Color (java.awt.Color)7 Font (java.awt.Font)7 File (java.io.File)7 List (java.util.List)7 ClosePriceIndicator (org.ta4j.core.indicators.helpers.ClosePriceIndicator)7 LocalDate (java.time.LocalDate)6 BasicStroke (java.awt.BasicStroke)5