Java Code Examples for org.influxdb.dto.QueryResult#Result

The following examples show how to use org.influxdb.dto.QueryResult#Result . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 6 votes vote down vote up
@Test
public void testToPOJO_HappyPath() {
  // Given...
  List<String> columnList = Arrays.asList("time", "uuid");
  List<Object> firstSeriesResult = Arrays.asList(Instant.now().toEpochMilli(), UUID.randomUUID().toString());

  QueryResult.Series series = new QueryResult.Series();
  series.setColumns(columnList);
  series.setName("CustomMeasurement");
  series.setValues(Arrays.asList(firstSeriesResult));

  QueryResult.Result internalResult = new QueryResult.Result();
  internalResult.setSeries(Arrays.asList(series));

  QueryResult queryResult = new QueryResult();
  queryResult.setResults(Arrays.asList(internalResult));

  //When...
  List<MyCustomMeasurement> myList = mapper.toPOJO(queryResult, MyCustomMeasurement.class);

  // Then...
  Assertions.assertEquals(1, myList.size(), "there must be one entry in the result list");
}
 
Example 2
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
* https://github.com/influxdata/influxdb/issues/7596 for more information.
*/
@Test
public void testToPOJO_SeriesFromQueryResultIsNull() {
  // Given...
  mapper.cacheMeasurementClass(MyCustomMeasurement.class);

  QueryResult.Result internalResult = new QueryResult.Result();
  internalResult.setSeries(null);

  QueryResult queryResult = new QueryResult();
  queryResult.setResults(Arrays.asList(internalResult));

  // When...
  List<MyCustomMeasurement> myList = mapper.toPOJO(queryResult, MyCustomMeasurement.class);

  // Then...
  Assertions.assertTrue( myList.isEmpty(), "there must NO entry in the result list");
}
 
Example 3
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 6 votes vote down vote up
@Test
void testToPOJO_SetMeasureName() {
	// Given...
	mapper.cacheMeasurementClass(MyCustomMeasurement.class);

	List<String> columnList = Arrays.asList("uuid");
	List<Object> firstSeriesResult = Arrays.asList(UUID.randomUUID().toString());

	QueryResult.Series series = new QueryResult.Series();
	series.setName("MySeriesName");
	series.setColumns(columnList);
	series.setValues(Arrays.asList(firstSeriesResult));

	QueryResult.Result internalResult = new QueryResult.Result();
	internalResult.setSeries(Arrays.asList(series));

	QueryResult queryResult = new QueryResult();
	queryResult.setResults(Arrays.asList(internalResult));

	//When...
	List<MyCustomMeasurement> result =
			mapper.toPOJO(queryResult, MyCustomMeasurement.class, "MySeriesName");

	//Then...
	Assertions.assertTrue(result.size() == 1);
}
 
Example 4
Source File: DefaultInfluxDbMetricsRetriever.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public InfluxMetric metric(NodeId nodeId, String metricName) {
    String queryString = new StringBuilder()
            .append("SELECT m1_rate FROM ")
            .append(database)
            .append(METRIC_DELIMITER)
            .append(quote(DEFAULT_POLICY))
            .append(METRIC_DELIMITER)
            .append(quote(nodeId + METRIC_DELIMITER + metricName))
            .append(" LIMIT 1")
            .toString();

    Query query = new Query(queryString, database);
    List<QueryResult.Result> results = influxDB.query(query).getResults();

    if (results != null && results.get(0) != null
            && results.get(0).getSeries() != null) {
        return new DefaultInfluxMetric.Builder()
                .time((String) results.get(0).getSeries().get(0).getValues().get(0).get(0))
                .oneMinRate((Double) results.get(0).getSeries().get(0)
                        .getValues().get(0).get(1)).build();
    }

    return null;
}
 
Example 5
Source File: DefaultInfluxDbMetricsRetriever.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all metric names that bound with node identification.
 *
 * @return all metric names
 */
protected Map<NodeId, Set<String>> allMetricNames() {
    Map<NodeId, Set<String>> metricNameMap = Maps.newHashMap();
    Query query = new Query("SHOW MEASUREMENTS", database);
    List<QueryResult.Result> results = influxDB.query(query).getResults();
    List<List<Object>> rawMetricNames = results.get(0).getSeries().get(0).getValues();

    rawMetricNames.forEach(rawMetricName -> {
        String nodeIdStr = getNodeId(strip(rawMetricName.toString()));

        if (nodeIdStr != null) {
            NodeId nodeId = NodeId.nodeId(nodeIdStr);
            String metricName = getMetricName(strip(rawMetricName.toString()));

            if (!metricNameMap.containsKey(nodeId)) {
                metricNameMap.putIfAbsent(nodeId, Sets.newHashSet());
            }

            if (metricName != null) {
                metricNameMap.get(nodeId).add(metricName);
            }
        }
    });

    return metricNameMap;
}
 
Example 6
Source File: CollectionThreadPoolStatHandler.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
private Map<String,NodeThreadPoolStatInfo> getLastStatInfoFromInfluxDb(String host) {
	Map<String,NodeThreadPoolStatInfo> lastThread = new HashMap<String,NodeThreadPoolStatInfo>();
	try {
		NodeThreadPoolStatInfo statInfo = new NodeThreadPoolStatInfo();
		statInfo.setClusterName(clusterName);
		statInfo.setHost(host);
		String query="select active, clusterName, completed, host, intervalCompleted, " +
				"intervalRejected, largest, queue, rejected, threadType, threads from thread_pool WHERE time >= '"+
				TimeUtil.toInfluxDBTimeFormat(DateUtil.getDiffTime(executeTime, Calendar.MINUTE, -1).getTime())+"' and " +
				"host ='"+host+"' and clusterName = '"+clusterName+"' order by time ";
		QueryResult queryResult = InflusDbUtil.query(query);
		List<QueryResult.Result> results = queryResult.getResults();
		query(lastThread, results);
	} catch (Exception e) {
		LOGGER.error(host+":从数据库中获取上一条失败!(threadpool)",e);
	}
	return lastThread;
}
 
Example 7
Source File: CollectionThreadPoolStatHandler.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
private void query(Map<String, NodeThreadPoolStatInfo> lastThread, List<QueryResult.Result> results) {
	Map<String,Map<String,Object>> mm = new HashMap<String, Map<String, Object>>();
	Map<String,Object> map = new HashMap<String, Object>();
	List<QueryResult.Series> series;
	List<String> columns;
	List<List<Object>> valus;
	if(CollectionUtils.isNotEmpty(results)){
           for (QueryResult.Result result : results) {
               series = result.getSeries();
               if(CollectionUtils.isNotEmpty(series)){
                   for (QueryResult.Series serie: series) {
                       columns=serie.getColumns();
                       valus = serie.getValues();
                       if(CollectionUtils.isNotEmpty(columns) && CollectionUtils.isNotEmpty(valus)){
                           for (List<Object> valu: valus) {
                               if(CollectionUtils.isNotEmpty(valu)){
                                   for (Integer i = 0;i<valu.size();i++){
                                       if(!columns.get(i).equals("time")){//过滤time字段
                                               map.put(columns.get(i),valu.get(i));
                                       }
                                   }
                                   mm.put((String) map.get("threadType"),map);
                               }
                           }
                       }
                   }
               }
           }
           if(mm.size() > 0){
               Iterator<Entry<String, Map<String, Object>>> mmIte = mm.entrySet().iterator();
               NodeThreadPoolStatInfo threadPoolStatInfo;
               while (mmIte.hasNext()) {
                   Entry<String, Map<String, Object>> re = mmIte.next();
                   JSON json = (JSON) JSONObject.toJSON(re.getValue());
                   threadPoolStatInfo = JSONObject.toJavaObject(json,NodeThreadPoolStatInfo.class);
                   lastThread.put(re.getKey(),threadPoolStatInfo);
               }
           }
       }
}
 
Example 8
Source File: CollectionJVMStatHandler.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
private NodeJVMStatInfo getLastStatInfoFromDB(String host) {
	NodeJVMStatInfo statInfo = new NodeJVMStatInfo();
	try {
		String qstr = "select host,clusterName,oldMemUsed,oldMemMax,youngMemMax,youngMemUsed," +
				"oldCollectionCount,oldCollectionTime from jvm where host='"+host+"' and clusterName='"+clusterName+"'" +
				" order by time desc limit 1";
		QueryResult result = InflusDbUtil.query(qstr);
		Map<String,Object> map = new HashMap<String, Object>();
		if(result != null){
			List<QueryResult.Result> results = result.getResults();
			if(CollectionUtils.isNotEmpty(results)){
				for (QueryResult.Result res : results){
						List<String> columns = res.getSeries().get(0).getColumns();
						List<List<Object>> values = res.getSeries().get(0).getValues();
						if(CollectionUtils.isNotEmpty(values)){
							for (List<Object> value:values) {
								for (int i =0;i<value.size();i++){
									map.put(columns.get(i),value.get(i));
								}
							}
						}
				}
			}
		}
		if(map.size() > 0){
			JSON json = (JSON) JSONObject.toJSON(map);
			statInfo = JSONObject.toJavaObject(json,NodeJVMStatInfo.class);
		}
	} catch (Exception e) {
		LOGGER.error(host+":从数据库中获取上一条失败(jvm)!",e);
		return null;
	}
	return statInfo;
}
 
Example 9
Source File: InfluxClient.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a query against InfluxDB with a single statement.
 *
 * @throws IOException if there is an error on the InfluxDB server or communication error
 */
public List<QueryResult.Series> queryForSeries(Query query) throws IOException {
    List<QueryResult.Result> results = query(query);

    if (CollectionUtils.isEmpty(results)) {
        return null;
    }
    return results.get(0).getSeries();
}
 
Example 10
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 5 votes vote down vote up
@Test
public void testThrowExceptionIfError_InfluxQueryResultSeriesHasError() {
	QueryResult queryResult = new QueryResult();

	QueryResult.Result seriesResult = new QueryResult.Result();
	seriesResult.setError("series error");

	queryResult.setResults(Arrays.asList(seriesResult));

	Assertions.assertThrows(InfluxDBMapperException.class, () -> {
		mapper.throwExceptionIfResultWithError(queryResult);
	});
}
 
Example 11
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 5 votes vote down vote up
@Test
void testToPOJOInheritance() {
  // Given...
  mapper.cacheMeasurementClass(MySubMeasurement.class);

  String superValue = UUID.randomUUID().toString();
  String subValue = "my sub value";
  List<String> columnList = Arrays.asList("superValue", "subValue");

  List<Object> firstSeriesResult = Arrays.asList(superValue, subValue);

  QueryResult.Series series = new QueryResult.Series();
  series.setName("MySeriesName");
  series.setColumns(columnList);
  series.setValues(Arrays.asList(firstSeriesResult));

  QueryResult.Result internalResult = new QueryResult.Result();
  internalResult.setSeries(Arrays.asList(series));

  QueryResult queryResult = new QueryResult();
  queryResult.setResults(Arrays.asList(internalResult));

  //When...
  List<MySubMeasurement> result =
      mapper.toPOJO(queryResult, MySubMeasurement.class, "MySeriesName");

  //Then...
  Assertions.assertTrue(result.size() == 1);
  Assertions.assertEquals(superValue, result.get(0).superValue);
  Assertions.assertEquals(subValue, result.get(0).subValue);
}
 
Example 12
Source File: DefaultInfluxDbMetricsRetriever.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<InfluxMetric> metric(NodeId nodeId, String metricName,
                           int period, TimeUnit unit) {
    List<InfluxMetric> metrics = Lists.newArrayList();
    String queryString = new StringBuilder()
            .append("SELECT m1_rate FROM ")
            .append(database)
            .append(METRIC_DELIMITER)
            .append(quote(DEFAULT_POLICY))
            .append(METRIC_DELIMITER)
            .append(quote(nodeId + METRIC_DELIMITER + metricName))
            .append(" WHERE time > now() - ")
            .append(period)
            .append(unitString(unit))
            .toString();

    Query query = new Query(queryString, database);
    List<QueryResult.Result> results = influxDB.query(query).getResults();

    if (results != null && results.get(0) != null
            && results.get(0).getSeries() != null) {

        results.get(0).getSeries().get(0).getValues().forEach(value ->
                metrics.add(new DefaultInfluxMetric.Builder()
                        .time((String) value.get(0))
                        .oneMinRate((Double) value.get(1))
                        .build()));
        return metrics;
    }

    return null;
}
 
Example 13
Source File: AlarmQuery.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Override
public Alarms getAlarm(Integer scopeId, String keyword, int limit, int from, long startTB,
                       long endTB) throws IOException {

    WhereQueryImpl<SelectQueryImpl> recallQuery = select()
        .function("top", AlarmRecord.START_TIME, limit + from).as(AlarmRecord.START_TIME)
        .column(AlarmRecord.ID0)
        .column(AlarmRecord.ALARM_MESSAGE)
        .column(AlarmRecord.SCOPE)
        .from(client.getDatabase(), AlarmRecord.INDEX_NAME)
        .where();
    if (startTB > 0 && endTB > 0) {
        recallQuery.and(gte(InfluxClient.TIME, InfluxClient.timeInterval(startTB)))
                   .and(lte(InfluxClient.TIME, InfluxClient.timeInterval(endTB)));
    }
    if (!Strings.isNullOrEmpty(keyword)) {
        recallQuery.and(contains(AlarmRecord.ALARM_MESSAGE, keyword.replaceAll("/", "\\\\/")));
    }
    if (Objects.nonNull(scopeId)) {
        recallQuery.and(eq(AlarmRecord.SCOPE, scopeId));
    }

    WhereQueryImpl<SelectQueryImpl> countQuery = select().count(AlarmRecord.ID0)
                                                         .from(client.getDatabase(), AlarmRecord.INDEX_NAME)
                                                         .where();
    recallQuery.getClauses().forEach(clause -> {
        countQuery.where(clause);
    });

    Query query = new Query(countQuery.getCommand() + recallQuery.getCommand());
    List<QueryResult.Result> results = client.query(query);
    if (log.isDebugEnabled()) {
        log.debug("SQL: {} result set: {}", query.getCommand(), results);
    }
    if (results.size() != 2) {
        throw new IOException("Expecting to get 2 Results, but it is " + results.size());
    }
    List<QueryResult.Series> series = results.get(1).getSeries();
    if (series == null || series.isEmpty()) {
        return new Alarms();
    }
    List<QueryResult.Series> counter = results.get(0).getSeries();
    Alarms alarms = new Alarms();
    alarms.setTotal(((Number) counter.get(0).getValues().get(0).get(1)).intValue());

    series.get(0).getValues()
          .stream()
          // re-sort by self, because of the result order by time.
          .sorted((a, b) -> Long.compare((long) b.get(1), (long) a.get(1)))
          .skip(from)
          .forEach(values -> {
              final int sid = ((Number) values.get(4)).intValue();
              Scope scope = Scope.Finder.valueOf(sid);

              AlarmMessage message = new AlarmMessage();
              message.setStartTime((long) values.get(1));
              message.setId((String) values.get(2));
              message.setMessage((String) values.get(3));
              message.setScope(scope);
              message.setScopeId(sid);

              alarms.getMsgs().add(message);
          });
    return alarms;
}
 
Example 14
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 4 votes vote down vote up
@Test
public void testToPOJO_QueryResultCreatedByGroupByClause() {
  // Given...
  mapper.cacheMeasurementClass(GroupByCarrierDeviceOS.class);

  List<String> columnList = Arrays.asList("time", "median", "min", "max");

  // InfluxDB client returns the time representation as Double.
  Double now = Long.valueOf(System.currentTimeMillis()).doubleValue();

  List<Object> firstSeriesResult = Arrays.asList(now, new Double("233.8"), new Double("0.0"),
    new Double("3090744.0"));
  // When the "GROUP BY" clause is used, "tags" are returned as Map<String,String>
  Map<String, String> firstSeriesTagMap = new HashMap<>();
  firstSeriesTagMap.put("CARRIER", "000/00");
  firstSeriesTagMap.put("DEVICE_OS_VERSION", "4.4.2");

  List<Object> secondSeriesResult = Arrays.asList(now, new Double("552.0"), new Double("135.0"),
    new Double("267705.0"));
  Map<String, String> secondSeriesTagMap = new HashMap<>();
  secondSeriesTagMap.put("CARRIER", "000/01");
  secondSeriesTagMap.put("DEVICE_OS_VERSION", "9.3.5");

  QueryResult.Series firstSeries = new QueryResult.Series();
  firstSeries.setColumns(columnList);
  firstSeries.setValues(Arrays.asList(firstSeriesResult));
  firstSeries.setTags(firstSeriesTagMap);
  firstSeries.setName("tb_network");

  QueryResult.Series secondSeries = new QueryResult.Series();
  secondSeries.setColumns(columnList);
  secondSeries.setValues(Arrays.asList(secondSeriesResult));
  secondSeries.setTags(secondSeriesTagMap);
  secondSeries.setName("tb_network");

  QueryResult.Result internalResult = new QueryResult.Result();
  internalResult.setSeries(Arrays.asList(firstSeries, secondSeries));

  QueryResult queryResult = new QueryResult();
  queryResult.setResults(Arrays.asList(internalResult));

  // When...
  List<GroupByCarrierDeviceOS> myList = mapper.toPOJO(queryResult, GroupByCarrierDeviceOS.class);

  // Then...
  GroupByCarrierDeviceOS firstGroupByEntry = myList.get(0);
  Assertions.assertEquals("000/00", firstGroupByEntry.carrier, "field 'carrier' does not match");
  Assertions.assertEquals("4.4.2", firstGroupByEntry.deviceOsVersion, "field 'deviceOsVersion' does not match");

  GroupByCarrierDeviceOS secondGroupByEntry = myList.get(1);
  Assertions.assertEquals("000/01", secondGroupByEntry.carrier, "field 'carrier' does not match");
  Assertions.assertEquals("9.3.5", secondGroupByEntry.deviceOsVersion, "field 'deviceOsVersion' does not match");
}