Java Code Examples for com.couchbase.client.java.document.json.JsonObject

The following examples show how to use com.couchbase.client.java.document.json.JsonObject. These examples are extracted from open source projects. 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 Project: ShedLock   Source File: CouchbaseLockProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean insertRecord(@NonNull LockConfiguration lockConfiguration) {
    try {

        JsonObject content = JsonObject.empty();
        content.put(LOCK_NAME, lockConfiguration.getName());
        content.put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil()));
        content.put(LOCKED_AT, toIsoString(ClockProvider.now()));
        content.put(LOCKED_BY, getHostname());
        JsonDocument document = JsonDocument.create(lockConfiguration.getName(), content);

        bucket.insert(document);
        return true;

    } catch (DocumentAlreadyExistsException e) {
        return false;
    }

}
 
Example 2
Source Project: components   Source File: CouchbaseWriter.java    License: Apache License 2.0 6 votes vote down vote up
public JsonObject createHierarchicalJson(Schema schema, IndexedRecord record, int idPos){
    JsonObject jsonObject = JsonObject.create();
    for (int i = 0; i < schema.getFields().size(); i++){
        if (i == idPos) continue;
        Object value = record.get(i);
        String fieldName = schema.getFields().get(i).name();
        try {
            JsonObject innerJson = JsonObject.fromJson(value.toString());
            jsonObject.put(fieldName, innerJson);
        } catch (Exception e) {
            try {
                JsonArray jsonArray = JsonArray.fromJson(value.toString());
                jsonObject.put(fieldName, jsonArray);
            } catch (Exception e2) {
                // This mean it's not JSON object
                jsonObject.put(fieldName, value);
            }
        }
    }
    return jsonObject;
}
 
Example 3
Source Project: components   Source File: CouchbaseInputTestIT.java    License: Apache License 2.0 6 votes vote down vote up
private void populateBucket() {
    CouchbaseEnvironment env = DefaultCouchbaseEnvironment
            .builder()
            .socketConnectTimeout(60000)
            .connectTimeout(60000)
            .keepAliveInterval(60000)
            .keyValueServiceConfig(KeyValueServiceConfig.create(60)) // If skip this config, we may get TimeoutException https://forums.couchbase.com/t/kv-upsert-throwing-timeoutexception-couchbase-4-5/9399
            .build();
    CouchbaseCluster cluster = CouchbaseCluster.create(env, bootstrapNodes);
    Bucket bucket = cluster.openBucket(bucketName, password);
    LOGGER.info("Connected to bucket - " + bucketName);
    assertTrue(bucket.bucketManager().flush());
    JsonDocument document = JsonDocument.create("foo", JsonObject.create().put("bar", 42));
    bucket.upsert(document, PersistTo.MASTER);
    bucket.close();
    LOGGER.info("Bucket is closed after upserting data");
    if (cluster != null) {
        cluster.disconnect();
    }
}
 
Example 4
Source Project: nosql4idea   Source File: CouchbaseKeyValueDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
public static CouchbaseKeyValueDescriptor createDescriptor(String key, Object value) {
    if (value == null) {
        return new CouchbaseKeyNullValueDescriptor(key);
    }
    if (value instanceof String) {
        return new CouchbaseKeyStringValueDescriptor(key, (String) value);
    }


    SimpleTextAttributes textAttributes = StyleAttributesProvider.getStringAttribute();
    if (value instanceof Boolean) {
        textAttributes = StyleAttributesProvider.getBooleanAttribute();
    } else if (value instanceof Number) {
        textAttributes = StyleAttributesProvider.getNumberAttribute();
    } else if (value instanceof JsonObject || value instanceof JsonArray) {
        textAttributes = StyleAttributesProvider.getObjectAttribute();
    }
    return new CouchbaseKeyValueDescriptor(key, value, textAttributes);
}
 
Example 5
Source Project: nosql4idea   Source File: CouchbasePanelTest.java    License: Apache License 2.0 6 votes vote down vote up
private CouchbaseResult createResults() {
    CouchbaseResult result = new CouchbaseResult("test");
    result.add(JsonObject.create().put("firstname", "Jojo")
            .put("age", 25)
            .put("mad", true)
            .put("interests", Arrays.asList("programming", "XP", "TDD"))
            .put("amount", 123456764L)
            .put("score", 12345.12121d)
            .put("address", JsonObject.create()
                    .put("Street", "Av. Champs Elysées")
                    .put("City", "Paris")
                    .put("ZIP Code", 75016))
            .put("movies", Arrays.asList(
                    JsonObject.create()
                            .put("title", "Fight Club")
                            .put("critic", 8.2),
                    JsonObject.create()
                            .put("title", "Blade Runner")
                            .put("critic", 9.3),
                    JsonObject.create()
                            .put("title", "Toys Story")
                            .put("critic", 8.7)
            )));
    return result;
}
 
Example 6
Source Project: incubator-pinot   Source File: CouchbaseCacheDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Insert a TimeSeriesDataPoint into Couchbase. If a document for this data point already
 * exists within Couchbase and the data value for the metricURN already exists in the cache,
 * we don't do anything. An example document generated and inserted for this might look like:
 * {
 *   "timestamp": 123456700000
 *   "metricId": 123456,
 *   "61427020": "3.0",
 *   "83958352": "59.6",
 *   "98648743": "0.0"
 * }
 * @param point data point
 */
public void insertTimeSeriesDataPoint(TimeSeriesDataPoint point) {

  JsonDocument doc = bucket.getAndTouch(point.getDocumentKey(), CacheConfig.getInstance().getCentralizedCacheSettings().getTTL());
  ThirdeyeMetricsUtil.couchbaseCallCounter.inc();

  if (doc == null) {
    JsonObject documentBody = CacheUtils.buildDocumentStructure(point);
    doc = JsonDocument.create(point.getDocumentKey(), CacheConfig.getInstance().getCentralizedCacheSettings().getTTL(), documentBody);
  } else {
    JsonObject dimensions = doc.content();
    if (dimensions.containsKey(point.getMetricUrnHash())) {
      return;
    }

    dimensions.put(point.getMetricUrnHash(), point.getDataValueAsDouble());
  }

  bucket.upsert(doc);
  ThirdeyeMetricsUtil.couchbaseWriteCounter.inc();
}
 
Example 7
Source Project: tutorials   Source File: N1QLLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenDocuments_whenBatchInsert_thenResult() {
    Bucket bucket = bucketFactory.getTravelSampleBucket();

    List<JsonDocument> documents = IntStream.rangeClosed(0,10)
      .mapToObj( i -> {
        JsonObject content = JsonObject.create()
          .put("id", i)
          .put("type", "airline")
          .put("name", "Sample Airline "  + i);
        return JsonDocument.create("cust_" + i, content);
      })
      .collect(Collectors.toList());

    List<JsonDocument> r5 = Observable
      .from(documents)
      .flatMap(doc -> bucket.async().insert(doc))
      .toList()
      .last()
      .toBlocking()
      .single();

    r5.forEach(System.out::println);
}
 
Example 8
Source Project: java-specialagent   Source File: CouchbaseClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test(final MockTracer tracer) {
  final Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment.builder().connectTimeout(TimeUnit.SECONDS.toMillis(60)).build());
  final Bucket bucket = cluster.openBucket(bucketName);

  final JsonObject arthur = JsonObject.create()
    .put("name", "Arthur")
    .put("email", "[email protected]")
    .put("interests", JsonArray.from("Holy Grail", "African Swallows"));

  bucket.upsert(JsonDocument.create("u:king_arthur", arthur));
  System.out.println(bucket.get("u:king_arthur"));

  cluster.disconnect(60, TimeUnit.SECONDS);

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(6, spans.size());

  boolean foundCouchbaseSpan = false;
  for (final MockSpan span : spans) {
    final String component = (String)span.tags().get(Tags.COMPONENT.getKey());
    if (component != null && component.startsWith("couchbase-java-client")) {
      foundCouchbaseSpan = true;
      break;
    }
  }

  assertTrue("couchbase-java-client span not found", foundCouchbaseSpan);
}
 
Example 9
Source Project: java-specialagent   Source File: CouchbaseClientITest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws BucketAlreadyExistsException, InterruptedException, IOException {
  final CouchbaseMock couchbaseMock = new CouchbaseMock("localhost", 8091, 2, 1);
  final BucketConfiguration bucketConfiguration = new BucketConfiguration();
  bucketConfiguration.name = bucketName;
  bucketConfiguration.numNodes = 1;
  bucketConfiguration.numReplicas = 1;
  bucketConfiguration.password = "";
  couchbaseMock.start();
  couchbaseMock.waitForStartup();
  couchbaseMock.createBucket(bucketConfiguration);

  final Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment.builder().connectTimeout(TimeUnit.SECONDS.toMillis(60)).build());
  final Bucket bucket = cluster.openBucket(bucketName);

  final JsonObject arthur = JsonObject
    .create().put("name", "Arthur")
    .put("email", "[email protected]")
    .put("interests", JsonArray.from("Holy Grail", "African Swallows"));

  bucket.upsert(JsonDocument.create("u:king_arthur", arthur));

  System.out.println(bucket.get("u:king_arthur"));

  cluster.disconnect(60, TimeUnit.SECONDS);
  couchbaseMock.stop();

  TestUtil.checkSpan(new ComponentSpanCount("couchbase-java-client.*", 2));
}
 
Example 10
Source Project: NetDiscovery   Source File: CouchbasePipeline.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(ResultItems resultItems) {

    JsonObject content = JsonObject.create();
    for (Map.Entry<String, Object> entry : resultItems.getAll().entrySet()) {

        content.put(entry.getKey(),entry.getValue());
    }

    bucket.upsert(JsonDocument.create(documentId, content));

    // Close all buckets and disconnect
    cluster.disconnect();
}
 
Example 11
Source Project: java-dcp-client   Source File: WorkloadGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
  CouchbaseCluster cluster = CouchbaseCluster.create("127.0.0.1").authenticate("Administrator", "password");
  Bucket bucket = cluster.openBucket("default");

  while (true) {
    for (int i = 0; i < 1024; i++) {
      bucket.upsert(JsonDocument.create("doc:" + i, JsonObject.create().put("uuid", UUID.randomUUID().toString())));
      Thread.sleep(1000);
    }
  }
}
 
Example 12
Source Project: serverless   Source File: ButtonDocument.java    License: Apache License 2.0 5 votes vote down vote up
JsonDocument toJson() {
    ObjectMapper mapper = new ObjectMapper();
    String json;
    try {
        json = mapper.writeValueAsString(this);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException(ex);
    }

    return JsonDocument.create(getId(), JsonObject.fromJson(json));
}
 
Example 13
Source Project: samza   Source File: CouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> putAsync(String key, V record) {
  Preconditions.checkArgument(StringUtils.isNotBlank(key), "key must not be null, empty or blank");
  Preconditions.checkArgument(!key.contains(" "), String.format("key should not contain spaces: %s", key));
  Preconditions.checkNotNull(record);
  Document<?> document = record instanceof JsonObject
      ? JsonDocument.create(key, (int) ttl.getSeconds(), (JsonObject) record)
      : BinaryDocument.create(key, (int) ttl.getSeconds(), Unpooled.copiedBuffer(valueSerde.toBytes(record)));
  return asyncWriteHelper(
      bucket.async().upsert(document, timeout.toMillis(), TimeUnit.MILLISECONDS),
      String.format("Failed to insert key %s into bucket %s", key, bucketName));
}
 
Example 14
Source Project: samza   Source File: TestCouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAsyncException() {
  String key = "throwExceptionKey";
  JsonObject value = JsonObject.create();
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableWriteFunction<JsonObject> writeFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.upsert(any(Document.class), anyLong(), any(TimeUnit.class))).thenReturn(
      Observable.error(new CouchbaseException()));
  assertTrue(writeFunction.putAsync(key, value).isCompletedExceptionally());
}
 
Example 15
Source Project: samza   Source File: TestCouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAsyncJsonObjectValue() throws Exception {
  String key = "key";
  JsonObject value = JsonObject.fromJson("{\"id\": 1}");
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableWriteFunction<JsonObject> writeFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.upsert(any(Document.class), anyLong(), any(TimeUnit.class))).thenReturn(Observable.just(null));
  assertNull(writeFunction.putAsync(key, value).get());
}
 
Example 16
Source Project: samza   Source File: TestCouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteAsyncException() {
  String key = "throwExceptionKey";
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableWriteFunction<JsonObject> writeFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.remove(eq(key), anyLong(), any(TimeUnit.class))).thenReturn(
      Observable.error(new CouchbaseException()));
  assertTrue(writeFunction.deleteAsync(key).isCompletedExceptionally());
}
 
Example 17
Source Project: samza   Source File: TestCouchbaseTableWriteFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteAsyncJsonObjectValue() throws Exception {
  String key = "key";
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableWriteFunction<JsonObject> writeFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.remove(eq(key), anyLong(), any(TimeUnit.class))).thenReturn(Observable.just(null));
  assertNull(writeFunction.deleteAsync(key).get());
}
 
Example 18
Source Project: samza   Source File: TestCouchbaseTableReadFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAsyncJsonObjectValue() throws Exception {
  String key = "key";
  JsonObject value = JsonObject.fromJson("{\"id\": 1}");
  Bucket bucket = mock(Bucket.class);
  AsyncBucket asyncBucket = mock(AsyncBucket.class);
  CouchbaseTableReadFunction readFunction = createAndInit(bucket, asyncBucket);
  when(asyncBucket.get(eq(key), anyObject(), anyLong(), any(TimeUnit.class))).thenReturn(
      Observable.just(JsonDocument.create(key, value)));
  assertEquals(value, readFunction.getAsync(key).get());
}
 
Example 19
Source Project: datacollector   Source File: CouchbaseProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes sub-document lookup values to the record
 *
 * @param record the record being processed
 * @param frag the sub-document fragment from Couchbase
 * @return an Observable of the updated record
 */
private Observable<Record> setFragmentInRecord(Record record, DocumentFragment<Lookup> frag) {
  if(frag.content(0) == null) {
    LOG.debug("Sub-document path not found");
    return handleError(record, Errors.COUCHBASE_25, true);
  }

  for(SubdocMappingConfig subdocMapping : config.subdocMappingConfigs) {
   Object fragJson = frag.content(subdocMapping.subdocPath);

    if(fragJson == null) {
      return handleError(record, Errors.COUCHBASE_25, true);
    }

    try {
      record.set(subdocMapping.sdcField, jsonToField(fragJson));
      record.getHeader().setAttribute(config.CAS_HEADER_ATTRIBUTE, String.valueOf(frag.cas()));
    } catch (IOException e) {
      try {
        record.set(subdocMapping.sdcField, jsonToField(JsonObject.fromJson(fragJson.toString()).toMap()));
        record.getHeader().setAttribute(config.CAS_HEADER_ATTRIBUTE, String.valueOf(frag.cas()));
      } catch (IOException ex) {
        return handleError(record, Errors.COUCHBASE_19, ex, false);
      }
    }
  }

  return Observable.just(record);
}
 
Example 20
Source Project: datacollector   Source File: CouchbaseProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes N1QL query result rows to the record
 *
 * @param record the record being processed
 * @param row the current row from the N1QL query result
 * @return an Observable of the updated record
 */
private Observable<Record> setN1QLRowInRecord(Record record, AsyncN1qlQueryRow row) {

  for(N1QLMappingConfig n1qlMapping : config.n1qlMappingConfigs) {
    if (config.multipleValueOperation == MultipleValueType.FIRST && record.get(n1qlMapping.sdcField) != null) {
      LOG.debug("Only populating output field with first record. Skipping additional result.");
      return Observable.empty();
    }

    Object property = row.value().get(n1qlMapping.property);

    if (property == null) {
      LOG.debug("Requested property not returned: {}", n1qlMapping.property);
      return handleError(record, Errors.COUCHBASE_27, true);
    }

    try {
      record.set(n1qlMapping.sdcField, jsonToField(property));
    } catch (IOException e) {
      try {
        record.set(n1qlMapping.sdcField, jsonToField(JsonObject.fromJson(property.toString()).toMap()));
      } catch (IOException ex) {
        LOG.debug("Unable to set N1QL property in record");
        return handleError(record, Errors.COUCHBASE_19, ex, false);
      }
    }
  }
  return Observable.just(record);
}
 
Example 21
Source Project: incubator-gobblin   Source File: CouchbaseTestServer.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public static void testServer()
    throws InterruptedException, IOException {
  CouchbaseTestServer couchbaseTestServer = new CouchbaseTestServer(TestUtils.findFreePort());
  couchbaseTestServer.start();

  int port = couchbaseTestServer.getPort();
  int serverPort = couchbaseTestServer.getServerPort();



  try {
    CouchbaseEnvironment cbEnv = DefaultCouchbaseEnvironment.builder().bootstrapHttpEnabled(true)
        .bootstrapHttpDirectPort(port)
        .bootstrapCarrierDirectPort(serverPort)
        .connectTimeout(TimeUnit.SECONDS.toMillis(15))
        .bootstrapCarrierEnabled(true).build();
    CouchbaseCluster cbCluster = CouchbaseCluster.create(cbEnv, "localhost");
    Bucket bucket = cbCluster.openBucket("default","");
    try {
      JsonObject content = JsonObject.empty().put("name", "Michael");
      JsonDocument doc = JsonDocument.create("docId", content);
      JsonDocument inserted = bucket.insert(doc);
    }
    catch (Exception e)
    {
      Assert.fail("Should not throw exception on insert", e);
    }
  }
  finally
  {
    couchbaseTestServer.stop();
  }
}
 
Example 22
Source Project: nosql4idea   Source File: CouchbaseTreeModel.java    License: Apache License 2.0 5 votes vote down vote up
public static NoSqlTreeNode buildTree(CouchbaseResult couchbaseResult) {
    NoSqlTreeNode resultTreeNode = new NoSqlTreeNode(new CouchbaseResultDescriptor(couchbaseResult.getName()));
    for (JsonObject record : couchbaseResult.getRecords()) {
        processRecord(resultTreeNode, record);
    }

    return resultTreeNode;
}
 
Example 23
Source Project: nosql4idea   Source File: CouchbaseTreeModel.java    License: Apache License 2.0 5 votes vote down vote up
private static void processRecord(NoSqlTreeNode parentNode, JsonObject record) {
    for (String key : record.getNames()) {
        Object value = record.get(key);
        NoSqlTreeNode currentNode = new NoSqlTreeNode(CouchbaseKeyValueDescriptor.createDescriptor(key, value));
        if (value instanceof JsonArray) {
            processRecordListValues(currentNode, (JsonArray) value);
        } else if (value instanceof JsonObject) {
            processRecord(currentNode, (JsonObject) value);
        }

        parentNode.add(currentNode);
    }
}
 
Example 24
Source Project: nosql4idea   Source File: CouchbaseTreeModel.java    License: Apache License 2.0 5 votes vote down vote up
private static void processRecordListValues(NoSqlTreeNode parentNode, JsonArray values) {
    int index = 0;
    for (Object value : values) {
        NoSqlTreeNode currentValueNode = new NoSqlTreeNode(CouchbaseValueDescriptor.createDescriptor(index++, value));
        if (value instanceof JsonArray) {
            processRecordListValues(currentValueNode, (JsonArray) value);
        } else if (value instanceof JsonObject) {
            processRecord(currentValueNode, (JsonObject) value);
        }
        parentNode.add(currentValueNode);
    }
}
 
Example 25
Source Project: nosql4idea   Source File: CouchbaseClient.java    License: Apache License 2.0 5 votes vote down vote up
public CouchbaseResult loadRecords(ServerConfiguration configuration, CouchbaseDatabase database, CouchbaseQuery couchbaseQuery) {
        Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment
                .builder()
                .queryEnabled(true)
                .build(),
                configuration.getServerUrl());
//        AuthenticationSettings authenticationSettings = configuration.getAuthenticationSettings();
//        ClusterManager clusterManager = cluster.clusterManager(authenticationSettings.getUsername(), authenticationSettings.getPassword());

        Bucket beerBucket = cluster.openBucket(database.getName(), 10, TimeUnit.SECONDS);
        N1qlQueryResult queryResult = beerBucket.query(N1qlQuery.simple(select("*").from(i(database.getName())).limit(couchbaseQuery.getLimit())));

//TODO dirty zone :(
        CouchbaseResult result = new CouchbaseResult(database.getName());
        List<JsonObject> errors = queryResult.errors();
        if (!errors.isEmpty()) {
            cluster.disconnect();
            result.addErrors(errors);
            return result;
        }

        for (N1qlQueryRow row : queryResult.allRows()) {
            result.add(row.value());
        }
        cluster.disconnect();
        return result;
    }
 
Example 26
Source Project: nosql4idea   Source File: CouchbaseClientTest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment
            .builder()
            .queryEnabled(true)
            .build());

    Bucket defaultBucket = cluster.openBucket("default");
    defaultBucket.remove("user:walter");

    JsonArray friends = JsonArray.empty()
            .add(JsonObject.empty().put("name", "Mike Ehrmantraut"))
            .add(JsonObject.empty().put("name", "Jesse Pinkman"));

    JsonObject content = JsonObject.empty()
            .put("firstname", "Walter")
            .put("lastname", "White")
            .put("age", 52)
            .put("aliases", JsonArray.from("Walt Jackson", "Mr. Mayhew", "David Lynn"))
            .put("friends", friends);
    JsonDocument walter = JsonDocument.create("user:walter", content);
    JsonDocument inserted = defaultBucket.insert(walter);

    JsonDocument foundGuy = defaultBucket.get("user:walter");
    System.out.println(foundGuy.content().toMap());


    Bucket beerBucket = cluster.openBucket("beer-sample");
    N1qlQueryResult result = beerBucket.query(N1qlQuery.simple(select("*").from(i("beer-sample")).limit(10)));

    System.out.println("Errors found: " + result.errors());

    for (N1qlQueryRow row : result.allRows()) {
        JsonObject jsonObject = row.value();
        System.out.println(jsonObject.toMap());
    }

    cluster.disconnect();
}
 
Example 27
Source Project: incubator-pinot   Source File: CacheUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildDocumentStructureShouldMapToJsonObject() {
  JsonObject mappedDataPoint = CacheUtils.buildDocumentStructure(dataPoint);

  Assert.assertEquals(mappedDataPoint.getLong("timestamp").longValue(), 1234567);
  Assert.assertEquals(mappedDataPoint.getLong("metricId").longValue(), 1);
  Assert.assertEquals(mappedDataPoint.getDouble(dataPoint.getMetricUrnHash()), (double)100);
}
 
Example 28
Source Project: incubator-pinot   Source File: CacheUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildDocumentStructureShouldMapNullDataValueToZero() {
  dataPoint.setDataValue(null);
  JsonObject mappedDataPoint = CacheUtils.buildDocumentStructure(dataPoint);

  Assert.assertEquals(mappedDataPoint.getDouble(dataPoint.getMetricUrnHash()), (double)0);
}
 
Example 29
Source Project: incubator-pinot   Source File: CacheUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildDocumentStructureShouldMapNullStringDataValueToZero() {
  dataPoint.setDataValue("null");
  JsonObject mappedDataPoint = CacheUtils.buildDocumentStructure(dataPoint);

  Assert.assertEquals(mappedDataPoint.getDouble(dataPoint.getMetricUrnHash()), (double)0);
}
 
Example 30
Source Project: hazelcast-simulator   Source File: BucketReadWriteTest.java    License: Apache License 2.0 5 votes vote down vote up
@Prepare(global = true)
public void prepare() {
    Random random = new Random();
    for (int k = 0; k < keyDomain; k++) {
        JsonObject content = JsonObject.create().put("x", values[random.nextInt(valueCount)]);
        bucket.upsert(JsonDocument.create("" + k, content));
    }
}