com.couchbase.client.java.document.json.JsonObject类的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(12.5k)|赞(0)|评价(0)|浏览(149)

本文整理了Java中com.couchbase.client.java.document.json.JsonObject类的一些代码示例,展示了JsonObject类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonObject类的具体详情如下:
包路径:com.couchbase.client.java.document.json.JsonObject
类名称:JsonObject

JsonObject介绍

[英]Represents a JSON object that can be stored and loaded from Couchbase Server. If boxed return values are unboxed, the calling code needs to make sure to handle potential NullPointerExceptions. The JsonObject is backed by a Map and is intended to work similar to it API wise, but to only allow to store such objects which can be represented by JSON.
[中]表示可以从Couchbase服务器存储和加载的JSON对象。如果取消装箱返回值,则调用代码需要确保处理潜在的NullPointerException。JsonObject由一个映射支持,其工作原理与它的API类似,但只允许存储可以用JSON表示的对象。

代码示例

代码示例来源:origin: brianfrankcooper/YCSB

/**
 * Helper method to turn the map of values into a {@link JsonObject} for further use.
 *
 * @param values the values to transform.
 * @return the created json object.
 */
private static JsonObject valuesToJsonObject(final Map<String, ByteIterator> values) {
 JsonObject result = JsonObject.create();
 for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
  result.put(entry.getKey(), entry.getValue().toString());
 }
 return result;
}

代码示例来源:origin: testcontainers/testcontainers-java

@Test
public void shouldExecuteN1ql() {
  getBucket().query(N1qlQuery.simple("INSERT INTO " + TEST_BUCKET + " (KEY, VALUE) VALUES ('" + ID + "', " + DOCUMENT + ")"));
  N1qlQueryResult query = getBucket().query(N1qlQuery.simple("SELECT * FROM " + TEST_BUCKET + " USE KEYS '" + ID + "'"));
  Assert.assertTrue(query.parseSuccess());
  Assert.assertTrue(query.finalSuccess());
  List<N1qlQueryRow> n1qlQueryRows = query.allRows();
  Assert.assertEquals(1, n1qlQueryRows.size());
  Assert.assertEquals(DOCUMENT, n1qlQueryRows.get(0).value().get(TEST_BUCKET).toString());
}

代码示例来源:origin: jooby-project/jooby

@Override
public <T> EntityDocument<T> toEntity(final JsonDocument source, final Class<T> clazz) {
 JsonObject json = source.content();
 // favor embedded type over provided type
 Class<T> type = type(json.getString(N1Q.CLASS), clazz);
 T value = mapper.convertValue(json, type);
 return EntityDocument.create(source.id(), value);
}

代码示例来源:origin: jooby-project/jooby

@Override
public void save(final Session session) {
 JsonObject json = JsonObject.from(session.attributes());
 // session metadata
 json.put("_accessedAt", session.accessedAt());
 json.put("_createdAt", session.createdAt());
 json.put("_savedAt", session.savedAt());
 JsonDocument doc = JsonDocument.create(N1Q.qualifyId(SESSION, session.id()), expiry, json);
 bucket.upsert(doc);
}

代码示例来源:origin: brianfrankcooper/YCSB

JsonObject value = row.value();
if (fields == null) {
 value = value.getObject(bucketName);
Set<String> f = allFields ? value.getNames() : fields;
HashMap<String, ByteIterator> tuple = new HashMap<String, ByteIterator>(f.size());
for (String field : f) {
 tuple.put(field, new StringByteIterator(value.getString(field)));

代码示例来源:origin: org.jnosql.diana/couchbase-driver

@Override
public DocumentEntity insert(DocumentEntity entity, Duration ttl) {
  requireNonNull(entity, "entity is required");
  requireNonNull(ttl, "ttl is required");
  JsonObject jsonObject = convert(entity);
  Document id = entity.find(ID_FIELD)
      .orElseThrow(() -> new CouchbaseNoKeyFoundException(entity.toString()));
  String prefix = getPrefix(id, entity.getName());
  jsonObject.put(KEY_FIELD, prefix);
  bucket.upsert(JsonDocument.create(prefix, (int) ttl.getSeconds(), jsonObject));
  return entity;
}

代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures

@Test
public void testInsertAndRemoveDocument() {
  PasswordAuthenticator passwordAuthenticator = new PasswordAuthenticator(USERNAME, PASSWORD);
  try (CouchbaseConnection connection = new CouchbaseConnection(Arrays.asList("couchbase://localhost"), passwordAuthenticator, BUCKET_NAME, null, ENV);) {
    JsonDocument document = connection.upsert("test", JsonObject.create().put("test", "test").toString());
    Assert.assertEquals("test", document.content().get("test"));
    connection.remove("test");
    Assert.assertNull(connection.get("test"));
  }
}

代码示例来源:origin: apache/incubator-gobblin

Bucket bucket = cbCluster.openBucket("default","");
try {
 JsonObject content = JsonObject.empty().put("name", "Michael");
 JsonDocument doc = JsonDocument.create("docId", content);
 JsonDocument inserted = bucket.insert(doc);

代码示例来源:origin: neo4j-contrib/neo4j-apoc-procedures

@Test
public void testRemove() {
  try {
    //@eclipse-formatter:off
    couchbaseBucket.insert(JsonDocument.create("testRemove", JsonObject.empty()));
    new Couchbase().remove(HOST, BUCKET_NAME, "testRemove");
    assertFalse(couchbaseBucket.exists("testRemove"));
    //@eclipse-formatter:on
  } catch (Exception e) {
    e.printStackTrace();
    fail();
  }
}

代码示例来源:origin: com.couchbase.client/java-client

private void addEncryption(JsonObject content) throws Exception {
   try {
     if (content != null && content.encryptionPathInfo() != null) {
       for (Map.Entry<String, String> entry : content.encryptionPathInfo().entrySet()) {
         String providerName = entry.getValue();
         String[] pathSplit = entry.getKey().split("/");
           parent = (JsonObject) parent.get(pathSplit[i]);
         Object value = parent.get(lastPointer);
         JsonObject encryptedVal = JsonObject.create();
         CryptoProvider provider = this.cryptoManager.getProvider(providerName);
         String jsonValue = JacksonTransformers.MAPPER.writeValueAsString(value);
         encryptedVal.put("kid", provider.getKeyStoreProvider().publicKeyName());
         encryptedVal.put("alg", provider.getProviderName());
           System.arraycopy(encryptedwithIv, 0, iv, 0, ivSize);
           System.arraycopy(encryptedwithIv, ivSize, encryptedBytes, 0, encryptedBytes.length);
           encryptedVal.put("iv", Base64.encode(iv));
           encryptedVal.put("ciphertext", Base64.encode(encryptedBytes));
           encryptedValString = encryptedVal.getString("kid") + encryptedVal.getString("alg")
               + encryptedVal.getString("iv") + encryptedVal.getString("ciphertext");
         } else {
           encryptedVal.put("ciphertext", Base64.encode(provider.encrypt(jsonValue.getBytes())));
           encryptedValString = encryptedVal.getString("kid") + encryptedVal.getString("alg")
               + encryptedVal.getString("ciphertext");
           encryptedVal.put("sig", Base64.encode(provider.getSignature(encryptedValString.getBytes())));

代码示例来源:origin: com.couchbase.client/java-client

@Override
  public JsonObject query() {
    JsonObject query = super.query();

    if (named != null && !named.isEmpty()) {
      for (String key : named.getNames()) {
        Object value = named.get(key);
        if (!key.startsWith("$")) {
          key = "$" + key;
        }
        query.put(key, value);
      }
    }
    if (positional != null && !positional.isEmpty()) {
      query.put("args", positional);
    }
    return query;
  }
}

代码示例来源:origin: com.couchbase.client/java-client

JsonObject jsonStatus = json.getObject("status");
SearchStatus status = new DefaultSearchStatus(
    jsonStatus.getLong("total"),
    jsonStatus.getLong("failed"),
    jsonStatus.getLong("successful"));
long totalHits = json.getLong("total_hits");
long took = json.getLong("took");
double maxScore = json.getDouble("max_score");
SearchMetrics metrics = new DefaultSearchMetrics(took, totalHits, maxScore);
JsonArray rawHits = json.getArray("hits");
if (rawHits != null) {
  for (Object rawHit : rawHits) {
    JsonObject hit = (JsonObject) rawHit;
    String index = hit.getString("index");
    String id = hit.getString("id");
    double score = hit.getDouble("score");
    JsonObject explanationJson = hit.getObject("explanation");
    if (explanationJson == null) {
      explanationJson = JsonObject.empty();
    HitLocations locations = DefaultHitLocations.from(hit.getObject("locations"));
    JsonObject fragmentsJson = hit.getObject("fragments");
    Map<String, List<String>> fragments;
    if (fragmentsJson != null) {
      fragments = new HashMap<String, List<String>>(fragmentsJson.size());
      for (String field : fragmentsJson.getNames()) {

代码示例来源:origin: lagom/lagom-recipes

private CompletionStage<Done> processGreetingMessageChanged(CouchbaseSession session, HelloEvent.GreetingMessageChanged evt) {
  return session.get(DOC_ID).thenComposeAsync(docOpt -> {
    JsonDocument doc = docOpt.get(); // document should've been created in globalPrepare
    doc.content().put(evt.name, evt.message);
    return session.upsert(doc);
  }).thenApply(ignore -> Done.getInstance());
}

代码示例来源:origin: lukas-krecan/ShedLock

@Override
public boolean updateRecord(LockConfiguration lockConfiguration) {
  try {
    JsonDocument document = bucket.get(lockConfiguration.getName());
    Instant lockUntil = parse(document.content().get(LOCK_UNTIL));
    Instant now = Instant.now();
    if (lockUntil.isAfter(now)) {
      return false;
    }
    document.content().put(LOCK_UNTIL, toIsoString(lockConfiguration.getLockAtMostUntil()));
    document.content().put(LOCKED_AT, toIsoString(now));
    document.content().put(LOCKED_BY, getHostname());
    bucket.replace(document);
    return true;
  }catch (CASMismatchException e){
    return false;
  }
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
public <T> EntityDocument<T> toEntity(JsonDocument source, Class<T> clazz) {
  try {
    EntityMetadata entityMetadata = metadata(clazz);
    T instance = clazz.newInstance(); // for now only support no-args constructor
    if (source.content() != null) {
      for (PropertyMetadata propertyMetadata : entityMetadata.properties()) {
        String fieldName = propertyMetadata.name();
        if (source.content().containsKey(JsonObject.ENCRYPTION_PREFIX + fieldName)) {
          propertyMetadata.set(source.content().getAndDecrypt(fieldName, propertyMetadata.encryptionProviderName()), instance);
        } else if(source.content().containsKey(fieldName)) {
          propertyMetadata.set(source.content().get(fieldName), instance);
        }
      }
    }
    if (entityMetadata.hasIdProperty()) {
      entityMetadata.idProperty().set(source.id(), instance);
    }
    return EntityDocument.create(source.id(), source.expiry(), instance, source.cas());
  } catch (Exception e) {
    throw new RepositoryMappingException("Could not instantiate entity.", e);
  }
}

代码示例来源:origin: com.couchbase.client/java-client

@Override
  protected void injectParams(JsonObject input) {
    input.put("match_all", (String) null);
  }
}

代码示例来源:origin: com.couchbase.client/java-client

/**
 * Exports the {@link MutationState} into a universal format, which can be used either to serialize it into
 * a N1QL query or to send it over the network to a different application/SDK.
 *
 * @return the exported {@link JsonObject}.
 */
public JsonObject export() {
  JsonObject result = JsonObject.create();
  for (MutationToken token : tokens) {
    JsonObject bucket = result.getObject(token.bucket());
    if (bucket == null) {
      bucket = JsonObject.create();
      result.put(token.bucket(), bucket);
    }
    bucket.put(
      String.valueOf(token.vbucketID()),
      JsonArray.from(token.sequenceNumber(), String.valueOf(token.vbucketUUID()))
    );
  }
  return result;
}

代码示例来源:origin: org.springframework.data/spring-data-couchbase

@Override
public <T>Observable<T> findByN1QL(N1qlQuery query, Class<T> entityClass) {
  return queryN1QL(query)
      .flatMap(asyncN1qlQueryResult -> asyncN1qlQueryResult.errors()
          .flatMap(error -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute n1ql query due to error:" + error.toString())))
          .switchIfEmpty(asyncN1qlQueryResult.rows()))
      .map(row -> {
        JsonObject json = ((AsyncN1qlQueryRow)row).value();
        String id = json.getString(TemplateUtils.SELECT_ID);
        Long cas = json.getLong(TemplateUtils.SELECT_CAS);
        if (id == null || cas == null) {
          throw new CouchbaseQueryExecutionException("Unable to retrieve enough metadata for N1QL to entity mapping, " +
              "have you selected " + TemplateUtils.SELECT_ID + " and " + TemplateUtils.SELECT_CAS + "?");
        }
        json = json.removeKey(TemplateUtils.SELECT_ID).removeKey(TemplateUtils.SELECT_CAS);
        RawJsonDocument entityDoc = RawJsonDocument.create(id, json.toString(), cas);
        T decoded = mapToEntity(id, entityDoc, entityClass);
        return decoded;
      })
      .doOnError(throwable -> Observable.error(new CouchbaseQueryExecutionException("Unable to execute n1ql query", throwable)));
}

代码示例来源:origin: Impetus/Kundera

/**
 * Validate query results.
 *
 * @param query
 *            the query
 * @param result
 *            the result
 */
private void validateQueryResults(String query, N1qlQueryResult result)
{
  LOGGER.debug("Query output status: " + result.finalSuccess());
  if (!result.finalSuccess())
  {
    StringBuilder errorBuilder = new StringBuilder();
    for (JsonObject obj : result.errors())
    {
      errorBuilder.append(obj.toString());
      errorBuilder.append("\n");
    }
    errorBuilder.deleteCharAt(errorBuilder.length() - 1);
    String errors = errorBuilder.toString();
    LOGGER.error(errors);
    throw new KunderaException("Not able to execute query/statement:" + query + ". More details : " + errors);
  }
}

代码示例来源:origin: ff4j/ff4j

/** {@inheritDoc} */
@Override
public Feature fromStore(JsonDocument jsonDoc) {
  if (jsonDoc == null) return null;
  return FeatureJsonParser.parseFeature(jsonDoc.content().toString());
}

相关文章