Skip to content

Commit

Permalink
Cloud Connection code samples (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardSmedley authored Jul 7, 2020
1 parent f5f3cff commit c9373a0
Show file tree
Hide file tree
Showing 6 changed files with 369 additions and 0 deletions.
70 changes: 70 additions & 0 deletions c/cloud.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include <string.h>
#include <libcouchbase/couchbase.h> //this code sample is for libcouchbase 2.10 & later
#include <stdlib.h>

static void
opCallback(lcb_t instance, int cbtype, const lcb_RESPBASE *rb) {
fprintf(stderr, "%.*s: %s... ", (int)rb->nkey, rb->key, lcb_strcbtype(cbtype));
if (rb->rc != LCB_SUCCESS) {
fprintf(stderr, "%s\n", lcb_strerror(NULL, rb->rc));
} else {
fprintf(stderr, "OK");
if (cbtype == LCB_CALLBACK_GET) {
const lcb_RESPGET *rg = (const lcb_RESPGET *)rb;
fprintf(stderr, "... Value: %.*s\n", (int)rg->nvalue, rg->value);
} else {
fprintf(stderr, "\n");
}
}
}

int main(int argc, char **argv)
{
lcb_t instance = NULL;
struct lcb_create_st crst = {0};
memset(&crst, 0, sizeof crst);
// Note that version 3 here refers to the internal API/ABI, not the version of the library supporting
// that API/ABI. This allows extension within a libcouchbase version with forward compatibility
crst.version = 3;

/* User input starts here; see note on v3 above */
crst.v.v3.connstr = "couchbases://cb.<your endpoint address>.dp.cloud.couchbase.com/couchbasecloudbucket?ssl=no_verify";
crst.v.v3.username = "user";
crst.v.v3.passwd = "password";
/* User input ends here */

lcb_create(&instance, &crst);
lcb_connect(instance);


/* This function is required to actually schedule the operations on the network */
lcb_wait(instance);

/* Determines if the bootstrap/connection succeeded */
lcb_error_t rc;
rc = lcb_get_bootstrap_status(instance);
if (rc != LCB_SUCCESS) {
fprintf(stderr, "%s failed. (0x%x, %s)\n", "bootstrap failure", rc, lcb_strerror(NULL, rc));
exit(1);
} else {
printf("Connection succeeded. Cluster has %d nodes\n", lcb_get_num_nodes(instance));
}

lcb_install_callback3(instance, LCB_CALLBACK_GET, opCallback);
lcb_install_callback3(instance, LCB_CALLBACK_STORE, opCallback);

lcb_CMDSTORE scmd = { 0 };
LCB_CMD_SET_KEY(&scmd, "key", 3);
LCB_CMD_SET_VALUE(&scmd, "true", 4);
scmd.operation = LCB_SET;
lcb_store3(instance, NULL, &scmd);
lcb_wait(instance);

lcb_CMDGET gcmd = { 0 };
LCB_CMD_SET_KEY(&gcmd, "key", 3);
lcb_get3(instance, NULL, &gcmd);
lcb_wait(instance);
lcb_destroy(instance);

return 0;
}
78 changes: 78 additions & 0 deletions go/cloud.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package main

import (
"fmt"
"log"

"gopkg.in/couchbase/gocb.v1"
)

func main() {
// Uncomment following line to enable logging
// gocb.SetLogger(gocb.VerboseStdioLogger())
endpoint := "cb.e493356f-f395-4561-a6b5-a3a1ec0aaa29.dp.cloud.couchbase.com"
bucketName := "couchbasecloudbucket"
username := "user"
password := "password"

// Initialize the Connection
cluster, err := gocb.Connect("couchbases://" + endpoint + "?ssl=no_verify")
if err != nil {
log.Fatal(err)
}

_ = cluster.Authenticate(gocb.PasswordAuthenticator{
Username: username,
Password: password,
})

bucket, err := cluster.OpenBucket(bucketName, "")
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected..")

// Create a N1QL Primary Index (but ignore if it exists)
err = bucket.Manager("", "").CreatePrimaryIndex("", true, false)
if err != nil {
log.Fatal(err)
}

type User struct {
Name string `json:"name"`
Email string `json:"email"`
Interests []string `json:"interests"`
}

// Create and store a Document
_, err = bucket.Upsert("u:kingarthur",
User{
Name: "Arthur",
Email: "[email protected]",
Interests: []string{"Holy Grail", "African Swallows"},
}, 0)
if err != nil {
log.Fatal(err)
}

// Get the document back
var inUser User
_, err = bucket.Get("u:kingarthur", &inUser)
if err != nil {
log.Fatal(err)
}
fmt.Printf("User: %v\n", inUser)

// Perform a N1QL Query
query := gocb.NewN1qlQuery(fmt.Sprintf("SELECT name FROM `%s` WHERE $1 IN interests", bucketName))
rows, err := bucket.ExecuteN1qlQuery(query, []interface{}{"African Swallows"})
if err != nil {
log.Fatal(err)
}

// Print each found Row
var row interface{}
for rows.Next(&row) {
fmt.Printf("Row: %v", row)
}
}
114 changes: 114 additions & 0 deletions java/src/main/java/com/couchbase/devguide/Cloud.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonArray;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;

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;

public class Example {
// 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 = "endpoint";
String bucketName = "couchbasecloudbucket";
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));

CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
.sslEnabled(true)
.dnsSrvEnabled(true)
.sslTruststore(trustStore)
.build();

// Initialize the Connection
Cluster cluster = CouchbaseCluster.create(env, endpoint);
cluster.authenticate(username, password);
Bucket bucket = cluster.openBucket(bucketName);

// Create a N1QL Primary Index (but ignore if it exists)
bucket.bucketManager().createN1qlPrimaryIndex(true, false);

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

// Store the Document
bucket.upsert(JsonDocument.create("u:king_arthur", arthur));

// Load the Document and print it
// Prints Content and Metadata of the stored Document
System.out.println(bucket.get("u:king_arthur"));

// Perform a N1QL Query
N1qlQueryResult result = bucket.query(
N1qlQuery.parameterized(String.format("SELECT name FROM `%s` WHERE $1 IN interests", bucketName),
JsonArray.from("African Swallows"))
);

// Print each found Row
for (N1qlQueryRow row : result) {
// Prints {"name":"Arthur"}
System.out.println(row);
}
}

public static List<X509Certificate> decodeCertificates(final List<String> 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());
}
}
38 changes: 38 additions & 0 deletions nodejs/cloud.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
var couchbase = require('couchbase');

var N1qlQuery = couchbase.N1qlQuery;

// Update this to your cluster
const endpoint = 'cb.e207a530-a469-492f-89d4-a5392e265c10.dp.cloud.couchbase.com'
const username = 'user'
const password = 'password'
const bucketName = 'couchbasecloudbucket'
// User Input ends here.

// Initialize the Connection
var cluster = new couchbase.Cluster('couchbases://' +endpoint+'?ssl=no_verify', {username: username, password: password});
var bucket = cluster.openBucket(bucketName);

// Create a N1QL Primary Index (but ignore if it exists)
bucket.manager().createPrimaryIndex({ignoreExists: true}, function() {
// Create and store a document
bucket.upsert('user:king_arthur', {
'name': 'Arthur', 'email': '[email protected]', 'interests': ['Holy Grail', 'African Swallows']
},
function (err, result) {
// Load the Document and print it
// Prints Content and Metadata of the stored Document
bucket.get('user:king_arthur', function (err, result) {
console.log('Got result: %j', result.value);

// Perform a N1QL Query
bucket.query(
N1qlQuery.fromString('SELECT name FROM '+ bucketName + ' WHERE $1 in interests LIMIT 1'),
['African Swallows'],
function (err, rows) {
// Print the result
console.log('Got rows: %j', rows);
});
});
});
});
38 changes: 38 additions & 0 deletions php/cloud.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
######## Update this to your cluster
$endpoint = "cb.e207a530-a469-492f-89d4-a5392e265c10.dp.cloud.couchbase.com";
$username = "user";
$password = "password";
$bucketName = "couchbasecloudbucket";
#### User Input ends here.

var_dump("couchbases://$endpoint?ssl=no_verify");
// Initialize the Connection
$myCluster = new CouchbaseCluster("couchbases://$endpoint?ssl=no_verify");
$authenticator = new \Couchbase\PasswordAuthenticator();
$authenticator->username($username)->password($password);
$myCluster->authenticate($authenticator);
$myBucket = $myCluster->openBucket($bucketName);

// Create a N1QL Primary Index (but ignore if it exists)
$myBucket->manager()->createN1qlPrimaryIndex("", true, false);

// Store a Document
$result = $myBucket->upsert("u:king_arthur", array(
"name" => "Arthur",
"email" => "[email protected]",
"interests" => array("Holy Grail", "African Swallows")
));

# Load the Document and print it
$result = $myBucket->get("u:king_arthur");
var_dump($result->value);

# Perform a N1QL Query
$query = CouchbaseN1qlQuery::fromString("SELECT * FROM `$bucketName` WHERE \$1 IN interests");
$query->positionalParams(array("African Swallows"));

# Print each found Row
$rows = $myBucket->query($query);
echo "Results:\n";
var_dump($rows);
31 changes: 31 additions & 0 deletions python/cloud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator
from couchbase.n1ql import N1QLQuery

######## Update this to your cluster
endpoint = 'cb.e207a530-a469-492f-89d4-a5392e265c10.dp.cloud.couchbase.com'
username = 'user'
password = 'password'
bucket_name = 'couchbasecloudbucket'
#### User Input ends here.

# Initialize the Connection
cluster = Cluster('couchbases://' + endpoint + '?ssl=no_verify') # Update the cluster endpoint
authenticator = PasswordAuthenticator(username, password)
cluster.authenticate(authenticator)
cb = cluster.open_bucket(bucket_name)

# Create a N1QL Primary Index (but ignore if it exists)
cb.bucket_manager().n1ql_index_create_primary(ignore_exists=True)

# Store a Document
cb.upsert('u:king_arthur', {'name': 'Arthur', 'email': '[email protected]', 'interests': ['Holy Grail', 'African Swallows']})

# Load the Document and print it
print(cb.get('u:king_arthur').value)

# Perform a N1QL Query
row_iter = cb.n1ql_query(N1QLQuery('SELECT name FROM %s WHERE $1 IN interests' % (bucket_name), 'African Swallows'))

# Print each found Row
for row in row_iter: print(row)

0 comments on commit c9373a0

Please sign in to comment.