Java源码示例:com.couchbase.client.java.document.json.JsonArray

示例1
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;
}
 
示例2
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);
}
 
示例3
public Map<String, Long> countStudentsByCourse() {
    ViewQuery query = ViewQuery.from("studentGrades", "countStudentsByCourse")
            .reduce()
            .groupLevel(1);
    ViewResult result = bucket.query(query);
    
    Map<String, Long> numStudentsByCourse = new HashMap<>();
    for(ViewRow row : result.allRows()) {
        JsonArray keyArray = (JsonArray) row.key();
        String course = keyArray.getString(0);
        long count = Long.valueOf(row.value().toString());
        numStudentsByCourse.put(course, count);
    }
    
    return numStudentsByCourse;
}
 
示例4
@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);
}
 
示例5
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));
}
 
示例6
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);
    }
}
 
示例7
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);
    }
}
 
示例8
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();
}
 
示例9
public ViewQuery findTopGradesByCourse(String course, int limit) {
    return ViewQuery.from("studentGrades", "findByCourseAndGrade")
            .startKey(JsonArray.from(course, 100))
            .endKey(JsonArray.from(course, 0))
            .inclusiveEnd(true)
            .descending()
            .limit(limit);
}
 
示例10
@Test
public void givenDocument_whenInsert_thenResult() {
    Bucket bucket = bucketFactory.getTestBucket();
    JsonObject personObj = JsonObject.create()
            .put("name", "John")
            .put("email", "[email protected]")
            .put("interests", JsonArray.from("Java", "Nigerian Jollof"));

    String id = UUID.randomUUID().toString();
    JsonDocument doc = JsonDocument.create(id, personObj);
    bucket.insert(doc);
    assertNotNull(bucket.get(id));
}
 
示例11
private JsonObject createStructuredJsonObject(){
    JsonObject jsonObjectInnerInner = JsonObject.create();
    jsonObjectInnerInner.put("val1", 40);
    jsonObjectInnerInner.put("val2", 20.2);
    jsonObjectInnerInner.put("val3", true);

    JsonObject jsonObjectInner = JsonObject.create();
    jsonObjectInner.put("mobile", "0989901515");
    jsonObjectInner.put("home", "0342556644");
    jsonObjectInner.put("inner", jsonObjectInnerInner);
    jsonObjectInner.put("some", "444444");

    JsonObject jsonObjectOuterOuter = JsonObject.create();
    jsonObjectOuterOuter.put("id", "0017");
    jsonObjectOuterOuter.put("name", "Patrik");
    jsonObjectOuterOuter.put("surname", "Human");
    jsonObjectOuterOuter.put("tel" ,jsonObjectInner);

    JsonArray jsonArray = JsonArray.create();
    jsonArray.add("one");
    jsonArray.add("two");
    jsonArray.add("three");

    jsonObjectOuterOuter.put("numbers", jsonArray);

    JsonObject innerArray1 = JsonObject.create();
    innerArray1.put("arr01", 1);
    innerArray1.put("arr02", 2);
    innerArray1.put("arr03", 3);

    JsonObject innerArray2 = JsonObject.create();
    innerArray2.put("arr01", 4);
    innerArray2.put("arr02", 5);
    innerArray2.put("arr03", 6);

    JsonArray jsonArray1 = JsonArray.create();
    jsonArray1.add(innerArray1);
    jsonArray1.add(innerArray2);

    jsonObjectOuterOuter.put("arrWithJSON", jsonArray1);

    return JsonObject.create().put("val_str_like_json", jsonObjectOuterOuter).put("val_str", "str");
}
 
示例12
@Ignore("This test method requires a live Couchbase Server instance")
@Test
public void testDocumentTypesAndStringConversion() {
    final CouchbaseCluster cluster = CouchbaseCluster.fromConnectionString("couchbase://192.168.99.100:8091");
    final Bucket bucket = cluster.openBucket("b1", "b1password");

    bucket.upsert(JsonDocument.create("JsonDocument", JsonObject.create().put("one", 1)));
    bucket.upsert(JsonArrayDocument.create("JsonArray", JsonArray.create().add(1).add(2).add(3)));
    bucket.upsert(JsonDoubleDocument.create("JsonDouble", 0.123));
    bucket.upsert(JsonStringDocument.create("JsonString", "value"));
    bucket.upsert(JsonBooleanDocument.create("JsonBoolean", true));
    bucket.upsert(JsonLongDocument.create("JsonLong", 123L));

    bucket.upsert(RawJsonDocument.create("RawJsonDocument", "value"));
    bucket.upsert(StringDocument.create("StringDocument", "value"));

    bucket.upsert(BinaryDocument.create("BinaryDocument", Unpooled.copiedBuffer("value".getBytes(StandardCharsets.UTF_8))));
    bucket.upsert(ByteArrayDocument.create("ByteArrayDocument", "value".getBytes(StandardCharsets.UTF_8)));

    final String[][] expectations = {
            {"JsonDocument", "String", "{\"one\":1}"},
            {"JsonArray", "String", "[1,2,3]"},
            {"JsonDouble", "String", "0.123"},
            {"JsonString", "String", "\"value\""},
            {"JsonBoolean", "String", "true"},
            {"JsonLong", "String", "123"},
            {"RawJsonDocument", "String", "value"},
            {"StringDocument", "String", "value"},
            {"BinaryDocument", "byte[]", "value"},
            {"ByteArrayDocument", "byte[]", "value"},
    };

    for (String[] expectation : expectations) {
        final LegacyDocument document = bucket.get(LegacyDocument.create(expectation[0]));
        assertEquals(expectation[1], document.content().getClass().getSimpleName());
        assertEquals(expectation[2], CouchbaseUtils.getStringContent(document.content()));
    }

    final BinaryDocument binaryDocument = bucket.get(BinaryDocument.create("BinaryDocument"));
    final String stringFromByteBuff = CouchbaseUtils.getStringContent(binaryDocument.content());
    assertEquals("value", stringFromByteBuff);

    try {
        bucket.get(BinaryDocument.create("JsonDocument"));
        fail("Getting a JSON document as a BinaryDocument fails");
    } catch (TranscodingException e) {
        assertTrue(e.getMessage().contains("Flags (0x2000000) indicate non-binary document for id JsonDocument"));
    }

}
 
示例13
public ViewQuery findByCourses(String... courses) {
    return ViewQuery.from("studentGrades", "findByCourse")
            .keys(JsonArray.from(courses));
}
 
示例14
public ViewQuery findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) {
    return ViewQuery.from("studentGrades", "findByCourseAndGrade")
            .startKey(JsonArray.from(course, minGrade))
            .endKey(JsonArray.from(course, maxGrade))
            .inclusiveEnd(inclusiveEnd);
}