Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rajagp/14ef1baf3b714f7c4f84fbe947300716 to your computer and use it in GitHub Desktop.
Save rajagp/14ef1baf3b714f7c4f84fbe947300716 to your computer and use it in GitHub Desktop.
Sample Java App with Couchbase Lite 1.4.4
//package com.couchbase.HelloWorld-Java;
import com.couchbase.lite.*;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorFactory;
import com.couchbase.lite.replicator.Replication;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
// Enable logging
Logger log = Logger.getLogger("db");
log.setLevel(Level.ALL);
JavaContext context = new JavaContext();
// Create a manager
Manager manager = null;
try {
manager = new Manager(context, Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
}
// Create or open the database named app
Database database = null;
try {
database = manager.getDatabase("db");
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
// The properties that will be saved on the document
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("title", "Couchbase Mobile");
properties.put("sdk", "Java");
// Create a new document
Document document = database.createDocument();
// Save the document to the database
try {
document.putProperties(properties);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
// Log the document ID (generated by the database)
// and properties
log.info(String.format("Document ID :: %s", document.getId()));
log.info(String.format("Learning %s with %s", (String) document.getProperty("title"), (String) document.getProperty("sdk")));
// Create replicators to push pull changes to from Sync Gateway.
URL url = null;
try {
url = new URL("http://localhost:4984/demobucket/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Replication push = database.createPushReplication(url);
Replication pull = database.createPullReplication(url);
Authenticator auth = AuthenticatorFactory.createBasicAuthenticator("admin", "password");
push.setAuthenticator(auth);
pull.setAuthenticator(auth);
push.setContinuous(true);
pull.setContinuous(true);
// Start replicators
push.start();
pull.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment