org.influxdb.dto.QueryResult Java Examples

The following examples show how to use org.influxdb.dto.QueryResult. 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: InfluxDBImpl.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
 * Calls the influxDBService for the query.
 */
private Call<QueryResult> callQuery(final Query query) {
  Call<QueryResult> call;
  if (query instanceof BoundParameterQuery) {
      BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query;
      call = this.influxDBService.postQuery(getDatabase(query), query.getCommandWithUrlEncoded(),
              boundParameterQuery.getParameterJsonWithUrlEncoded());
  } else {
      if (query.requiresPost()) {
        call = this.influxDBService.postQuery(getDatabase(query), query.getCommandWithUrlEncoded());
      } else {
        call = this.influxDBService.query(getDatabase(query), query.getCommandWithUrlEncoded());
      }
  }
  return call;
}
 
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
public void testUnsupportedField() {
  // Given...
	mapper.cacheMeasurementClass(MyPojoWithUnsupportedField.class);

	List<String> columnList = Arrays.asList("bar");
	List<Object> firstSeriesResult = Arrays.asList("content representing a Date");

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

	//When...
	List<MyPojoWithUnsupportedField> result = new LinkedList<>();
	Assertions.assertThrows(InfluxDBMapperException.class, () -> {
		mapper.parseSeriesAs(series, MyPojoWithUnsupportedField.class, result);
	});
}
 
Example #4
Source File: InfluxDbSources.java    From hazelcast-jet-contrib with Apache License 2.0 6 votes vote down vote up
private static boolean throwExceptionIfResultWithErrorOrNull(final QueryResult queryResult) {
    if (queryResult == null) {
        throw new RuntimeException("InfluxDB returned null query result");
    }
    if (queryResult.getResults() == null && "DONE".equals(queryResult.getError())) {
        return true;
    }
    if (queryResult.getError() != null) {
        throw new RuntimeException("InfluxDB returned an error: " + queryResult.getError());
    }
    if (queryResult.getResults() == null) {
        throw new RuntimeException("InfluxDB returned null query results");
    }
    for (Result seriesResult : queryResult.getResults()) {
        if (seriesResult.getError() != null) {
            throw new RuntimeException("InfluxDB returned an error with Series: " + seriesResult.getError());
        }
    }
    return false;
}
 
Example #5
Source File: InfluxDBResultMapperTest.java    From influxdb-java with MIT License 6 votes vote down vote up
@Test
public void testFieldValueModified_DateAsISO8601() {
  // Given...
	mapper.cacheMeasurementClass(MyCustomMeasurement.class);

	List<String> columnList = Arrays.asList("time");
	List<Object> firstSeriesResult = Arrays.asList("2017-06-19T09:29:45.655123Z");

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

	//When...
	List<MyCustomMeasurement> result = new LinkedList<>();
	mapper.parseSeriesAs(series, MyCustomMeasurement.class, result);

	//Then...
	Assertions.assertTrue(result.size() == 1);
}
 
Example #6
Source File: InfluxDB.java    From iotdb-benchmark with Apache License 2.0 6 votes vote down vote up
private Status executeQueryAndGetStatus(String sql) {
  LOGGER.debug("{} query SQL: {}", Thread.currentThread().getName(), sql);

  QueryResult results = influxDbInstance.query(new Query(sql, influxDbName));
  int cnt = 0;
  for (Result result : results.getResults()) {
    List<Series> series = result.getSeries();
    if (series == null) {
      continue;
    }
    if (result.getError() != null) {
      return new Status(false, cnt, new Exception(result.getError()), sql);
    }
    for (Series serie : series) {
      List<List<Object>> values = serie.getValues();
      cnt += values.size() * (serie.getColumns().size() - 1);
    }
  }

  LOGGER.debug("{} 查到数据点数: {}", Thread.currentThread().getName(), cnt);
  return new Status(true, cnt);
}
 
Example #7
Source File: SeriesHandler.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void addSeries(QueryResult.Series series) {
    final GroupName group = seriesToGroupName(series);
    final Optional<Histogram.Range> range = rangeFromSeries(series);
    final int timeColumnIdx = InfluxUtil.getColumnIndexFromSeries(series, TIME_COLUMN).orElseThrow(() -> new IllegalStateException("missing time column"));

    series.getValues().forEach(row -> {
        assert series.getColumns().size() == row.size();

        final DateTime timestamp = new DateTime(((Number) row.get(timeColumnIdx)).longValue());
        final IntermediateTSV valueMap = new IntermediateTSV();

        final ListIterator<String> columnIter = series.getColumns().listIterator();
        final Iterator<Object> rowIter = row.iterator();
        while (rowIter.hasNext()) {
            final Object field = rowIter.next();
            final int columnIdx = columnIter.nextIndex();
            final String columnName = columnIter.next();
            if (columnIdx != timeColumnIdx && field != null)
                valueMap.addMetric(valueKeyToMetricName(columnName), range, seriesValueToMetricValue(field));
        }

        datums.merge(new TimestampedGroup(timestamp, group), valueMap, IntermediateTSV::withMerged);
    });
}
 
Example #8
Source File: InfluxDBTest.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
   * Test chunking on 0.13 and 1.0.
   * @throws InterruptedException
   */
  @Test()
  public void testChunkingOldVersion() throws InterruptedException {

      if (this.influxDB.version().startsWith("0.") || this.influxDB.version().startsWith("1.0")) {

          Assertions.assertThrows(RuntimeException.class, () -> {
          String dbName = "write_unittest_" + System.currentTimeMillis();
          Query query = new Query("SELECT * FROM cpu GROUP BY *", dbName);
          this.influxDB.query(query, 10, new Consumer<QueryResult>() {
              @Override
              public void accept(QueryResult result) {
              }
	});
});
      }
  }
 
Example #9
Source File: InfluxDBTest.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
 * Tests for callback query with a failure.
 * see Issue #602
 */
@Test
public void testCallbackQueryFailureHandling() throws Throwable {
  final AsyncResult<QueryResult> res = new AsyncResult<>();

  this.influxDB.query(new Query("SHOW SERRIES"), res.resultConsumer, res.errorConsumer);

  try{
    res.result();
    Assertions.fail("Malformed query should throw InfluxDBException");
  }
  catch (InfluxDBException e){
    Pattern errorPattern = Pattern.compile("Bad Request.*error parsing query: found SERRIES, expected.*",
            Pattern.DOTALL);

    Assertions.assertTrue(errorPattern.matcher(e.getMessage()).matches(),
            "Error string \"" + e.getMessage() + "\" does not match error pattern");
  }
}
 
Example #10
Source File: InfluxDBContainerWithUserTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void queryForWriteAndRead() {
    InfluxDB influxDB = influxDBContainer.getNewInfluxDB();

    Point point = Point.measurement("cpu")
        .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
        .addField("idle", 90L)
        .addField("user", 9L)
        .addField("system", 1L)
        .build();
    influxDB.write(point);

    Query query = new Query("SELECT idle FROM cpu", DATABASE);
    QueryResult actual = influxDB.query(query);

    assertThat(actual, notNullValue());
    assertThat(actual.getError(), nullValue());
    assertThat(actual.getResults(), notNullValue());
    assertThat(actual.getResults().size(), is(1));

}
 
Example #11
Source File: ITExecuteInfluxDBQuery.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidSinglePoint() {
    String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652";
    influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    String query = "select * from water";
    byte [] bytes = query.getBytes();
    runner.enqueue(bytes);
    runner.run(1,true,true);
    runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    assertEquals("Value should be equal", 1, flowFiles.size());
    assertNull("Value should be null", flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));

    QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    Series series = queryResult.getResults().get(0).getSeries().get(0);
    validateSeries(series.getName(), series.getColumns(), series.getValues().get(0),"newark",1.0);
}
 
Example #12
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 #13
Source File: InfluxDBProxyTest.java    From influxdb-java with MIT License 6 votes vote down vote up
@Test
public void testWriteSomePointThroughTcpProxy() {
  influxDB.query(new Query("CREATE DATABASE " + TEST_DB));;
  influxDB.setDatabase(TEST_DB);

  for(int i = 0; i < 20; i++) {
    Point point = Point.measurement("weather")
        .time(i,TimeUnit.HOURS)
        .addField("temperature", (double) i)
        .addField("humidity", (double) (i) * 1.1)
        .addField("uv_index", "moderate").build();
    influxDB.write(point);
  }

  QueryResult result = influxDB.query(new Query("select * from weather", TEST_DB));
  //check points written already to DB
  Assertions.assertEquals(20, result.getResults().get(0).getSeries().get(0).getValues().size());

  influxDB.deleteDatabase(TEST_DB);
}
 
Example #14
Source File: TopologyQuery.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private List<Call.CallDetail> buildEndpointCalls(Query query,
                                                 DetectPoint detectPoint) throws IOException {
    QueryResult.Series series = client.queryForSingleSeries(query);

    if (log.isDebugEnabled()) {
        log.debug("SQL: {} result set: {}", query.getCommand(), series);
    }
    if (series == null) {
        return Collections.emptyList();
    }

    List<Call.CallDetail> calls = new ArrayList<>();
    series.getValues().forEach(values -> {
        Call.CallDetail call = new Call.CallDetail();
        String entityId = (String) values.get(1);
        call.buildFromEndpointRelation(entityId, detectPoint);
        calls.add(call);
    });
    return calls;
}
 
Example #15
Source File: ITPutInfluxDB.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidTwoPointWithSameMeasurement() {
    String message = "water,country=US,city=newark rain=1,humidity=0.6" + System.lineSeparator()
            + "water,country=US,city=nyc rain=2,humidity=0.7" + System.lineSeparator();
    byte [] bytes = message.getBytes();
    runner.enqueue(bytes);
    runner.run(1,true,true);
    runner.assertAllFlowFilesTransferred(PutInfluxDB.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(PutInfluxDB.REL_SUCCESS);
    assertEquals("Value should be equal", 1, flowFiles.size());
    assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(PutInfluxDB.INFLUX_DB_ERROR_MESSAGE));
    QueryResult result = influxDB.query(new Query("select * from water", dbName));
    assertEquals("size should be same", 1, result.getResults().iterator().next().getSeries().size());
    List<List<Object>> values = result.getResults().iterator().next().getSeries().iterator().next().getValues();
    assertEquals("size should be same", 2, values.size());
}
 
Example #16
Source File: UDPInfluxDBTest.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
 * Test writing multiple separate records to the database using string
 * protocol through UDP.
 */
@Test
public void testWriteMultipleStringDataLinesThroughUDP() throws InterruptedException {
    String measurement = TestUtils.getRandomMeasurement();
    this.influxDB.write(UDP_PORT, Arrays.asList(
            measurement + ",atag=test1 idle=100,usertime=10,system=1",
            measurement + ",atag=test2 idle=200,usertime=20,system=2",
            measurement + ",atag=test3 idle=300,usertime=30,system=3"
    ));
    Thread.sleep(2000);
    Query query = new Query("SELECT * FROM " + measurement + " GROUP BY *", UDP_DATABASE);
    QueryResult result = this.influxDB.query(query);

    Assertions.assertEquals(3, result.getResults().get(0).getSeries().size());
    Assertions.assertEquals("test1", result.getResults().get(0).getSeries().get(0).getTags().get("atag"));
    Assertions.assertEquals("test2", result.getResults().get(0).getSeries().get(1).getTags().get("atag"));
    Assertions.assertEquals("test3", result.getResults().get(0).getSeries().get(2).getTags().get("atag"));
}
 
Example #17
Source File: ITPutInfluxDB.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidTwoPointWithDifferentMeasurement() {
    String message = "water,country=US,city=newark rain=1,humidity=0.6" + System.lineSeparator()
            + "testm,country=US,city=chicago rain=10,humidity=0.9" + System.lineSeparator();
    byte [] bytes = message.getBytes();
    runner.enqueue(bytes);
    runner.run(1,true,true);
    runner.assertAllFlowFilesTransferred(PutInfluxDB.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(PutInfluxDB.REL_SUCCESS);
    assertEquals("Value should be equal", 1, flowFiles.size());
    assertEquals("Value should be equal",null, flowFiles.get(0).getAttribute(PutInfluxDB.INFLUX_DB_ERROR_MESSAGE));
    QueryResult result = influxDB.query(new Query("select * from water, testm", dbName));
    assertEquals("size should be same", 2, result.getResults().iterator().next().getSeries().size());
    List<List<Object>> values = result.getResults().iterator().next().getSeries().iterator().next().getValues();
    assertEquals("size should be same", 1, values.size());
}
 
Example #18
Source File: ITExecuteInfluxDBQuery.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testShowDatabases() {
    String query = "show databases";
    byte [] bytes = query.getBytes();
    runner.enqueue(bytes);
    runner.run(1,true,true);
    runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    assertEquals("Value should be equal", 1, flowFiles.size());
    assertNull("Value should be null", flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));

    String result = new String(flowFiles.get(0).toByteArray());
    QueryResult queryResult = gson.fromJson(new StringReader(result), QueryResult.class);
    Series series = queryResult.getResults().get(0).getSeries().get(0);
    assertEquals("series name should be same", "databases", series.getName());
    assertEquals("series column should be same", "name", series.getColumns().get(0));
    boolean internal = series.getValues().get(0).stream().anyMatch(o -> o.equals("_internal"));
    Assert.assertTrue("content should contain _internal " + queryResult, internal);
    boolean test = series.getValues().stream().flatMap(i -> ((List<Object>)i).stream()).anyMatch(o -> o.equals("test"));
    Assert.assertTrue("content should contain test " + queryResult, test);
}
 
Example #19
Source File: InfluxDBResultMapper.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
 * <p>
 * Process a {@link QueryResult} object returned by the InfluxDB client inspecting the internal
 * data structure and creating the respective object instances based on the Class passed as
 * parameter.
 * </p>
 *
 * @param queryResult the InfluxDB result object
 * @param clazz the Class that will be used to hold your measurement data
 * @param <T> the target type
 * @param measurementName name of the Measurement
 * @param precision the time precision of results
 *
 * @return a {@link List} of objects from the same Class passed as parameter and sorted on the
 * same order as received from InfluxDB.
 *
 * @throws InfluxDBMapperException If {@link QueryResult} parameter contain errors,
 * <code>clazz</code> parameter is not annotated with &#64;Measurement or it was not
 * possible to define the values of your POJO (e.g. due to an unsupported field type).
 */
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz, final String measurementName,
                          final TimeUnit precision)
    throws InfluxDBMapperException {

  Objects.requireNonNull(measurementName, "measurementName");
  Objects.requireNonNull(queryResult, "queryResult");
  Objects.requireNonNull(clazz, "clazz");

  throwExceptionIfResultWithError(queryResult);
  cacheMeasurementClass(clazz);

  List<T> result = new LinkedList<T>();

  queryResult.getResults().stream()
    .filter(internalResult -> Objects.nonNull(internalResult) && Objects.nonNull(internalResult.getSeries()))
    .forEach(internalResult -> {
      internalResult.getSeries().stream()
        .filter(series -> series.getName().equals(measurementName))
        .forEachOrdered(series -> {
          parseSeriesAs(series, clazz, result, precision);
        });
      });

  return result;
}
 
Example #20
Source File: UDPInfluxDBTest.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
 * Test writing multiple records to the database using string protocol
 * through UDP.
 */
@Test
public void testWriteMultipleStringDataThroughUDP() throws InterruptedException {
    String measurement = TestUtils.getRandomMeasurement();
    this.influxDB.write(UDP_PORT, measurement + ",atag=test1 idle=100,usertime=10,system=1\n"
            + measurement + ",atag=test2 idle=200,usertime=20,system=2\n"
            + measurement + ",atag=test3 idle=300,usertime=30,system=3");
    Thread.sleep(2000);
    Query query = new Query("SELECT * FROM " + measurement + " GROUP BY *", UDP_DATABASE);
    QueryResult result = this.influxDB.query(query);

    Assertions.assertEquals(3, result.getResults().get(0).getSeries().size());
    Assertions.assertEquals("test1", result.getResults().get(0).getSeries().get(0).getTags().get("atag"));
    Assertions.assertEquals("test2", result.getResults().get(0).getSeries().get(1).getTags().get("atag"));
    Assertions.assertEquals("test3", result.getResults().get(0).getSeries().get(2).getTags().get("atag"));
}
 
Example #21
Source File: MetadataQuery.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private List<Service> buildServices(Query query) throws IOException {
    QueryResult.Series series = client.queryForSingleSeries(query);
    if (log.isDebugEnabled()) {
        log.debug("SQL: {} result: {}", query.getCommand(), series);
    }

    ArrayList<Service> services = Lists.newArrayList();
    if (Objects.nonNull(series)) {
        for (List<Object> values : series.getValues()) {
            Service service = new Service();
            service.setId((String) values.get(1));
            service.setName((String) values.get(2));
            services.add(service);
        }
    }
    return services;
}
 
Example #22
Source File: MetadataQuery.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public List<Database> getAllDatabases() throws IOException {
    SelectSubQueryImpl<SelectQueryImpl> subQuery = select()
        .fromSubQuery(client.getDatabase())
        .column(ID_COLUMN).column(NAME)
        .from(ServiceTraffic.INDEX_NAME)
        .where(eq(InfluxConstants.TagName.NODE_TYPE, NodeType.Database.value()))
        .groupBy(TagName.NAME, TagName.NODE_TYPE);
    SelectQueryImpl query = select(ID_COLUMN, NAME).from(client.getDatabase());
    query.setSubQuery(subQuery);
    QueryResult.Series series = client.queryForSingleSeries(query);
    if (log.isDebugEnabled()) {
        log.debug("SQL: {} result: {}", query.getCommand(), series);
    }

    List<Database> databases = Lists.newArrayList();
    if (Objects.nonNull(series)) {
        for (List<Object> values : series.getValues()) {
            Database database = new Database();
            database.setId((String) values.get(1));
            database.setName((String) values.get(2));
            databases.add(database);
        }
    }
    return databases;
}
 
Example #23
Source File: UITemplateManagementDAOImpl.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateChangeStatus disableTemplate(final String name) throws IOException {
    WhereQueryImpl<SelectQueryImpl> query = select().all()
                                                    .from(client.getDatabase(), UITemplate.INDEX_NAME)
                                                    .where(eq(InfluxConstants.TagName.ID_COLUMN, name));
    QueryResult.Series series = client.queryForSingleSeries(query);
    if (Objects.nonNull(series)) {
        Point point = Point.measurement(UITemplate.INDEX_NAME)
                           .tag(InfluxConstants.TagName.ID_COLUMN, name)
                           .addField(UITemplate.DISABLED, BooleanUtils.TRUE)
                           .time(1L, TimeUnit.NANOSECONDS)
                           .build();
        client.write(point);
        return TemplateChangeStatus.builder().status(true).build();
    } else {
        return TemplateChangeStatus.builder().status(false).message("Can't find the template").build();
    }
}
 
Example #24
Source File: UITemplateManagementDAOImpl.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateChangeStatus changeTemplate(final DashboardSetting setting) throws IOException {
    final UITemplate.Builder builder = new UITemplate.Builder();
    final UITemplate uiTemplate = setting.toEntity();

    WhereQueryImpl<SelectQueryImpl> query = select().all()
                                                    .from(client.getDatabase(), UITemplate.INDEX_NAME)
                                                    .where(eq(InfluxConstants.TagName.ID_COLUMN, uiTemplate.id()));

    QueryResult.Series series = client.queryForSingleSeries(query);
    if (Objects.nonNull(series)) {
        Point point = Point.measurement(UITemplate.INDEX_NAME)
                           .fields(builder.data2Map(uiTemplate))
                           .tag(InfluxConstants.TagName.ID_COLUMN, uiTemplate.id())
                           .time(1L, TimeUnit.NANOSECONDS)
                           .build();
        client.write(point);
        return TemplateChangeStatus.builder().status(true).build();
    } else {
        return TemplateChangeStatus.builder().status(false).message("Can't find the template").build();
    }
}
 
Example #25
Source File: ITExecuteInfluxDBQuery.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidTwoPoints() {
    String message = "water,country=US,city=newark rain=1,humidity=0.6 1501002274856668652" +
        System.lineSeparator() +
        "water,country=US,city=nyc rain=2,humidity=0.6 1501002274856668652";
    influxDB.write(dbName, DEFAULT_RETENTION_POLICY, InfluxDB.ConsistencyLevel.ONE, message);
    String query = "select * from water";
    byte [] bytes = query.getBytes();
    runner.enqueue(bytes);
    runner.run(1,true,true);
    runner.assertAllFlowFilesTransferred(ExecuteInfluxDBQuery.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ExecuteInfluxDBQuery.REL_SUCCESS);
    assertEquals("Value should be equal", 1, flowFiles.size());
    assertNull("Value should be null", flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_ERROR_MESSAGE));
    assertEquals("Value should be equal",query, flowFiles.get(0).getAttribute(ExecuteInfluxDBQuery.INFLUX_DB_EXECUTED_QUERY));
    QueryResult queryResult = gson.fromJson(new StringReader(new String(flowFiles.get(0).toByteArray())), QueryResult.class);
    assertNotNull("QueryResult should not be null", queryResult.getResults());
    assertEquals("results array should be same size", 1, queryResult.getResults().size());
    assertEquals("Series size should be same",1, queryResult.getResults().get(0).getSeries().size());
    Series series1 = queryResult.getResults().get(0).getSeries().get(0);
    validateSeries(series1.getName(),series1.getColumns(), series1.getValues().get(0),"newark",1.0);

    Series series2 = queryResult.getResults().get(0).getSeries().get(0);
    validateSeries(series2.getName(),series2.getColumns(), series2.getValues().get(1),"nyc",2.0);
}
 
Example #26
Source File: InfluxDBTest.java    From influxdb-java with MIT License 6 votes vote down vote up
/**
 * Tests for callback query.
 */
@Test
public void testCallbackQuery() throws Throwable {
  final AsyncResult<QueryResult> result = new AsyncResult<>();
  final Consumer<QueryResult> firstQueryConsumer = new Consumer<QueryResult>() {
    @Override
    public void accept(QueryResult queryResult) {
      influxDB.query(new Query("DROP DATABASE mydb2", "mydb"), result.resultConsumer, result.errorConsumer);
    }
  };

  this.influxDB.query(new Query("CREATE DATABASE mydb2", "mydb"), firstQueryConsumer, result.errorConsumer);

  // Will throw exception in case of error.
  result.result();
}
 
Example #27
Source File: BatchOptionsTest.java    From influxdb-java with MIT License 5 votes vote down vote up
/**
 * Test the implementation of {@link BatchOptions#flushDuration(int)} }.
 * @throws InterruptedException
 */
@Test
public void testFlushDuration() throws InterruptedException {
  String dbName = "write_unittest_" + System.currentTimeMillis();
  try {
    BatchOptions options = BatchOptions.DEFAULTS.flushDuration(200);
    influxDB.query(new Query("CREATE DATABASE " + dbName));
    influxDB.setDatabase(dbName);
    influxDB.enableBatch(options);
    write20Points(influxDB);

    //check no points writen to DB before the flush duration
    QueryResult result = influxDB.query(new Query("select * from weather", dbName));
    Assertions.assertNull(result.getResults().get(0).getSeries());
    Assertions.assertNull(result.getResults().get(0).getError());

    //wait for at least one flush
    Thread.sleep(500);
    result = influxDB.query(new Query("select * from weather", dbName));

    //check points written already to DB
    Assertions.assertEquals(20, result.getResults().get(0).getSeries().get(0).getValues().size());
  }
  finally {
    this.influxDB.disableBatch();
    this.influxDB.query(new Query("DROP DATABASE " + dbName));
  }
}
 
Example #28
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 but return a single {@link QueryResult.Series}.
 *
 * @throws IOException if there is an error on the InfluxDB server or communication error
 */
public QueryResult.Series queryForSingleSeries(Query query) throws IOException {
    List<QueryResult.Series> series = queryForSeries(query);
    if (CollectionUtils.isEmpty(series)) {
        return null;
    }
    return series.get(0);
}
 
Example #29
Source File: MessagePackTraverserTest.java    From influxdb-java with MIT License 5 votes vote down vote up
@Test
public void testParseMethodOnNonEmptyResult() {
  MessagePackTraverser traverser = new MessagePackTraverser();
  /* a json-like view of msgpack_2.bin

  {"results":[{"statement_id":0,"series":[{"name":"measurement_957996674028300","columns":["time","device","foo"],
        "values":[[(5,0x000058-797a00000),"one",1.0],[(5,0x000058-79-78100000),"two",2.0],[(5,0x000058-79-6a200000),"three",3.0]]}]}]}
  */
  QueryResult queryResult = traverser.parse(MessagePackTraverserTest.class.getResourceAsStream("msgpack_2.bin"));
  List<List<Object>> values = queryResult.getResults().get(0).getSeries().get(0).getValues();
  Assertions.assertEquals(3, values.size());
  assertEquals(1485273600000000000L, values.get(0).get(0));
  assertEquals("two", values.get(1).get(1));
  assertEquals(3.0, values.get(2).get(2));
}
 
Example #30
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();
}