Java Code Examples for com.couchbase.client.java.document.JsonDocument#create()
The following examples show how to use
com.couchbase.client.java.document.JsonDocument#create() .
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: CouchbaseLockProvider.java From ShedLock with Apache License 2.0 | 6 votes |
@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 File: CouchbaseInputTestIT.java From components with Apache License 2.0 | 6 votes |
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 3
Source File: CouchbaseCacheDAO.java From incubator-pinot with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: ButtonDocument.java From serverless with Apache License 2.0 | 5 votes |
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 5
Source File: CouchbaseTableWriteFunction.java From samza with Apache License 2.0 | 5 votes |
@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 6
Source File: CouchbaseTestServer.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@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 7
Source File: CouchbaseClientTest.java From nosql4idea with Apache License 2.0 | 5 votes |
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 8
Source File: StudentGradeService.java From tutorials with MIT License | 5 votes |
public String insert(StudentGrade studentGrade) throws DuplicateKeyException { String id = keyGenerator.generateKey(studentGrade); if(bucket.exists(id)) { throw new DuplicateKeyException("document already exists with key " + id); } JsonObject content = JsonObject.empty() .put("type", "StudentGrade") .put("name", studentGrade.getName()) .put("course", studentGrade.getCourse()) .put("grade", studentGrade.getGrade()) .put("hours", studentGrade.getHours()); JsonDocument doc = JsonDocument.create(id, content); bucket.insert(doc); return id; }
Example 9
Source File: CodeSnippets.java From tutorials with MIT License | 5 votes |
static JsonDocument insertExample(Bucket bucket) { JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "[email protected]").put("homeTown", "Chicago"); String id = UUID.randomUUID().toString(); JsonDocument document = JsonDocument.create(id, content); JsonDocument inserted = bucket.insert(document); return inserted; }
Example 10
Source File: N1QLLiveTest.java From tutorials with MIT License | 5 votes |
@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)); }
Example 11
Source File: CouchbaseTarget.java From datacollector with Apache License 2.0 | 4 votes |
/** * Executes a document write operation. * * @param key the document key * @param ttl the document expiry ttl * @param cas the compare-and-swap (CAS) value to apply to the write * @param baos the raw document content * @param record the record being written * @return an observable for the document write or an empty observable on error */ private Observable<AbstractDocument> writeDoc(String key, int ttl, long cas, ByteArrayOutputStream baos, Record record) { WriteOperationType opType = getOperationFromHeader(record, key); if(opType == null) { return Observable.empty(); } AbstractDocument doc; if(config.dataFormat == DataFormat.JSON) { try { doc = JsonDocument.create(key, ttl, JsonObject.fromJson(baos.toString(config.dataFormatConfig.charset)), cas); } catch(Exception e) { return handleError(record, Errors.COUCHBASE_10, e); } } else { doc = ByteArrayDocument.create(key, ttl, baos.toByteArray(), cas); } switch (opType) { case DELETE: { LOG.debug("DELETE key: {}, TTL: {}, CAS: {}", key, ttl, cas); return connector.bucket().remove(doc, config.persistTo, config.replicateTo) .timeout(config.couchbase.kvTimeout, TimeUnit.MILLISECONDS); } case INSERT: { LOG.debug("INSERT key: {}, TTL: {}, CAS: {}", key, ttl, cas); return connector.bucket().insert(doc, config.persistTo, config.replicateTo) .timeout(config.couchbase.kvTimeout, TimeUnit.MILLISECONDS); } case REPLACE: { LOG.debug("REPLACE key: {}, TTL: {}, CAS: {}", key, ttl, cas); return connector.bucket().replace(doc, config.persistTo, config.replicateTo) .timeout(config.couchbase.kvTimeout, TimeUnit.MILLISECONDS); } case UPSERT: { LOG.debug("UPSERT key: {}, TTL: {}, CAS: {}", key, ttl, cas); return connector.bucket().upsert(doc, config.persistTo, config.replicateTo) .timeout(config.couchbase.kvTimeout, TimeUnit.MILLISECONDS); } default: return Observable.empty(); } }
Example 12
Source File: PersonDocumentConverter.java From tutorials with MIT License | 4 votes |
@Override public JsonDocument toDocument(Person p) { JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); return JsonDocument.create(p.getId(), content); }
Example 13
Source File: PersonDocumentConverter.java From tutorials with MIT License | 4 votes |
@Override public JsonDocument toDocument(Person p) { JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); return JsonDocument.create(p.getId(), content); }