Querying Data

Function Description

You can use the OpenTSDB query API to read data.

Function genQueryReq () generates a query request, and function query () sends the query request to the OpenTSDB server.

Sample Code

private static String QUERY_URL = (securityMode ? "https://" : "http://") + OPENTSDB_IP + ":"
      + OPENTSDB_PORT + "/api/query";

static class Query {
  public Long start;
  public Long end;
  public boolean delete = false;
  public List<SubQuery> queries;
}

static class SubQuery {
  public String metric;
  public String aggregator;
  public SubQuery(String metric, String aggregator) {
    this.metric = metric;
    this.aggregator = aggregator;
  }
}

String genQueryReq() {
  Query query = new Query();
  query.start = 1498838400L;
  query.end = 1498921200L;
  query.queries = ImmutableList.of(new SubQuery("city.temp", "sum"), new SubQuery("city.hum", "sum"));
  Gson gson = new Gson();
  return gson.toJson(query);
}

public void query() throws ClientProtocolException, IOException {
  try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    HttpPost httpPost = new HttpPost(QUERY_URL);
    // A timeout interval needs to be set for the request.
    addTimeout(httpPost);
    String queryRequest = genQueryReq();
    //System.out.println("Request=" + queryRequest);
    StringEntity entity = new StringEntity(queryRequest, "ISO-8859-1");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost);

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("Status Code : " + statusCode);
    if (statusCode != HttpStatus.SC_OK) {
      System.out.println("Request failed! " + response.getStatusLine());
    }

    String body = EntityUtils.toString(response.getEntity(), "ISO-8859-1");
    System.out.println("Response content : " + body);
  }
}