A newer version of this documentation is available.

View Latest
March 16, 2025
+ 12

Description — Build and run a starter app to validate your install of Couchbase Lite on Java
Abstract — This content provides sample code and instructions that enable you to test your Couchbase Lite for java installation.
Related Content — Install | Prerequisites | Build and Run |

Build a Getting Started App

This section explains how to validate your configured build environment by building a starter app that uses many of Couchbase Lite on Java’s more common features.

The GettingStarted app demonstrates how to use Couchbase Lite on Java. Console and Web App versions are available.

Development-type Scenarios
Ensure you added the Couchbase Lite dependency to your build.gradle file

Create, build and run a new project using the following GettingStarted.java code:

import com.couchbase.lite.*;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class GettingStarted {

private static final String DB_NAME = "getting-started";
/*      Credentials declared this way purely for expediency in this demo - use OAUTH in production code */
private static final String DB_USER = "sync_gateway";
private static final String DB_PASS = "password"; (3)
//    private static final String SYNC_GATEWAY_URL = "ws://127.0.0.1:4984/db" + DB_NAME;
private static final String SYNC_GATEWAY_URL = "ws://127.0.0.1:4984/getting-started"; (1)
private static final String DB_PATH = new File("").getAbsolutePath()+"/resources";


public static void main (String [] args) throws CouchbaseLiteException, InterruptedException, URISyntaxException {
    Random RANDOM = new Random();
    int randPtrLang = RANDOM.nextInt(5) ;
    int randPtrType = RANDOM.nextInt(5) ;
    int numRows = 0;

    Double randVn = RANDOM.nextDouble() + 1;

    List<String> listLangs = new ArrayList<String> (Arrays.asList("Java","Swift","C#.Net","Objective-C","C++","Cobol"));
//        List<String> listTypes = new ArrayList<String>();
    List<String> listTypes = new ArrayList<String> (Arrays.asList("SDK","API","Framework","Methodology","Language","IDE"));

    String Prop_Id ="id";
    String Prop_Language = "language";
    String Prop_Type = "type";
    String Prop_Version = "version";
    String searchStringType = "SDK";
    String dirPath = new File("").getAbsolutePath()+"/resources";


    // Initialize Couchbase Lite
    CouchbaseLite.init(); (2)

    // Get the database (and create it if it doesn’t exist).
    DatabaseConfiguration config = new DatabaseConfiguration();

    config.setDirectory(context.getFilesDir().getAbsolutePath()); (5)

    config.setEncryptionKey(new EncryptionKey(DB_PASS)); (3)
    Database database = new Database(DB_NAME, config);

    // Create a new document (i.e. a record) in the database.
    MutableDocument mutableDoc = new MutableDocument()
            .setDouble(Prop_Version, randVn)
            .setString(Prop_Type,listTypes.get(randPtrType));

    // Save it to the database.
    database.save(mutableDoc);

    // Update a document.
    mutableDoc = database.getDocument(mutableDoc.getId()).toMutable();
    mutableDoc.setString(Prop_Language, listLangs.get(randPtrLang));
    database.save(mutableDoc);

    Document document = database.getDocument(mutableDoc.getId());
    // Log the document ID (generated by the database) and properties
    System.out.println("Document ID is :: " + document.getId());
    System.out.println("Learning " + document.getString(Prop_Language));

    // Create a query to fetch documents of type SDK.
    System.out.println("== Executing Query 1");
    Query query = QueryBuilder.select(SelectResult.all())
            .from(DataSource.database(database))
            .where(Expression.property(Prop_Type).equalTo(Expression.string(searchStringType)));
    ResultSet result = query.execute();
    System.out.println(String.format("Query returned %d rows of type %s", result.allResults().size(), searchStringType));

    // Create a query to fetch all documents.
    System.out.println("== Executing Query 2");
    Query queryAll = QueryBuilder.select(SelectResult.expression(Meta.id),
            SelectResult.property(Prop_Language),
            SelectResult.property(Prop_Version),
            SelectResult.property(Prop_Type))
        .from(DataSource.database(database));
        try {
            for (Result thisDoc : queryAll.execute()) {
              numRows++;
              System.out.println(String.format("%d ... Id: %s is learning: %s version: %.2f type is %s",
                  numRows,
                  thisDoc.getString(Prop_Id),
                  thisDoc.getString(Prop_Language),
                  thisDoc.getDouble(Prop_Version),
                  thisDoc.getString(Prop_Type)));
              }
        } catch (CouchbaseLiteException e) {
            e.printStackTrace();
        }
    System.out.println(String.format("Total rows returned by query = %d", numRows));

    Endpoint targetEndpoint = new URLEndpoint(new URI(SYNC_GATEWAY_URL));
    ReplicatorConfiguration replConfig = new ReplicatorConfiguration(database, targetEndpoint);
    replConfig.setReplicatorType(ReplicatorConfiguration.ReplicatorType.PUSH_AND_PULL);

    // Add authentication.
    replConfig.setAuthenticator(new BasicAuthenticator(DB_USER, DB_PASS));

    // Create replicator (be sure to hold a reference somewhere that will prevent the Replicator from being GCed)
    Replicator replicator = new Replicator(replConfig);

    // Listen to replicator change events.
    replicator.addChangeListener(change -> {
        if (change.getStatus().getError() != null) {
            System.err.println("Error code ::  " + change.getStatus().getError().getCode());
        }
    });

    // Start replication.
    replicator.start();

    // Check status of replication and wait till it is completed
    while (replicator.getStatus().getActivityLevel() != Replicator.ActivityLevel.STOPPED) {
        Thread.sleep(1000);
    }

    System.out.println("Finish!");

    System.exit(0); (4)
}
1 The app will start a replicator pointing to ws://localhost:4984/db, where db is the name of your Sync Gateway database
2 This is the only API that differs from the Java (android) version. It accepts no parameters and should be called once only
3 You can optionally AES-256 encrypt the database by providing a key
4 This is needed for a tidy closedown of work executors
5 It is advisable to set a specific directory path for the database.

On running the app, you should see the document ID and property printed to the console together with a query result showing the number of rows in the database.

This shows the document was successfully persisted to the database.

See the tab About the Starter App for more on the app itself