HighCharts-GXT/GWT Project The official HighCharts-GWT/GXT adapters blog

Forum

Welcome Guest 

Show/Hide Header

Welcome Guest, posting in this forum requires registration.





Pages: [1]
Author Topic: Snippet for live charts
strollo
Administrator
Posts: 59
Post Snippet for live charts
on: April 7, 2011, 15:50

The following code can be used inside your HighChart or HighChartFrame components to add points to a series (given the x, and y values of point to add).

The shiftGap parameter is used to decide how many points are rendered before the chart is shifted.

/*
 * Used internally on render phase.
 */
private native synchronized void insertPoint(
 final String chartId, final double x, final double y, final int shiftGap) /*-{

  var chart = $wnd.getChartById(chartId);
  if (chart == null) {
    alert('cannot retrieve chart ' + chartId);
      return;
    }
    var series = chart.series[0];
    shift = series.data.length > shiftGap;

    chart.series[0].addPoint([x, y], true, shift);
}-*/;

The whole client code (for Highcharts-Gxt-1.2.x) is

import org.adapters.highcharts.codegen.sections.options.OptionPath;
import org.adapters.highcharts.codegen.types.SeriesType;
import org.adapters.highcharts.gxt.widgets.HighChart;
import org.adapters.highcharts.gxt.widgets.ext.ChartFrame;
import org.gcube.charts.cloud.client.widgets.ext.plugins.PlgSetDelay;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Timer;

public class LiveMonitor extends ChartFrame implements RefreshableChart {
  private String dataUrl = null;
  private int refreshDelay = 3000;
  // max num of elems before shifting the chart
  private int shiftGap = 10;

  public LiveMonitor(
      final String title,
      final String dataUrl) {
    super(new HighChart(null, title));
    this.dataUrl = dataUrl;
    this.initUI();
    this.initLoop();
    this.initToolbar();
  }

  public final void setRefreshDelay(int refreshDelay) {
    this.refreshDelay = refreshDelay;
  }

  public final void setShiftGap(final int shiftGap) {
    this.shiftGap = shiftGap;
  }

  private void initToolbar() {
    this.clearToolbar();
    try {
      this.addPlugin("Options", new PlgSetDelay(this));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void initUI () {
    try {
      this.chart.setOption(new OptionPath("/credits/enabled"), false);

      this.chart.setOption(new OptionPath("/legend/enabled"), false);
      this.chart.setOption(new OptionPath("/xAxis/type"), "datetime");
      this.chart.setOption(new OptionPath("/xAxis/tickPixelInterval"), 150);
      this.chart.setOption(new OptionPath("/xAxis/maxZoom"), 20 * 1000);
      this.chart.setOption(new OptionPath("/plotOptions/series/marker/enabled"), false);

      this.chart.setOption(new OptionPath("/yAxis/minPadding"), 0.2);
      this.chart.setOption(new OptionPath("/yAxis/maxPadding"), 0.2);
      this.chart.setOption(new OptionPath("/yAxis/title/text"), "Value");
      this.chart.setOption(new OptionPath("/yAxis/title/margin"), 80);

      this.chart.setOption(new OptionPath("/yAxis/title/style/visibility"), "hidden");
      this.chart.setOption(new OptionPath("/chart/marginLeft"), 40);
      this.chart.setOption(new OptionPath("/exporting/enabled"), false);

      SeriesType series = new SeriesType("line #1");
      series.setType("areaspline");
      this.chart.addSeries(series);
    } catch (Exception e) {
    }
  }

  private void initLoop() {
    Timer t = new Timer() {
      @Override
      public void run() {
        getData();
        this.schedule(refreshDelay);
      }
    };
    t.schedule(refreshDelay);
  }

  private void getData() {
    final String chartId = this.chart.getChartJSId();
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, dataUrl);
    try {
      builder.sendRequest(null, new RequestCallback() {
        public void onResponseReceived(Request request, Response response) {
          // TODO Auto-generated method stub
          JSONValue jsonValue = JSONParser.parseLenient(response.getText());
          JSONArray jsonArray = jsonValue.isArray();
          if (jsonArray != null && jsonArray.size() > 0) {
            JSONNumber x = jsonArray.get(0).isNumber();
            JSONNumber y = jsonArray.get(1).isNumber();
            insertPoint(chartId, x.doubleValue(), y.doubleValue(), shiftGap);
          }
        }

        public void onError(Request request, Throwable exception) {
        }
      });
    } catch (RequestException e) {
      e.printStackTrace();
    }
  }

  /*
   * Used internally on render phase.
   */
  private native synchronized void insertPoint(
      final String chartId, final double x, final double y, final int shiftGap) /*-{
    var chart = $wnd.getChartById(chartId);
    if (chart == null) {
    alert('cannot retrieve chart ' + chartId);
        return;
    }
    var series = chart.series[0];
      shift = series.data.length > shiftGap;

      chart.series[0].addPoint([x, y], true, shift);
  }-*/;

}

The instantiation of the chart is:

LiveMonitor hc = new LiveMonitor(
		"Live Monitor",
		"http://127.0.0.1:8888/monitor/resourceLoad?format=json&jsoncallback=?");
hc.setShiftGap(20);
hc.setRefreshDelay(500);
return hc;

Servlet implementation:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonResourceLoad extends HttpServlet {
	private static final long serialVersionUID = 1236552397730511410L;
	private static final double MAX_VAL = 100.0; // $100.00

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		Random rnd = new Random();
		long x = new Date().getTime();
		resp.setContentType("application/x-javascript; charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.println("[" + x + ", " + rnd.nextDouble() * MAX_VAL + "]");
		out.flush();
	}

}

The web.xml file:

  <!-- Servlets -->
  <servlet>
    <servlet-name>jsonResourceLoad</servlet-name>
    <servlet-class>org.gcube.charts.cloud.server.JsonResourceLoad</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>jsonResourceLoad</servlet-name>
    <url-pattern>/monitor/resourceLoad</url-pattern>
  </servlet-mapping>
Lancer
Newbie
Posts: 3
Post Re: Snippet for live charts
on: February 8, 2013, 23:07

To run live chart with multiple series, you have to add SeriesType object

final SeriesType series = new SeriesType("Title");
series.setType("spline");
final SeriesType series2 = new SeriesType("Title2");
series.setType("spline");
hc.addSeries(series);
hc.addSeries(series2);

and then, you can use second series

chart.series[0].addPoint([x, y]);
chart.series[1].addPoint([x, y2]);
Pages: [1]
Mingle Forum by cartpauj
Version: 1.0.29 ; Page loaded in: 0.039 seconds.