From 5982086da60bc3d90f296d4bdd7f9b5fd97b09b9 Mon Sep 17 00:00:00 2001 From: Richard Smedley Date: Thu, 27 Nov 2025 13:02:50 +0000 Subject: [PATCH 1/3] classname match --- modules/devguide/examples/java/ArtSchoolRetrieverAll.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/devguide/examples/java/ArtSchoolRetrieverAll.java b/modules/devguide/examples/java/ArtSchoolRetrieverAll.java index 673c5275..58f71924 100644 --- a/modules/devguide/examples/java/ArtSchoolRetrieverAll.java +++ b/modules/devguide/examples/java/ArtSchoolRetrieverAll.java @@ -4,7 +4,7 @@ import com.couchbase.client.java.query.QueryResult; import com.couchbase.client.java.ClusterOptions; -public class ArtSchoolRetriever { +public class ArtSchoolRetrieverAll { public static void main(String[] args) { @@ -34,4 +34,4 @@ private static void retrieveCourses(Cluster cluster) { ex.printStackTrace(); } } -} \ No newline at end of file +} From d389b505613b8487396e63a79ebe37035ceaf553 Mon Sep 17 00:00:00 2001 From: Richard Smedley Date: Thu, 27 Nov 2025 13:08:56 +0000 Subject: [PATCH 2/3] deleted old files --- .../java/pending-deletion/BulkGet.java | 64 -------- .../java/pending-deletion/BulkInsert.java | 49 ------ .../java/pending-deletion/CasCheckAndSet.java | 118 --------------- .../examples/java/pending-deletion/Cloud.java | 139 ------------------ .../pending-deletion/ConnectingCertAuth.java | 67 --------- .../java/pending-deletion/ConnectingSsl.java | 87 ----------- .../java/pending-deletion/ConnectionBase.java | 81 ---------- .../java/pending-deletion/Counter.java | 59 -------- .../java/pending-deletion/Durability.java | 88 ----------- .../java/pending-deletion/Expiration.java | 100 ------------- .../pending-deletion/FieldEncryptionAES.java | 95 ------------ .../pending-deletion/HealthCheckExample.java | 116 --------------- .../pending-deletion/QueryConsistency.java | 80 ---------- .../java/pending-deletion/QueryCriteria.java | 86 ----------- .../pending-deletion/QueryPlaceholders.java | 96 ------------ .../java/pending-deletion/QueryPrepared.java | 93 ------------ .../java/pending-deletion/Retrieving.java | 49 ------ .../java/pending-deletion/SimpleConnect.java | 20 --- .../java/pending-deletion/Updating.java | 63 -------- .../java/student/examples/AddEnrollments.java | 84 ----------- .../student/examples/ArtSchoolRetriever.java | 30 ---- .../ArtSchoolRetrieverParameters.java | 35 ----- .../java/student/examples/ConnectStudent.java | 27 ---- .../java/student/examples/InsertCourses.java | 38 ----- .../java/student/examples/InsertStudent.java | 34 ----- .../examples/java/student/examples/pom.xml | 29 ---- 26 files changed, 1827 deletions(-) delete mode 100644 modules/devguide/examples/java/pending-deletion/BulkGet.java delete mode 100644 modules/devguide/examples/java/pending-deletion/BulkInsert.java delete mode 100644 modules/devguide/examples/java/pending-deletion/CasCheckAndSet.java delete mode 100644 modules/devguide/examples/java/pending-deletion/Cloud.java delete mode 100644 modules/devguide/examples/java/pending-deletion/ConnectingCertAuth.java delete mode 100644 modules/devguide/examples/java/pending-deletion/ConnectingSsl.java delete mode 100644 modules/devguide/examples/java/pending-deletion/ConnectionBase.java delete mode 100644 modules/devguide/examples/java/pending-deletion/Counter.java delete mode 100644 modules/devguide/examples/java/pending-deletion/Durability.java delete mode 100644 modules/devguide/examples/java/pending-deletion/Expiration.java delete mode 100644 modules/devguide/examples/java/pending-deletion/FieldEncryptionAES.java delete mode 100644 modules/devguide/examples/java/pending-deletion/HealthCheckExample.java delete mode 100644 modules/devguide/examples/java/pending-deletion/QueryConsistency.java delete mode 100644 modules/devguide/examples/java/pending-deletion/QueryCriteria.java delete mode 100644 modules/devguide/examples/java/pending-deletion/QueryPlaceholders.java delete mode 100644 modules/devguide/examples/java/pending-deletion/QueryPrepared.java delete mode 100644 modules/devguide/examples/java/pending-deletion/Retrieving.java delete mode 100644 modules/devguide/examples/java/pending-deletion/SimpleConnect.java delete mode 100644 modules/devguide/examples/java/pending-deletion/Updating.java delete mode 100644 modules/devguide/examples/java/student/examples/AddEnrollments.java delete mode 100644 modules/devguide/examples/java/student/examples/ArtSchoolRetriever.java delete mode 100644 modules/devguide/examples/java/student/examples/ArtSchoolRetrieverParameters.java delete mode 100644 modules/devguide/examples/java/student/examples/ConnectStudent.java delete mode 100644 modules/devguide/examples/java/student/examples/InsertCourses.java delete mode 100644 modules/devguide/examples/java/student/examples/InsertStudent.java delete mode 100644 modules/devguide/examples/java/student/examples/pom.xml diff --git a/modules/devguide/examples/java/pending-deletion/BulkGet.java b/modules/devguide/examples/java/pending-deletion/BulkGet.java deleted file mode 100644 index 6df90bbf..00000000 --- a/modules/devguide/examples/java/pending-deletion/BulkGet.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.ArrayList; -import java.util.List; - -import com.couchbase.client.java.ReactiveCollection; -import com.couchbase.client.java.json.JsonObject; - -import reactor.core.publisher.Flux; - -/** - * Example of Bulk Get in Java for the Couchbase Developer Guide. - */ -public class BulkGet extends ConnectionBase { - - @Override - protected void doWork() { - final String key = "javaDevguideExampleBulkGet"; - - // Create a JSON document content - final JsonObject content = JsonObject.create().put("item", "A bulk get test value"); - - // Prepare 10 keys - List keys = new ArrayList(10); - for (int i = 0; i < 10; i++) { - keys.add(key + "_" + i); - } - - // Insert 10 documents, the old way - for (String id : keys) { - collection.upsert(id, content); - } - - JsonObject jo = collection.get(key + "_1").contentAsObject(); - System.out.println(jo); - // Describe what we want to do asynchronously using RxJava Observables: - - ReactiveCollection reactiveCollection = collection.reactive(); - Flux resultFlux = Flux.range(0, 10) - .map(index -> { return key + "_" + index; }) - .flatMap(k -> reactiveCollection.get(k)); - - resultFlux.subscribe(System.out::println); - - } - - public static void main(String[] args) { - new BulkGet().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/BulkInsert.java b/modules/devguide/examples/java/pending-deletion/BulkInsert.java deleted file mode 100644 index 6da5a427..00000000 --- a/modules/devguide/examples/java/pending-deletion/BulkInsert.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.couchbase.client.java.ReactiveCollection; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.kv.MutationResult; - -import reactor.core.publisher.Flux; - -/** - * Example of Bulk Insert in Java for the Couchbase Developer Guide. - */ -public class BulkInsert extends ConnectionBase { - - @Override - protected void doWork() { - final String key = "javaDevguideExampleBulkInsert"; - - // Create a JSON document content - final JsonObject content = JsonObject.create().put("item", "A bulk insert test value"); - - // Describe what we want to do asynchronously using RxJava Observables: - - ReactiveCollection reactiveCollection = collection.reactive(); - Flux resultFlux = Flux.range(0, 10) - .map(index -> { return key + "_" + index; }) - .flatMap(k -> reactiveCollection.upsert(k, content)); - - resultFlux.subscribe(System.out::println); - - } - - public static void main(String[] args) { - new BulkInsert().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/CasCheckAndSet.java b/modules/devguide/examples/java/pending-deletion/CasCheckAndSet.java deleted file mode 100644 index 551bdf7e..00000000 --- a/modules/devguide/examples/java/pending-deletion/CasCheckAndSet.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.concurrent.CountDownLatch; - -import com.couchbase.client.java.json.JsonArray; -import com.couchbase.client.java.kv.GetResult; -import com.couchbase.client.java.kv.ReplaceOptions; - -/** - * Example of Cas (Check and Set) handling in Java for the Couchbase Developer - * Guide. - */ -public class CasCheckAndSet extends ConnectionBase { - - private static final int PARALLEL = 10; - private static final String KEY = "javaDevguideExampleCas"; - - @Override - protected void doWork() { - JsonArray initialDoc = JsonArray.create().add("initial"); - bucket.defaultCollection().upsert(KEY, initialDoc); - - LOGGER.info("Will attempt concurrent document mutations without CAS"); - parallel(false); - - JsonArray currentList = bucket.defaultCollection().get(KEY).contentAsArray(); - LOGGER.info("Current list has " + currentList.size() + " elements"); - if (currentList.size() != PARALLEL) { - LOGGER.info("Concurrent modifications removed some of our items! " + currentList.toString()); - } - - // Reset the list again - bucket.defaultCollection().upsert(KEY, initialDoc); - - // The same as above, but using CAS - LOGGER.info("Will attempt concurrent modifications using CAS"); - parallel(true); - - currentList = bucket.defaultCollection().get(KEY).contentAsArray(); - LOGGER.info("Current list has " + currentList.size() + " elements: " + currentList.toString()); - if (currentList.size() != PARALLEL) { - LOGGER.error("Expected the whole list of elements - " + currentList.toString()); - } - } - - public void iterationWithoutCAS(int idx, CountDownLatch latch) { - // this code plainly ignores the CAS by creating a new document (CAS O) - JsonArray l = bucket.defaultCollection().get(KEY).contentAsArray(); - l.add("value_" + idx); - bucket.defaultCollection().replace(KEY, l); - latch.countDown(); - } - - public void iterationWithCAS(int idx, CountDownLatch latch) { - String item = "item_" + idx; - - while (true) { - // GetResult current = bucket.defaultCollection().get(KEY); - // JsonArray l = bucket.defaultCollection().get(KEY).contentAsArray(); - // l.add( "value_"+idx); - - // we mutated the content of the document, and the SDK injected the CAS value in - // there as well - // so we can use it directly - try { - GetResult current = bucket.defaultCollection().get(KEY); - JsonArray l = current.contentAsArray(); - l.add("value_" + idx); - bucket.defaultCollection().replace(KEY, l, ReplaceOptions.replaceOptions().cas(current.cas())); - break; // success! stop the loop - } catch (RuntimeException e) { - // in case a parallel execution already updated the document, continue trying - LOGGER.info(e + " Cas mismatch for item " + item); - } - } - latch.countDown(); - } - - public void parallel(final boolean useCas) { - final CountDownLatch latch = new CountDownLatch(PARALLEL); - for (int i = 0; i < PARALLEL; i++) { - final int idx = i; - Runnable r = new Runnable() { - public void run() { - if (!useCas) { - iterationWithoutCAS(idx, latch); - } else { - iterationWithCAS(idx, latch); - } - } - }; - new Thread(r).start(); - } - try { - latch.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public static void main(String[] args) { - new CasCheckAndSet().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/Cloud.java b/modules/devguide/examples/java/pending-deletion/Cloud.java deleted file mode 100644 index 202561b0..00000000 --- a/modules/devguide/examples/java/pending-deletion/Cloud.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import static com.couchbase.client.java.query.QueryOptions.queryOptions; - -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.security.KeyStore; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import com.couchbase.client.core.deps.io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import com.couchbase.client.core.env.IoConfig; -import com.couchbase.client.core.env.SecurityConfig; -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.ClusterOptions; -import com.couchbase.client.java.Collection; -import com.couchbase.client.java.Scope; -import com.couchbase.client.java.env.ClusterEnvironment; -import com.couchbase.client.java.json.JsonArray; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.manager.query.CreatePrimaryQueryIndexOptions; -import com.couchbase.client.java.query.QueryResult; - -/** - * Example of Cas (Check and Set) handling in Java for the Couchbase Developer - * Guide ported from 2.x. See StartUsingCapella.java for 3.x. - */ - -public class Cloud { - // Update this to your certificate. - private static final String CERT = "-----BEGIN CERTIFICATE-----\n" - + "MIIDFTCCAf2gAwIBAgIRANLVkgOvtaXiQJi0V6qeNtswDQYJKoZIhvcNAQELBQAw\n" - + "JDESMBAGA1UECgwJQ291Y2hiYXNlMQ4wDAYDVQQLDAVDbG91ZDAeFw0xOTEyMDYy\n" - + "MjEyNTlaFw0yOTEyMDYyMzEyNTlaMCQxEjAQBgNVBAoMCUNvdWNoYmFzZTEOMAwG\n" - + "A1UECwwFQ2xvdWQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCfvOIi\n" - + "enG4Dp+hJu9asdxEMRmH70hDyMXv5ZjBhbo39a42QwR59y/rC/sahLLQuNwqif85\n" - + "Fod1DkqgO6Ng3vecSAwyYVkj5NKdycQu5tzsZkghlpSDAyI0xlIPSQjoORA/pCOU\n" - + "WOpymA9dOjC1bo6rDyw0yWP2nFAI/KA4Z806XeqLREuB7292UnSsgFs4/5lqeil6\n" - + "rL3ooAw/i0uxr/TQSaxi1l8t4iMt4/gU+W52+8Yol0JbXBTFX6itg62ppb/Eugmn\n" - + "mQRMgL67ccZs7cJ9/A0wlXencX2ohZQOR3mtknfol3FH4+glQFn27Q4xBCzVkY9j\n" - + "KQ20T1LgmGSngBInAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE\n" - + "FJQOBPvrkU2In1Sjoxt97Xy8+cKNMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0B\n" - + "AQsFAAOCAQEARgM6XwcXPLSpFdSf0w8PtpNGehmdWijPM3wHb7WZiS47iNen3oq8\n" - + "m2mm6V3Z57wbboPpfI+VEzbhiDcFfVnK1CXMC0tkF3fnOG1BDDvwt4jU95vBiNjY\n" - + "xdzlTP/Z+qr0cnVbGBSZ+fbXstSiRaaAVcqQyv3BRvBadKBkCyPwo+7svQnScQ5P\n" - + "Js7HEHKVms5tZTgKIw1fbmgR2XHleah1AcANB+MAPBCcTgqurqr5G7W2aPSBLLGA\n" - + "fRIiVzm7VFLc7kWbp7ENH39HVG6TZzKnfl9zJYeiklo5vQQhGSMhzBsO70z4RRzi\n" - + "DPFAN/4qZAgD5q3AFNIq2WWADFQGSwVJhg==\n" + "-----END CERTIFICATE-----"; - - public static void main(String... args) throws Exception { - // Update this to your cluster - String endpoint = "cb..dp.cloud.couchbase.com"; - String bucketName = "yourBucketName"; - String username = "user"; - String password = "password"; - // User Input ends here. - - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - trustStore.setCertificateEntry("server", decodeCertificates(Collections.singletonList(CERT)).get(0)); - - ClusterEnvironment env = ClusterEnvironment.builder() - .securityConfig( - SecurityConfig.enableTls(true).trustManagerFactory(InsecureTrustManagerFactory.INSTANCE)) - .ioConfig(IoConfig.enableDnsSrv(true)) - .build(); - - // Initialize the Connection - Cluster cluster = Cluster.connect(endpoint, ClusterOptions.clusterOptions(username, password).environment(env)); - Bucket bucket = cluster.bucket(bucketName); - Scope scope = bucket.defaultScope(); - Collection collection = bucket.defaultCollection(); - - // Create a N1QL Primary Index (but ignore if it exists) - cluster.queryIndexes().createPrimaryIndex(bucketName, - CreatePrimaryQueryIndexOptions.createPrimaryQueryIndexOptions().ignoreIfExists(true)); - - // Create a JSON Document - JsonObject arthur = JsonObject.create() - .put("name", "Arthur") - .put("email", "kingarthur@couchbase.com") - .put("interests", JsonArray.from("Holy Grail", "African Swallows")); - - // Store the Document - collection.upsert("u:king_arthur", arthur); - - // Load the Document and print it - // Prints Content and Metadata of the stored Document - System.out.println(collection.get("u:king_arthur")); - - // Perform a N1QL Query - QueryResult result = cluster.query( - String.format("SELECT name FROM `%s` WHERE $1 IN interests", bucketName), - queryOptions().parameters(JsonArray.from("African Swallows")) - ); - - // Print each found Row - for (JsonObject row : result.rowsAsObject()) { - System.out.println(row); - } - } - - public static List decodeCertificates(final List certificates) { - final CertificateFactory cf; - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException e) { - throw new RuntimeException(e); - } - return certificates.stream().map(c -> { - try { - return (X509Certificate) cf.generateCertificate( - new ByteArrayInputStream(c.getBytes(StandardCharsets.UTF_8)) - ); - } catch (CertificateException e) { - throw new RuntimeException(e); - } - }).collect(Collectors.toList()); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/ConnectingCertAuth.java b/modules/devguide/examples/java/pending-deletion/ConnectingCertAuth.java deleted file mode 100644 index 5872713d..00000000 --- a/modules/devguide/examples/java/pending-deletion/ConnectingCertAuth.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.couchbase.client.core.deps.io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import com.couchbase.client.core.env.IoConfig; -import com.couchbase.client.core.env.SecurityConfig; -import com.couchbase.client.core.error.DocumentNotFoundException; -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.ClusterOptions; -import com.couchbase.client.java.env.ClusterEnvironment; - -/** - * This example shows how to connect to a couchbase server EE cluster using - * client certificate authentication. - * - * Please make sure to follow the proper server side documentation on how to - * import the certifactes into the server and set up the Java keystore. - * - * https://developer.couchbase.com/documentation/server/current/security/security-x509certsintro.html - */ -public class ConnectingCertAuth { - static String connectstring = "localhost"; - static String username = "Administrator"; - static String password = "password"; - - public static void main(String... args) { - ClusterEnvironment env = ClusterEnvironment.builder() - .securityConfig( - SecurityConfig.enableTls(true).trustManagerFactory(InsecureTrustManagerFactory.INSTANCE)) - .ioConfig(IoConfig.enableDnsSrv(true)) - /* - * .sslEnabled(true) .certAuthEnabled(true) - * .sslKeystoreFile("/path/to/keystore") .sslKeystorePassword("password") - * .sslTruststoreFile("/path/to/truststore") // you can also pack it all in just - * the keystore .sslTruststorePassword("password") - */ - .build(); - - Cluster cluster = Cluster.connect(connectstring, - ClusterOptions.clusterOptions(username, password).environment(env)); - // IMPORTANT: do NOT call cluster.authenticate() since this is part of the cert - // auth - Bucket bucket = cluster.bucket("travel-sample"); - - // perform operations here... - try { - bucket.defaultCollection().get("airport_1254"); - } catch (DocumentNotFoundException dnf) { - System.out.println(dnf); - } - } - -} diff --git a/modules/devguide/examples/java/pending-deletion/ConnectingSsl.java b/modules/devguide/examples/java/pending-deletion/ConnectingSsl.java deleted file mode 100644 index 82247f7c..00000000 --- a/modules/devguide/examples/java/pending-deletion/ConnectingSsl.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.nio.file.Paths; -import java.util.Optional; - -import com.couchbase.client.core.env.SecurityConfig; -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.ClusterOptions; -import com.couchbase.client.java.env.ClusterEnvironment; - -import org.apache.log4j.Logger; - -public class ConnectingSsl { - - protected static final Logger LOGGER = Logger.getLogger("devguide"); - protected final Cluster cluster; - protected final Bucket bucket; - protected final ClusterEnvironment env; - - // === EDIT THESE TO ADAPT TO YOUR COUCHBASE INSTALLATION === - public static final String bucketName = "travel-sample"; - static String connectstring = "localhost"; - static String username = "Administrator"; - static String password = "password"; - - // === You need to correctly set up your JVM keystore first! === - // see instructions in - // http://developer.couchbase.com/documentation/server/4.0/sdks/java-2.2/managing-connections.html#story-h2-5 - - protected ConnectingSsl() { - // configure the SDK to use SSL and point it to the keystore - - env = ClusterEnvironment.builder().securityConfig( - SecurityConfig.enableTls(true).trustStore(Paths.get("/path/tokeystore"), "password", Optional.empty())) - .build(); - - // connect to the cluster using the SSL configuration, by hitting one of the - // given nodes - cluster = Cluster.connect(connectstring, ClusterOptions.clusterOptions(username, password).environment(env)); - - // get a Bucket reference from the cluster to the configured bucket - bucket = cluster.bucket(bucketName); - } - - private void disconnect() { - // release shared resources and close all open buckets - cluster.disconnect(); - - // also release the environment since we created it ourselves (notice this is an - // async operation so we block on it) - env.shutdownAsync(); - } - - public void execute() { - // connection has been done in the constructor - doWork(); - disconnect(); - } - - /** - * Override this method to showcase specific examples. - * Make them executable by adding a main method calling new ExampleClass().execute(); - */ - protected void doWork() { - // this one just showcases connection methods, see constructor and shutdown() - LOGGER.info("Connected to the cluster, opened bucket " + bucketName); - } - - public static void main(String[] args) { - new ConnectingSsl().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/ConnectionBase.java b/modules/devguide/examples/java/pending-deletion/ConnectionBase.java deleted file mode 100644 index ecee0a04..00000000 --- a/modules/devguide/examples/java/pending-deletion/ConnectionBase.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.time.Duration; - -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.Collection; -import com.couchbase.client.java.Scope; - -import org.apache.log4j.Logger; - -public class ConnectionBase { - - protected static final Logger LOGGER = Logger.getLogger("devguide"); - - protected final Cluster cluster; - protected final Bucket bucket; - protected final Scope scope; - protected final Collection collection; - protected final Scope namedScope; - protected final Collection namedCollection; - - // === EDIT THESE TO ADAPT TO YOUR COUCHBASE INSTALLATION === - public static final String bucketName = "travel-sample"; - public static final String scopeName = "_default"; - public static final String collectionName = "_default"; - public static final String userName = "Administrator"; - public static final String userPass = "password"; - public static final String seedNode = "localhost"; - - public ConnectionBase() { - // connect deferred to the cluster by hitting one of the given nodes - cluster = Cluster.connect(seedNode, userName, userPass); - // get a Bucket reference from the cluster to the configured bucket - bucket = cluster.bucket(bucketName); - // reference the scope and collection - scope = bucket.defaultScope(); - collection = bucket.defaultCollection(); - namedScope = bucket.scope(scopeName); - namedCollection = scope.collection(collectionName); - bucket.waitUntilReady(Duration.ofSeconds(30)); - } - - private void disconnect() { - // release shared resources and close all open buckets - cluster.disconnect(); - } - - public void execute() { - // connection has been done in the constructor - doWork(); - disconnect(); - } - - /** - * Override this method to showcase specific examples. Make them executable by - * adding a main method calling new ExampleClass().execute(); - */ - protected void doWork() { - // this one just showcases connection methods, see constructor and shutdown() - LOGGER.info("Connected to the cluster, opened bucket " + bucketName); - } - - public static void main(String[] args) { - new ConnectionBase().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/Counter.java b/modules/devguide/examples/java/pending-deletion/Counter.java deleted file mode 100644 index 2be9485b..00000000 --- a/modules/devguide/examples/java/pending-deletion/Counter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.couchbase.client.core.error.DocumentNotFoundException; -import com.couchbase.client.java.kv.CounterResult; -import com.couchbase.client.java.kv.DecrementOptions; -import com.couchbase.client.java.kv.IncrementOptions; - -/** - * Example of Counters in Java for the Couchbase Developer Guide. - */ -public class Counter extends ConnectionBase { - - @Override - protected void doWork() { - String key = "javaDevguideExampleCounter"; - // Remove document so we have predictable behavior in this example - try { - bucket.defaultCollection().remove(key); - } catch (DocumentNotFoundException e) { - // do nothing, the document is already not here - } - - try { - bucket.defaultCollection().binary().increment(key, - IncrementOptions.incrementOptions().delta(20).initial(100)); - } catch (DocumentNotFoundException e) { - LOGGER.info( - "The counter method failed because the counter doesn't exist yet and no initial value was provided"); - } - - CounterResult rv = bucket.defaultCollection().binary().increment(key, - IncrementOptions.incrementOptions().initial(20)); - LOGGER.info("increment Delta=20, Initial=100. Current value is: " + rv.content()); - - rv = bucket.defaultCollection().binary().increment(key, IncrementOptions.incrementOptions().delta(1)); - LOGGER.info("increment Delta=1. Current value is: " + rv.content()); - - rv = bucket.defaultCollection().binary().decrement(key, DecrementOptions.decrementOptions().delta(50)); - LOGGER.info("decrement Delta=50. Current value is: " + rv.content()); - } - - public static void main(String[] args) { - new Counter().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/Durability.java b/modules/devguide/examples/java/pending-deletion/Durability.java deleted file mode 100644 index ae12d04a..00000000 --- a/modules/devguide/examples/java/pending-deletion/Durability.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.time.Duration; -import java.util.concurrent.TimeoutException; - -import com.couchbase.client.core.error.DurabilityImpossibleException; -import com.couchbase.client.core.error.ReplicaNotAvailableException; -import com.couchbase.client.core.error.ReplicaNotConfiguredException; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.kv.PersistTo; -import com.couchbase.client.java.kv.ReplicateTo; -import com.couchbase.client.java.kv.UpsertOptions; - -/** - * Example of Durability in Java for the Couchbase Developer Guide. - */ -public class Durability extends ConnectionBase { - - @Override - protected void doWork() { - String key = "javaDevguideExampleDurability"; - JsonObject doc = JsonObject.create().put("value", "a String is valid JSON"); - - LOGGER.info("Storing with maximum factor"); - // In the Java SDK you must specify a factor matching the number of replicas you - // have configured - // if you want "maximum" persistence or replication - // Here we expect 3 replicas configured so we can wait for persistence on 4 - // nodes total, replication on 3 replicas. - try { - bucket.defaultCollection().upsert(key, doc, - UpsertOptions.upsertOptions().durability(PersistTo.FOUR, ReplicateTo.THREE)); - } catch (Exception e) { // if the durability cannot be met - if (e instanceof ReplicaNotConfiguredException) { - // this exception is a fail fast if not enough replicas are configured on the - // bucket - LOGGER.info("Couldn't persist to FOUR nor replicate to THREE, not enough replicas configured"); - } else if (e instanceof ReplicaNotAvailableException) { - // this exception occurs if enough replica are configured on the bucket but - // currently not enough are online - // eg. during a failover - LOGGER.info("Couldn't persist/replicate on 1 replica, not enough replicas online"); - } else { - LOGGER.error("Durability Exception", e); - } - } - - // Store with persisting to master node - LOGGER.info("Storing with waiting for persistence on MASTER"); - bucket.defaultCollection().upsert(key, doc, - UpsertOptions.upsertOptions().durability(PersistTo.ACTIVE, ReplicateTo.NONE)); - - LOGGER.info("Storing with waiting for persistence on any two nodes, replication on one replica node"); - try { - bucket.defaultCollection().upsert(key, doc, UpsertOptions.upsertOptions() - .durability(PersistTo.TWO, ReplicateTo.ONE).timeout(Duration.ofSeconds(1))); - } catch (DurabilityImpossibleException e) { - // if the durability cannot be met (eg. if the cluster detected that the replica - // wasn't available due to failover) - LOGGER.error("Durability Exception", e); - } catch (RuntimeException e) { - System.out.println(e); - if (e.getCause() instanceof TimeoutException) { - // if one of the nodes isn't responsive, a TimeoutException rather than - // DurabilityException may occur - LOGGER.warn("The replica didn't notify us in time"); - } - } - } - - public static void main(String[] args) { - new Durability().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/Expiration.java b/modules/devguide/examples/java/pending-deletion/Expiration.java deleted file mode 100644 index a179b618..00000000 --- a/modules/devguide/examples/java/pending-deletion/Expiration.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.time.Duration; - -import com.couchbase.client.core.error.DocumentNotFoundException; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.kv.GetResult; -import com.couchbase.client.java.kv.UpsertOptions; - -/** - * Example of Expiry/TTL in Java for the Couchbase Developer Guide. - */ -public class Expiration extends ConnectionBase { - - @Override - protected void doWork() { - String key = "javaDevguideExampleExpiration"; - // create content - JsonObject content = JsonObject.create().put("some", "value"); - - LOGGER.info("Storing with an expiration of 2 seconds"); - bucket.defaultCollection().upsert(key, content, UpsertOptions.upsertOptions().expiry(Duration.ofSeconds(2))); - - LOGGER.info("Getting item back immediately"); - LOGGER.info(bucket.defaultCollection().get(key)); - - LOGGER.info("Sleeping for 4 seconds..."); - sleepSeconds(4); - LOGGER.info("Getting key again (should fail)"); - - // get returns null if the key doesn't exist - try { - if (bucket.defaultCollection().get(key) == null) { - LOGGER.info("Get failed because item has expired"); - } - } catch (DocumentNotFoundException dnf) { - LOGGER.info("Get failed because item has expired"); - } - - LOGGER.info("Storing item again (without expiry)"); - bucket.defaultCollection().upsert(key, content); - - LOGGER.info("Using get-and-touch to retrieve key and modify expiry"); - GetResult rv = bucket.defaultCollection().getAndTouch(key, Duration.ofSeconds(2)); - LOGGER.info("Value is:" + rv); - - LOGGER.info("Sleeping for 4 seconds again"); - sleepSeconds(4); - LOGGER.info("Getting key again (should fail)"); - try { - if (bucket.defaultCollection().get(key) == null) { - LOGGER.info("Get failed because item has expired"); - } - } catch (DocumentNotFoundException dnf) { - LOGGER.info("Get failed because item has expired"); - } - - LOGGER.info("Storing key again..."); - bucket.defaultCollection().upsert(key, content); - LOGGER.info("Using touch (without get). Setting expiry for 1 second"); - bucket.defaultCollection().touch(key, Duration.ofSeconds(1)); - - LOGGER.info("Sleeping for 4 seconds..."); - sleepSeconds(4); - LOGGER.info("Will try to get item again (should fail)"); - try { - if (bucket.defaultCollection().get(key) == null) { - LOGGER.info("Get failed because item has expired"); - } - } catch (DocumentNotFoundException dnf) { - LOGGER.info("Get failed because item has expired"); - } - } - - private void sleepSeconds(int seconds) { - try { - Thread.sleep(seconds * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public static void main(String[] args) { - new Expiration().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/FieldEncryptionAES.java b/modules/devguide/examples/java/pending-deletion/FieldEncryptionAES.java deleted file mode 100644 index 0364ac75..00000000 --- a/modules/devguide/examples/java/pending-deletion/FieldEncryptionAES.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.FileInputStream; -import java.security.KeyStore; - -import com.couchbase.client.core.encryption.CryptoManager; -import com.couchbase.client.encryption.AeadAes256CbcHmacSha512Provider; -import com.couchbase.client.encryption.DefaultCryptoManager; -import com.couchbase.client.encryption.KeyStoreKeyring; -import com.couchbase.client.encryption.Keyring; -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.ClusterOptions; -import com.couchbase.client.java.encryption.annotation.Encrypted; -import com.couchbase.client.java.env.ClusterEnvironment; - -public class FieldEncryptionAES extends ConnectionBase { - - @Override - protected void doWork() { - Cluster cluster; - try { - KeyStore javaKeyStore = KeyStore.getInstance("MyKeyStoreType"); - FileInputStream fis = new java.io.FileInputStream("keyStoreName"); - char[] password = { 'a', 'b', 'c' }; - javaKeyStore.load(fis, password); - Keyring keyring = new KeyStoreKeyring(javaKeyStore, keyName -> "swordfish"); - - // AES-256 authenticated with HMAC SHA-512. Requires a 64-byte key. - AeadAes256CbcHmacSha512Provider provider = AeadAes256CbcHmacSha512Provider.builder() - .keyring(keyring) - .build(); - - CryptoManager cryptoManager = DefaultCryptoManager.builder() - .decrypter(provider.decrypter()) - .defaultEncrypter(provider.encrypterForKey("myKey")) - .build(); - - ClusterEnvironment env = ClusterEnvironment.builder() - .cryptoManager(cryptoManager) - .build(); - - cluster = Cluster.connect("localhost", - ClusterOptions.clusterOptions("username", "password").environment(env)); - } catch (Exception e) { - throw new RuntimeException(e); - } - - Bucket myBucket = cluster.bucket(bucketName); - - Person person = new Person(); - person.id = "johnd"; - person.password = "secret"; - person.firstName = "John"; - person.lastName = "Doe"; - person.userName = "jdoe"; - person.age = 20; - - myBucket.defaultCollection().upsert(person.id, person); - Person stored = bucket.defaultCollection().get(person.id).contentAs(Person.class); - System.out.println("Password: " + stored.password); - } - - public static class Person { - - public String id; - - @Encrypted - public String password; - - // The rest will be transported and stored unencrypted - public String firstName; - public String lastName; - public String userName; - public int age; - } - - public static void main(String[] args) { - new FieldEncryptionAES().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/HealthCheckExample.java b/modules/devguide/examples/java/pending-deletion/HealthCheckExample.java deleted file mode 100644 index 5b6db150..00000000 --- a/modules/devguide/examples/java/pending-deletion/HealthCheckExample.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.time.Duration; -import java.util.List; -import java.util.Map; - -import com.couchbase.client.core.diagnostics.DiagnosticsResult; -import com.couchbase.client.core.diagnostics.EndpointDiagnostics; -import com.couchbase.client.core.diagnostics.EndpointPingReport; -import com.couchbase.client.core.diagnostics.PingResult; -import com.couchbase.client.core.diagnostics.PingState; -import com.couchbase.client.core.endpoint.EndpointState; -import com.couchbase.client.core.service.ServiceType; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.kv.MutationResult; - -/** - * Example Health Check with the Couchbase Java SDKa for the Couchbase Developer - * Guide. - */ -public class HealthCheckExample extends ConnectionBase { - - // public static void main(String... args) { - - // Cluster cluster = Cluster.connect("127.0.0.1", "Administrator", "password"); - // - // Bucket bucket = cluster.bucket("bucket-name"); - // Scope scope = bucket.scope("scope-name"); - // Collection collection = scope.collection("collection-name"); - // - // JsonObject json = JsonObject.create() - // .put("foo", "bar") - // .put("baz", "qux"); - // - // - //// tag::apis[] - // AsyncCollection asyncCollection = collection.async(); - // ReactiveCollection reactiveCollection = collection.reactive(); - //// end::apis[] - // - // JsonObject content = JsonObject.create().put("foo", "bar"); - //// MutationResult result = collection.upsert("document-key", content); - // - //// tag::apis[] - // PingResult ping = bucket.ping(); - //// end::apis[] - @Override - protected void doWork() { - - bucket.waitUntilReady(Duration.ofSeconds(5)); - - JsonObject content = JsonObject.create() - .put("foo", "bar") - .put("baz", "qux"); - - MutationResult result = collection.upsert("document-key", content); - - // tag::ping[] - // Ping a specified bucket to look at the state of all associated endpoints - PingResult pingResult = bucket.ping(); - // Look at the KV endpoints and warn if their state is not OK - Map> pingEndpoints = pingResult.endpoints(); - List kvPingReports = pingEndpoints.get(ServiceType.KV); - - for (EndpointPingReport pingEndpoint : kvPingReports) { - if (pingEndpoint.state() != PingState.OK) { - LOGGER.warn(String.format("Node %s at remote %s is %s.", pingEndpoint.id(), pingEndpoint.remote(), - pingEndpoint.state())); - } else { - LOGGER.info(String.format("Node %s at remote %s is OK.", pingEndpoint.id(), pingEndpoint.remote())); - } - } - // end::ping[] - - // tag::diagnostics[] - // Get all diagnostics associated with a given cluster, passively - DiagnosticsResult diagnosticsResult = cluster.diagnostics(); - Map> diagEndpoints = diagnosticsResult.endpoints(); - // Look at the KV connections, warn if not connected - List kvDiagReports = diagEndpoints.get(ServiceType.KV); - - for (EndpointDiagnostics diagEndpoint : kvDiagReports) { - // Identify the KV connection associated with the bucket we are using from the - // namespace - if (diagEndpoint.namespace().isPresent() && diagEndpoint.namespace().get().contentEquals(bucketName)) { - if (diagEndpoint.state() != EndpointState.CONNECTED) { - LOGGER.warn(String.format("Endpoint %s at remote %s is in state %s.", diagEndpoint.id(), - diagEndpoint.remote(), diagEndpoint.state())); - } else { - LOGGER.info(String.format("Endpoint %s at remote %s connected.", diagEndpoint.id().orElse("NO_ID"), - diagEndpoint.remote())); - } - } - } - // end::diagnostics[] - } - - public static void main(String[] args) { - new HealthCheckExample().execute(); - } - -} diff --git a/modules/devguide/examples/java/pending-deletion/QueryConsistency.java b/modules/devguide/examples/java/pending-deletion/QueryConsistency.java deleted file mode 100644 index 2c10d5c1..00000000 --- a/modules/devguide/examples/java/pending-deletion/QueryConsistency.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.Random; - -import com.couchbase.client.java.json.JsonArray; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.manager.query.CreatePrimaryQueryIndexOptions; -import com.couchbase.client.java.query.QueryOptions; -import com.couchbase.client.java.query.QueryResult; -import com.couchbase.client.java.query.QueryScanConsistency; -import com.couchbase.client.java.query.QueryStatus; - -/** - * Example of N1QL Query Consistency in Java for the Couchbase Developer Guide. - */ -public class QueryConsistency extends ConnectionBase { - - @Override - protected void doWork() { - String key = "javaDevguideExampleQueryConsistency"; - - cluster.queryIndexes().createPrimaryIndex(bucketName, - CreatePrimaryQueryIndexOptions.createPrimaryQueryIndexOptions().ignoreIfExists(true)); - Random random = new Random(); - int randomNumber = random.nextInt(10000000); - - // prepare the random user - JsonObject user = JsonObject.create() - .put("name", JsonArray.from("Brass", "Doorknob")) - .put("email", "brass.doorknob@juno.com") - .put("random", randomNumber); - // upsert it with the corresponding random key - bucket.defaultCollection().upsert(key, user); - - LOGGER.info("Expecting random: " + randomNumber); - QueryResult result = cluster.query( - "select name, email, random, META(default).id " + " from `travel-sample` where $1 in name", - QueryOptions.queryOptions().scanConsistency(QueryScanConsistency.REQUEST_PLUS) - .parameters(JsonArray.from("Brass"))); - if (!result.metaData().status().equals(QueryStatus.SUCCESS)) { - LOGGER.warn("No result/errors: " + result.metaData().warnings()); - } - - for (JsonObject row : result.rowsAsObject()) { - int rowRandom = row.getInt("random"); - String rowId = row.getString("id"); - - LOGGER.info("Doc Id: " + rowId + ", Name: " + row.getArray("name") + ", Email: " + row.getString("email") - + ", Random: " + rowRandom); - - if (rowRandom == randomNumber) { - LOGGER.info("!!! Found our newly inserted document !!!"); - } else { - LOGGER.warn("Found a different random value : " + rowRandom); - } - - if (System.getProperty("REMOVE_DOORKNOBS") != null || System.getenv("REMOVE_DOORKNOBS") != null) { - bucket.defaultCollection().remove(rowId); - } - } - } - - public static void main(String[] args) { - new QueryConsistency().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/QueryCriteria.java b/modules/devguide/examples/java/pending-deletion/QueryCriteria.java deleted file mode 100644 index f8a7c6f3..00000000 --- a/modules/devguide/examples/java/pending-deletion/QueryCriteria.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.List; - -import com.couchbase.client.core.error.ParsingFailureException; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.query.QueryMetaData; -import com.couchbase.client.java.query.QueryOptions; -import com.couchbase.client.java.query.QueryScanConsistency; - -/** - * Example of Querying with N1QL in Java for the Couchbase Developer Guide. - */ -public class QueryCriteria extends ConnectionBase { - - @Override - protected void doWork() { - - JsonObject airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Reno International Airport") - .put("city", "Reno") - .put("country", "United States"); - - bucket.defaultCollection().upsert("1", airport); - - String statement = "SELECT airportname, city, country FROM `travel-sample` WHERE type=\"airport\" AND city=\"Reno\""; - - LOGGER.info("Results from a simple statement:"); - LOGGER.info(statement); - List result = cluster - .query(statement, QueryOptions.queryOptions().scanConsistency(QueryScanConsistency.REQUEST_PLUS)) - .rowsAsObject(); - for (JsonObject row : result) { - LOGGER.info("\t" + row); - } - - // when there is a server-side error, the server will feed errors in the - // result.error() collection - // you can find that out by checking finalSuccess() == false - // alternatively, syntax errors are also detected early and for them you can - // check parseSuccess() - - try { - QueryMetaData errorResult = cluster.query("SELECTE * FROM `travel-sample` LIMIT 3").metaData(); - LOGGER.info( - "With bad syntax, finalSuccess = " + errorResult.status() + ", errors: " + errorResult.warnings()); - } catch (ParsingFailureException pf) { - System.out.println(pf); - } - /* - * //there is also a fluent API to construct N1QL statements, generally import - * static the Select.select method Statement fluentStatement = - * Select.select("airportname", "city", "country") //Expression.i escapes an - * expression with backticks .from(i("travel-sample")) //Expression.x creates an - * expression token that can be manipulated //Expression.s creates a string - * literal .where(x("type").eq(s("airport")) .and(x("city").eq(s("Reno"))) ); - * - * LOGGER.info("Results from a fluent-API statement:"); - * LOGGER.info(fluentStatement.toString()); N1qlQueryResult fluentResult = - * bucket.query(N1qlQuery.simple(fluentStatement)); for (N1qlQueryRow row : - * fluentResult) { LOGGER.info("\t" + row.value()); } - * - * //the result also contains metrics sent by the server LOGGER.info("Metrics: " - * + fluentResult.info()); - */ - } - - public static void main(String[] args) { - new QueryCriteria().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/QueryPlaceholders.java b/modules/devguide/examples/java/pending-deletion/QueryPlaceholders.java deleted file mode 100644 index 1dd0dfeb..00000000 --- a/modules/devguide/examples/java/pending-deletion/QueryPlaceholders.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.List; - -import com.couchbase.client.java.json.JsonArray; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.query.QueryOptions; - -/** - * Example of Querying using placeholders with N1QL in Java for the Couchbase - * Developer Guide. - */ -public class QueryPlaceholders extends ConnectionBase { - - private static final String PLACEHOLDER_STATEMENT = "SELECT airportname FROM `travel-sample` WHERE city=$1 AND type=\"airport\""; - - private List queryCity(String city) { - - // the placeholder values can be provided as a JSON array (if using $1 syntax) - // or map-like JSON object (if using $name syntax) - JsonArray placeholderValues = JsonArray.from(city); - return cluster.query("SELECT airportname FROM `travel-sample` WHERE city=$1 AND type=\"airport\"", - QueryOptions.queryOptions().parameters(placeholderValues)).rowsAsObject(); - } - - @Override - protected void doWork() { - - JsonObject airport; - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Reno International Airport") - .put("city", "Reno") - .put("country", "United States"); - - bucket.defaultCollection().upsert("1", airport); - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Los Angeles International Airport") - .put("city", "Los Angeles") - .put("country", "United States"); - - bucket.defaultCollection().upsert("2", airport); - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Culver City Airport") - .put("city", "Los Angeles") - .put("country", "United States"); - - bucket.defaultCollection().upsert("3", airport); - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Dallas International Airport") - .put("city", "Dallas") - .put("country", "United States"); - - bucket.defaultCollection().upsert("4", airport); - - LOGGER.info("Airports in Reno: "); - for (JsonObject row : queryCity("Reno")) { - LOGGER.info("\t" + row); - } - - LOGGER.info("Airports in Dallas: "); - for (JsonObject row : queryCity("Dallas")) { - LOGGER.info("\t" + row); - } - - LOGGER.info("Airports in Los Angeles: "); - for (JsonObject row : queryCity("Los Angeles")) { - LOGGER.info("\t" + row); - } - } - - public static void main(String[] args) { - new QueryPlaceholders().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/QueryPrepared.java b/modules/devguide/examples/java/pending-deletion/QueryPrepared.java deleted file mode 100644 index 73d2a242..00000000 --- a/modules/devguide/examples/java/pending-deletion/QueryPrepared.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.List; - -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.query.QueryOptions; - -/** - * Example of Querying using placeholders with N1QL in Java for the Couchbase - * Developer Guide. - */ -public class QueryPrepared extends ConnectionBase { - - private static final String PLACEHOLDER_STATEMENT = "SELECT airportname FROM `travel-sample` WHERE city=$1 AND type=\"airport\""; - - private List queryCity(String city) { - // the placeholder values can be provided as a JSON array (if using $1 syntax) - // or map-like JSON object (if using $name syntax) - JsonObject placeholderValues = JsonObject.create().put("city", city); - return cluster.query("SELECT airportname FROM `travel-sample` WHERE city=$city AND type=\"airport\"", - QueryOptions.queryOptions().parameters(placeholderValues)).rowsAsObject(); - } - - @Override - protected void doWork() { - JsonObject airport; - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Reno International Airport") - .put("city", "Reno") - .put("country", "United States"); - - bucket.defaultCollection().upsert("1", airport); - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Los Angeles International Airport") - .put("city", "Los Angeles") - .put("country", "United States"); - - bucket.defaultCollection().upsert("2", airport); - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Culver City Airport") - .put("city", "Los Angeles") - .put("country", "United States"); - - bucket.defaultCollection().upsert("3", airport); - - airport = JsonObject.create() - .put("type", "airport") - .put("airportname", "Dallas International Airport") - .put("city", "Dallas") - .put("country", "United States"); - - bucket.defaultCollection().upsert("4", airport); - - LOGGER.info("Airports in Reno: "); - for (JsonObject row : queryCity("Reno")) { - LOGGER.info("\t" + row); - } - - LOGGER.info("Airports in Dallas: "); - for (JsonObject row : queryCity("Dallas")) { - LOGGER.info("\t" + row); - } - - LOGGER.info("Airports in Los Angeles: "); - for (JsonObject row : queryCity("Los Angeles")) { - LOGGER.info("\t" + row); - } - } - - public static void main(String[] args) { - new QueryPrepared().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/Retrieving.java b/modules/devguide/examples/java/pending-deletion/Retrieving.java deleted file mode 100644 index b0064fe2..00000000 --- a/modules/devguide/examples/java/pending-deletion/Retrieving.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.couchbase.client.core.error.DocumentNotFoundException; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.kv.GetResult; - -/** - * Example of Retrieving in Java for the Couchbase Developer Guide. - */ -public class Retrieving extends ConnectionBase { - - @Override - protected void doWork() { - String key = "javaDevguideExampleRetrieving"; - LOGGER.info("Getting non-existent key. Should fail.."); - try { - GetResult nonExistentDocument = bucket.defaultCollection().get("non-exist-document"); - if (nonExistentDocument == null) { - LOGGER.info("Got null for missing document, it doesn't exist!"); - } - } catch (DocumentNotFoundException dnf) { - System.out.println(dnf); - } - - LOGGER.info("Upserting..."); - JsonObject document = JsonObject.create().put("foo", "bar"); - bucket.defaultCollection().upsert(key, document); - LOGGER.info("Getting..."); - LOGGER.info(bucket.defaultCollection().get(key)); - } - - public static void main(String[] args) { - new Retrieving().execute(); - } -} diff --git a/modules/devguide/examples/java/pending-deletion/SimpleConnect.java b/modules/devguide/examples/java/pending-deletion/SimpleConnect.java deleted file mode 100644 index d6a26bb4..00000000 --- a/modules/devguide/examples/java/pending-deletion/SimpleConnect.java +++ /dev/null @@ -1,20 +0,0 @@ -// tag::simple-connect[] -// tag::imports[] -import com.couchbase.client.java.*; -// end::imports[] - -public class SimpleConnect { - static String connectionString = "couchbases://example.com"; - static String username = "username"; - static String password = "Password!123"; - static String bucketName = "travel-sample"; - - public static void main(String... args) { - // tag::connect-string[] - // Alternatively, connect without customizing the cluster envionrment. - Cluster cluster = Cluster.connect(connectionString, username, password); - // end::connect-string[] - cluster.disconnect(); - } -} -// end::simple-connect[] diff --git a/modules/devguide/examples/java/pending-deletion/Updating.java b/modules/devguide/examples/java/pending-deletion/Updating.java deleted file mode 100644 index 35e78bdb..00000000 --- a/modules/devguide/examples/java/pending-deletion/Updating.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2020 Couchbase, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import com.couchbase.client.core.error.DocumentExistsException; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.kv.MutationResult; - -/** - * Example of Updating/Storing in Java for the Couchbase Developer Guide. - */ -public class Updating extends ConnectionBase { - - @Override - protected void doWork() { - String key = "javaDevguideExampleUpdating"; - // create content - JsonObject content = JsonObject.create().put("topic", "storing").put("mutation", true); - - LOGGER.info("Prepared document " + content); - - // store the document (upsert will always work whether or not a value is already - // associated to the key) - MutationResult result = bucket.defaultCollection().upsert(key, content); - LOGGER.info("Result after upsert: " + result); // notice the CAS changed (the returned document is updated with - // correct CAS) - - // prepare an update - content.put("update", "something"); - // see that inserting it fails because it already exists - try { - bucket.defaultCollection().insert(key, content); - } catch (DocumentExistsException e) { - LOGGER.warn("Couldn't insert it, DocumentAlreadyExists... Let's try to replace it"); - } - - // on the other hand, updating works (it would have failed if the key was not in - // database) - result = bucket.defaultCollection().replace(key, content); - LOGGER.info("Replaced the old document by the new one: " + result); // notice the document's CAS changed - // again... - - LOGGER.info("Got the following from database: " + bucket.defaultCollection().get(key)); // ... which is - // consistent with a get - // (RYOW) - } - - public static void main(String[] args) { - new Updating().execute(); - } -} diff --git a/modules/devguide/examples/java/student/examples/AddEnrollments.java b/modules/devguide/examples/java/student/examples/AddEnrollments.java deleted file mode 100644 index 7a5dba7e..00000000 --- a/modules/devguide/examples/java/student/examples/AddEnrollments.java +++ /dev/null @@ -1,84 +0,0 @@ -import com.couchbase.client.core.error.CouchbaseException; -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.Collection; -import com.couchbase.client.java.Scope; -import com.couchbase.client.java.json.JsonArray; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.query.QueryOptions; -import com.couchbase.client.java.query.QueryResult; -import com.couchbase.client.java.query.QueryScanConsistency; - -import java.time.Duration; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -public class AddEnrollments { - - public static void main(String[] args) { - - Cluster cluster = Cluster.connect("localhost", - "Administrator", "password"); // <1> - - Bucket bucket = cluster.bucket("student-bucket"); // <2> - bucket.waitUntilReady(Duration.ofSeconds(10)); // <3> - - Scope scope = bucket.scope("art-school-scope"); - Collection student_records = scope.collection("student-record-collection"); // <4> - - // Retrieve the records - JsonObject hilary = retrieveStudent(cluster,"Hilary Smith"); // <5> - JsonObject graphic_design = retrieveCourse(cluster, "graphic design"); // <5> - JsonObject art_history = retrieveCourse(cluster, "art history"); // <5> - - String currentDate = LocalDate.now().format(DateTimeFormatter.ISO_DATE); // <6> - - // Create Hilary's enrollments - - JsonArray enrollments = JsonArray.create(); // <7> - - enrollments.add(JsonObject.create() - .put("course-id", graphic_design.getString("id")) - .put("date-enrolled", currentDate)); // <8> - - enrollments.add(JsonObject.create() - .put("course-id", art_history.getString("id")) - .put("date-enrolled", currentDate)); // <8> - - hilary.put("enrollments", enrollments); // <9> - - student_records.upsert(hilary.getString("id"), hilary); // <10> - - cluster.disconnect(); - - } - - private static JsonObject retrieveStudent(Cluster cluster, String name) throws CouchbaseException { - - QueryOptions studentQueryOptions = QueryOptions.queryOptions(); - studentQueryOptions.parameters(JsonObject.create().put("name", name)); - studentQueryOptions.scanConsistency(QueryScanConsistency.REQUEST_PLUS); - - final QueryResult result = cluster.query("select META().id, src.* " + - "from `student-bucket`.`art-school-scope`.`student-record-collection` src " + - "where src.`name` = $name", studentQueryOptions); - - return result.rowsAsObject().get(0); - - } - - private static JsonObject retrieveCourse(Cluster cluster, String course) throws CouchbaseException { - - QueryOptions courseQueryOptions = QueryOptions.queryOptions(); - courseQueryOptions.parameters(JsonObject.create().put("courseName", course)); - courseQueryOptions.scanConsistency(QueryScanConsistency.REQUEST_PLUS); - - final QueryResult result = cluster.query("select META().id, crc.* " + - "from `student-bucket`.`art-school-scope`.`course-record-collection` crc " + - "where crc.`course-name` = $courseName", courseQueryOptions); - - return result.rowsAsObject().get(0); - - } - -} diff --git a/modules/devguide/examples/java/student/examples/ArtSchoolRetriever.java b/modules/devguide/examples/java/student/examples/ArtSchoolRetriever.java deleted file mode 100644 index e741c0d6..00000000 --- a/modules/devguide/examples/java/student/examples/ArtSchoolRetriever.java +++ /dev/null @@ -1,30 +0,0 @@ -import com.couchbase.client.core.error.CouchbaseException; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.query.QueryResult; - -public class ArtSchoolRetriever { - - public static void main(String[] args) { - Cluster cluster = Cluster.connect("localhost", - "Administrator", "password"); - - retrieveCourses(cluster); - - cluster.disconnect(); - } - - private static void retrieveCourses(Cluster cluster) { - - try { - final QueryResult result = cluster.query("select crc.* from `student-bucket`.`art-school-scope`.`course-record-collection` crc"); - - for (JsonObject row : result.rowsAsObject()) { - System.out.println("Found row: " + row); - } - - } catch (CouchbaseException ex) { - ex.printStackTrace(); - } - } -} diff --git a/modules/devguide/examples/java/student/examples/ArtSchoolRetrieverParameters.java b/modules/devguide/examples/java/student/examples/ArtSchoolRetrieverParameters.java deleted file mode 100644 index f308ff17..00000000 --- a/modules/devguide/examples/java/student/examples/ArtSchoolRetrieverParameters.java +++ /dev/null @@ -1,35 +0,0 @@ -import com.couchbase.client.core.error.CouchbaseException; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.json.JsonObject; -import com.couchbase.client.java.query.QueryOptions; -import com.couchbase.client.java.query.QueryResult; - -public class ArtSchoolRetrieverParameters { - - public static void main(String[] args) { - Cluster cluster = Cluster.connect("localhost", - "Administrator", "password"); - - retrieveCourses(cluster); - - cluster.disconnect(); - } - - private static void retrieveCourses(Cluster cluster) { - - try { - final QueryResult result = cluster.query("select crc.* " + - "from `student-bucket`.`art-school-scope`.`course-record-collection` crc " + - "where crc.`credit-points` < $creditPoints", // <1> - QueryOptions.queryOptions() - .parameters(JsonObject.create().put("creditPoints", 200))); // <2> - - for (JsonObject row : result.rowsAsObject()) { - System.out.println("Found row: " + row); - } - - } catch (CouchbaseException ex) { - ex.printStackTrace(); - } - } -} diff --git a/modules/devguide/examples/java/student/examples/ConnectStudent.java b/modules/devguide/examples/java/student/examples/ConnectStudent.java deleted file mode 100644 index adbf6419..00000000 --- a/modules/devguide/examples/java/student/examples/ConnectStudent.java +++ /dev/null @@ -1,27 +0,0 @@ -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.Collection; -import com.couchbase.client.java.Scope; - -import java.time.Duration; - -public class ConnectStudent { - - public static void main(String[] args) { - - Cluster cluster = Cluster.connect("localhost", - "Administrator", "password"); // <1> - - Bucket bucket = cluster.bucket("student-bucket"); // <2> - - bucket.waitUntilReady(Duration.ofSeconds(10)); // <3> - - Scope scope = bucket.scope("art-school-scope"); //<4> - - Collection student_records = scope.collection("student-record-collection"); // <5> - - System.out.println("The name of this collection is " + student_records.name()); // <6> - - cluster.disconnect(); // <7> - } -} diff --git a/modules/devguide/examples/java/student/examples/InsertCourses.java b/modules/devguide/examples/java/student/examples/InsertCourses.java deleted file mode 100644 index b2ed065e..00000000 --- a/modules/devguide/examples/java/student/examples/InsertCourses.java +++ /dev/null @@ -1,38 +0,0 @@ -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.Collection; -import com.couchbase.client.java.Scope; -import com.couchbase.client.java.json.JsonObject; - -import java.time.Duration; - -public class InsertCourses { - - public static void main(String[] args) { - Cluster cluster = Cluster.connect("localhost", - "Administrator", "password"); - - Bucket bucket = cluster.bucket("student-bucket"); - bucket.waitUntilReady(Duration.ofSeconds(10)); - Scope scope = bucket.scope("art-school-scope"); - Collection course_records = scope.collection("course-record-collection"); // <.> - - addCourse(course_records, "ART-HISTORY-000001", "art history", "fine art", 100); - addCourse(course_records, "FINE-ART-000002", "fine art", "fine art", 50); - addCourse(course_records, "GRAPHIC-DESIGN-000003", "graphic design", "media and communication", 200); - - cluster.disconnect(); - } - - private static void addCourse(Collection collection, String id, String name, - String faculty, int creditPoints) { - - JsonObject course = JsonObject.create() - .put("course-name", name) - .put("faculty", faculty) - .put("credit-points", creditPoints); - - collection.upsert(id, course); - - } -} diff --git a/modules/devguide/examples/java/student/examples/InsertStudent.java b/modules/devguide/examples/java/student/examples/InsertStudent.java deleted file mode 100644 index a234035f..00000000 --- a/modules/devguide/examples/java/student/examples/InsertStudent.java +++ /dev/null @@ -1,34 +0,0 @@ -import com.couchbase.client.java.Bucket; -import com.couchbase.client.java.Cluster; -import com.couchbase.client.java.Collection; -import com.couchbase.client.java.Scope; -import com.couchbase.client.java.json.JsonObject; - -import java.time.Duration; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -public class InsertStudent { - - public static void main(String[] args) { - - Cluster cluster = Cluster.connect("localhost", - "Administrator", "password"); - - Bucket bucket = cluster.bucket("student-bucket"); - bucket.waitUntilReady(Duration.ofSeconds(10)); - Scope scope = bucket.scope("art-school-scope"); - Collection student_records = scope.collection("student-record-collection"); // <.> - - JsonObject hilary = JsonObject.create() - .put("name", "Hilary Smith") - .put("date-of-birth", - LocalDate.of(1980, 12, 21) - .format(DateTimeFormatter.ISO_DATE)); // <.> - - - student_records.upsert("000001", hilary); // <.> - - cluster.disconnect(); - } -} diff --git a/modules/devguide/examples/java/student/examples/pom.xml b/modules/devguide/examples/java/student/examples/pom.xml deleted file mode 100644 index f9dfb695..00000000 --- a/modules/devguide/examples/java/student/examples/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - - org.example - couchbase-java - 1.0-SNAPSHOT - - - 16 - 16 - UTF-8 - ${encoding} - ${encoding} - ${encoding} - ${encoding} - - - - - com.couchbase.client - java-client - 3.10.0 - - - - From fce42be045ce53e57ca13c462f992c1266c18ec6 Mon Sep 17 00:00:00 2001 From: Richard Smedley Date: Thu, 27 Nov 2025 13:24:15 +0000 Subject: [PATCH 3/3] student tutorial code compile fix --- ...{ArtSchoolRetriever.java => ArtSchoolRetrieverParameters.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename modules/devguide/examples/java/{ArtSchoolRetriever.java => ArtSchoolRetrieverParameters.java} (100%) diff --git a/modules/devguide/examples/java/ArtSchoolRetriever.java b/modules/devguide/examples/java/ArtSchoolRetrieverParameters.java similarity index 100% rename from modules/devguide/examples/java/ArtSchoolRetriever.java rename to modules/devguide/examples/java/ArtSchoolRetrieverParameters.java