Skip to content

• Astra SDK Java


Astra Java SDK is a framework that wraps different apis and interfaces exposed by Astra and provides fluent API and ease of usage.

1. Pre-requisites

Setup your JAVA Development environment
  • Install Java Development Kit (JDK) 8+

Use java reference documentation targetting your operating system to install a Java Development Kit. You can then validate your installation with the following command.

java --version
  • Install Apache Maven (3.8+)

Samples and tutorials have been designed with Apache Maven. Use the reference documentation top install maven validate your installation with

mvn -version
Setup Datastax Astra DB
  • Create your DataStax Astra account:

Sign Up

  • Create an Astra Token

An astra token acts as your credentials, it holds the different permissions. The scope of a token is the whole organization (tenant) but permissions can be edited to limit usage to a single database.

To create a token, please follow this guide

The Token is in fact three separate strings: a Client ID, a Client Secret and the token proper. You will need some of these strings to access the database, depending on the type of access you plan. Although the Client ID, strictly speaking, is not a secret, you should regard this whole object as a secret and make sure not to share it inadvertently (e.g. committing it to a Git repository) as it grants access to your databases.

{
  "ClientId": "ROkiiDZdvPOvHRSgoZtyAapp",
  "ClientSecret": "fakedfaked",
  "Token":"AstraCS:fake"
}

It is handy to have your token declare as an environment variable (replace with proper value):

export ASTRA_TOKEN="AstraCS:replace_me"
  • Create a Database and a keyspace

With your account you can run multiple databases, a Databases is an Apache Cassandra cluster. It can live in one or multiple regions (dc). In each Database you can have multiple keyspaces. In the page we will use the database name db_demo and the keyspace keyspace_demo.

You can create the DB using the user interface and here is a tutorial. You can also use Astra command line interface. To install and setup the CLI run the following:

curl -Ls "https://dtsx.io/get-astra-cli" | bash
source ~/.astra/cli/astra-init.sh
astra setup --token ${ASTRA_TOKEN}

To create DB and keyspace with the CLI:

astra db create db_demo -k keyspace_demo --if-not-exists
  • Download the Secure Connect Bundle for current database

A Secure Connect Bundle contains the certificates and endpoints informations to open a mTLS connection. Often mentionned as scb its scope is a database AND a region. If your database is deployed on multiple regions you will have to download the bundle for each one and initiate the connection accordingly. Instructions to download Secure Connect Bundle are here

You can download the secure connect bundle from the user interface and here is a tutorial. You can also use Astra command line interface.

astra db download-scb db_demo -f /tmp/secure-connect-bundle-db-demo.zip

2. Astra DB

2.1 - Project Setup

Project Setup
  • If you create a project from scratch you can start with our template that include the astra-sdk dependency.:
mvn archetype:generate \
  -DarchetypeGroupId=com.datastax.astra \
  -DarchetypeArtifactId=astra-sdk-quickstart \
  -DarchetypeVersion=0.6.2 \
  -DinteractiveMode=false \
  -DgroupId=foo.bar \
  -DartifactId=astra-quickstart\
  -Dversion=1.0-SNAPSHOT
  • OR, if you already have a project simple Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>

2.2 - CQL Native Drivers

Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraSdkDrivers {
    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .withCqlKeyspace("demo")
                .enableCql()
                .build()) {

            try(CqlSession cqlSession = astraClient.cqlSession()) {
                System.out.println("+ Cql Version (cql)   : " + cqlSession
                  .execute("SELECT cql_version from system.local")
                  .one().getString("cql_version"));
            }
        }
    }
}

 Download Project

What you need to know

🔑 About Credentials

  • The pair clientId/ clientSecret hold your credentials. It can be replaced by the value of the token only.
AstraClient.builder().withToken("AstraCS:...");
  • There is no need to download the cloud securebundle in advance as it will be downloaded for you in folder ~.astra/scb by default. Stil, but you can also provide the file location with .withCqlCloudSecureConnectBundle():
AstraClient.builder().withCqlCloudSecureConnectBundle("/tmp/scb.zio");
  • Notice than enableCQL() must be explictely provided. The sdk will open only the asked interfaces in order to limit the resource consumption.

⚙️ About Database identifiers

  • databaseId/databaseRegion will be required to locate the proper endpoint. You can find them for a particular database with either the cli.
$astra db list

+---------------------+--------------------------------------+---------------------+-----------+
| Name                | id                                   | Default Region      | Status    |
+---------------------+--------------------------------------+---------------------+-----------+
| db_demo             | 3043a40f-39bf-464e-8337-dc283167b2c3 | us-east1            | ACTIVE    |
+---------------------+--------------------------------------+---------------------+-----------+

$astra db describe db_demo

+------------------------+-----------------------------------------+
| Attribute              | Value                                   |
+------------------------+-----------------------------------------+
| Name                   | db_demo                                 |
| id                     | 3043a40f-39bf-464e-8337-dc283167b2c3    |
| Status                 | ACTIVE                                  |
| Default Cloud Provider | GCP                                     |
| Default Region         | us-east1                                |
| Default Keyspace       | keyspace_demo                           |
| Creation Time          | 2023-04-17T09:03:14Z                    |
| Keyspaces              | [0] demo                                |
| Regions                | [0] us-east1                            |
+------------------------+-----------------------------------------+

2.3 - Stargate Rest API

The REST API (also known as api Data) is wrapping exposing CQL language as Rest Resources. To get more information about this API check the dedicated page

Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.core.domain.RowResultPage;
import io.stargate.sdk.rest.StargateRestApiClient;
import io.stargate.sdk.rest.TableClient;
import io.stargate.sdk.rest.domain.CreateTable;
import io.stargate.sdk.rest.domain.SearchTableQuery;

import java.util.HashMap;
import java.util.Map;

public class AstraSdkRestApi {
    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {
            StargateRestApiClient restApiClient =
                    astraClient.apiStargateData();

            // -- Create a table
            CreateTable createTable = CreateTable.builder()
                    .name("my_table")
                    .addPartitionKey("foo", "text")
                    .addColumn("bar", "text")
                    .ifNotExist(true)
                    .build();
            restApiClient.keyspace("demo")
                    .createTable("my_table", createTable);

            // we can now work on the table
            TableClient tableClient = restApiClient
                    .keyspace("demo")
                    .table("my_table");

            // -- Insert a row
            Map<String, Object> record = new HashMap<>();
            record.put("foo", "Hello");
            record.put("bar", "World");
            tableClient.upsert(record);

            // -- Retrieve rows
            SearchTableQuery query = SearchTableQuery.builder().
                    select("foo", "bar")
                    .where("foo")
                    .isEqualsTo("Hello")
                    .build();
            RowResultPage result = tableClient.search(query);
            System.out.println(result.getResults()
                    .get(0).get("bar"));
        }
    }
}

 Download Project

More information about Rest API

2.4 - Stargate Document API

The DOCUMENT API exposes an Rest Resources to use Cassandra as a document-oriented database To get more information about this API check the dedicated page.

Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.doc.CollectionClient;
import io.stargate.sdk.doc.Document;
import io.stargate.sdk.doc.StargateDocumentApiClient;

import java.util.stream.Collectors;

public class AstraSdkDocApi {

    // Given a Java POJO
    public static final class User {
        String email;
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {

            StargateDocumentApiClient apiDoc =
                    astraClient.apiStargateDocument();

            // List namespaces
            System.out.println("- List namespaces  : " + apiDoc
                            .namespaceNames()
                            .collect(Collectors.toList()));

            // List Collection in a Keyspace
            System.out.println("- List collections : " + apiDoc
                    .namespace("demo")
                    .collectionNames()
                    .collect(Collectors.toList()));

            // Create collection
            CollectionClient userCollection = apiDoc
                    .namespace("demo")
                    .collection("user");
            if (!userCollection.exist()) userCollection.create();

            // Working with documents
            User userA = new User();userA.setEmail("a@a.com");
            User userB = new User();userB.setEmail("b@b.com");

            // Create a Document and let Astra create the ID
            String userADocumentId = userCollection.create(userA);
            System.out.println("Document Created: " + userADocumentId);

            // Create a Document with a specific ID
            userCollection.document("b@b.com").upsert(userB);

            // List Documents
            System.out.println("Documents:");
            for(Document<User> doc : userCollection.findPage(User.class).getResults()) {
                System.out.println("" +
                        "- id: " + doc.getDocumentId() +
                        ", email : " + doc.getDocument().getEmail());
            }
        }
    }



}

 Download Project

Document Repository

With modern java applications you want to interact with the DB using the repository pattern where most operations have been implemented for you findAll(), findById().... Astra SDK provide this feature for the document API.

Sample Document Repository
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.doc.StargateDocumentRepository;

public class AstraSdkDocRepository {

    // Given a Java POJO
    public static final class User {
        String email;
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .withCqlKeyspace("demo")
                .enableCql()
                .build()) {

            // Doc Repository
            StargateDocumentRepository<User> userRepo =
                    new StargateDocumentRepository<User>(
                            astraClient.apiStargateDocument().namespace("demo"),
                            User.class);

            // Working with documents
            User userA = new User();
            userA.setEmail("a@a.com");
            User userB = new User();
            userB.setEmail("b@b.com");

            // Create Documents
            userRepo.insert(userA);
            userRepo.insert("b@b.com", userB);

            // List Documents
            userRepo.findAll().forEach(doc -> {
                System.out.println(
                        "id=" + doc.getDocumentId()
                        + ", email= " + doc.getDocument().getEmail());
            });

        }
    }
}

 Download Project

2.5 - Stargate Grpc APi

The GRPC API exposes a grpc endpoint to query some CQL. From there it is very similar from native drivers. To know more about it check the dedicated page.

Sample Code
AstraSdkGrpcApi.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.grpc.StargateGrpcApiClient;

public class AstraSdkGrpcApi {

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {

            StargateGrpcApiClient grpcClient = astraClient.apiStargateGrpc();
            System.out.println("+ Cql Version (grpc)  : " + grpcClient
                    .execute("SELECT cql_version from system.local")
                    .one().getString("cql_version"));
        }

    }
}

 Download Project

2.6 - Stargate GraphQL Api

The GRAPHQL API exposes a graphQL endpoint to query CQL over graphQL. To know more about this api please check the dedicated page.

Sample Code
AstraSdkGraphQLApi.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.gql.StargateGraphQLApiClient;

public class AstraSdkGraphQLApi {

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {

            StargateGraphQLApiClient graphClient = astraClient.apiStargateGraphQL();
            graphClient.keyspaceDDL().keyspaces().forEach(k-> System.out.println(k.getName()));
        }
    }
}

 Download Project

3. Astra Streaming

3.1 - Project setup

Project Setup
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk-pulsar</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>

3.2 - PulsarClient

Pulsar Api are very simple and the need of an sdk is limited. It could be used to get the proper version of pulsar-client, there are no extra setup steps.

PulsarClient Setup
String pulsarUrl   = "pulsar+ssl://<cluster>.streaming.datastax.com:6651";
String pulsarToken = "<your_token>"
try(PulsarClient cli = new PulsarClientProvider(pulsarUrl, pulsarToken).get()) {
  // work with client
};

3.3 - Pulsar Admin

Pulsar Api are very simple and the need of an sdk is limited. It could be used to to setup the pulsar-admin for you.

Pulsar Admin Setup
String pulsarUrlAdmin = "https://<cluster>.api.streaming.datastax.com";
String pulsarToken = "<your_token>"
PulsarAdmin pa = new PulsarAdminProvider(pulsarUrlAdmin,pulsarToken).get();

// Get Infos
System.out.println(pa.tenants().getTenantInfo("tenant_name").toString());

// List Namespaces
pa.namespaces().getNamespaces("clun-gcp-east1").forEach(System.out::println);

// List Topics
pa.topics().getList("clun-gcp-east1/astracdc").forEach(System.out::println);

// Details on a topic
PersistentTopicInternalStats stats = pa.topics()
     .getInternalStats("persistent://<tenant>/<namespace>/<topic>");
System.out.println(stats.totalSize);

4.3 - Producer

The Astra user interface already shows the expected code. There is very little an SDK can provide here. A sample to code to copy.

Sample Code
import org.apache.pulsar.client.api.*;
import java.io.IOException;

public class SimpleProducer {

    private static final String CLUSTER      = "<cluster>";
    private static final String TENANT       = "<yourtenant>";
    private static final String NAMESPACE    = "<yournamespace>";
    private static final String TOPIC        = "<your_topic>";
    private static final String PULSAR_TOKEN = "<your_token>";
    private static final String SERVICE_URL  = 
      "pulsar+ssl://" + CLUSTER + "streaming.datastax.com:6651";

    public static void main(String[] args) throws IOException {
        try(PulsarClient cli = new PulsarClientProvider(pulsarUrl, pulsarToken).get()) {
            try( Producer<byte[]> producer = cli
                .newProducer()
                .topic("persistent://" + TENANT + "/"+NAMESPACE+"/" + TOPIC)
                .create()) {
                  // Send a message to the topic
                  producer.send("Hello World".getBytes());
                }
        };
    }
}

4.4 - Consumer

The Astra user interface already shows the expected code. There is very little an SDK can provide here. A sample to code to copy.

Sample Consumer
import org.apache.pulsar.client.api.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class SimpleConsumer {

  private static final String CLUSTER      = "<cluster>";
  private static final String TENANT       = "<yourtenant>";
  private static final String NAMESPACE    = "<yournamespace>";
  private static final String TOPIC        = "<your_topic>";
  private static final String SUBSCRIPTION = "<your_subscription>";
  private static final String PULSAR_TOKEN = "<your_token>";

  public static void main(String[] args) throws IOException {
    try(PulsarClient cli = new PulsarClientProvider(
      "pulsar+ssl://" + CLUSTER + "streaming.datastax.com:6651", pulsarToken).get()) {
        try(Consumer consumer = cli
            .newConsumer()
            .topic("persistent://" + TENANT + "/"+NAMESPACE+"/" + TOPIC)
            .subscriptionName(SUBSCRIPTION)
            .subscribe()) {

            boolean receivedMsg = false;
            // Loop until a message is received
            do {
                // Block for up to 1 second for a message
                Message msg = consumer.receive(1, TimeUnit.SECONDS);

                if(msg != null){
                    System.out.printf("Message received: %s", new String(msg.getData()));

                    // Acknowledge the message to remove it from the message backlog
                    consumer.acknowledge(msg);

                    receivedMsg = true;
                }

            } while (!receivedMsg);
        }
    }
}

4. Spring Boot

4.1 - Create Project

Spring Boot 2x
  • To Create a project from scratch start with our template:

The 3 last parameters in this command define your project groupId, artifactId and version.

0.6 is the latest version of the starter Maven Central

mvn archetype:generate \
  -DarchetypeGroupId=com.datastax.astra \
  -DarchetypeArtifactId=spring-boot-2x-archetype \
  -DarchetypeVersion=0.6 \
  -DinteractiveMode=false \
  -DgroupId=fr.clunven \
  -DartifactId=my-demo-springboot2x \
  -Dversion=1.0-SNAPSHOT
Spring Boot 3x
  • To Create a project from scratch start with our template:

The 3 last parameters in this command define your project groupId, artifactId and version.

0.6 is the latest version of the starter Maven Central

mvn archetype:generate \
  -DarchetypeGroupId=com.datastax.astra \
  -DarchetypeArtifactId=spring-boot-3x-archetype \
  -DarchetypeVersion=0.6 \
  -DinteractiveMode=false \
  -DgroupId=fr.clunven \
  -DartifactId=my-demo-springboot3x \
  -Dversion=1.0-SNAPSHOT

4.2 - Setup Project

Spring Boot 2x

If you created your project with the archetypes the pom.xml is already correct.

  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
  <dependency>
      <groupId>com.datastax.astra</groupId>
      <artifactId>astra-spring-boot-starter</artifactId>
      <version>${latest-stater}</version>
  </dependency>
</dependencies>
Spring Boot 3x

If you created your project with the archetypes the pom.xml is already correct.

  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
  <dependency>
      <groupId>com.datastax.astra</groupId>
      <artifactId>astra-spring-boot-3x-starter</artifactId>
      <version>${latest-stater}</version>
  </dependency>
</dependencies>

4.3 - Configuration

Configuration of application.xml

If you created the project with the archetypes the file is already populated.

  • Update your application.xml with the following keys
astra:
  api:
    application-token: ${ASTRA_DB_APPLICATION_TOKEN}
    database-id: ${ASTRA_DB_ID}
    database-region: ${ASTRA_DB_REGION}
    cross-region-failback: false
  cql:
    enabled: true
    download-scb:
      enabled: true
    driver-config:
      basic:
        session-keyspace: ${ASTRA_DB_KEYSPACE}

As you notice there are 4 variables to be replaced to point to your Astra Database. You can create environment variables or do the substition manually.

Param Description
ASTRA_DB_APPLICATION_TOKEN Your authentication token starting with AstraCS:.. It MUST HAVE ADMINISTRATION PRIVILEGES in order to download the secure connect bundle from devops API.
ASTRA_DB_ID Your database identifier, it is a UUID available at the top of your db page in the user interface or in the CLI with astra db list
ASTRA_DB_REGION Your database main region. Even if the database lives in multiple region you need to provide the main one (to reduce latency). The id of the region also provides information on the cloud provide in used. There is no need for an extra parameter. It is a value available in the details database page in the user interface or in the CLI with astra db list
ASTRA_DB_KEYSPACE The keyspace where to connect your application.

The ASTRA CLI can help you defining those environment variables with the following:

# Create a file .env with all needed keys
astra db create-dotenv demo -d `pwd`

# Load Those keys as environment variables
set -a
source .env
set +a

# Display variables in the console
env | grep ASTRA_DB

4.4 - Run Application

You can now start your application with:

mvn spring-boot:run

If you created the application with archetype a firs table todos has been created and populated. An REST APi is also available for your

curl localhost:8080/todos

5. Astra Devops Api

Reminders

To work with the devops Apis it is recommanded to have an Organization Administrator role token. Most of the operation indeed required an high level of permissions.

  • Create an Astra Token

To create a token, please follow this guide

Project Setup

If you added the astra-sdk dependency your are good to go. Now if you want to work only work with the Devops API and not the stargate APis you might want to only import this subset.

  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk-devops</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
  • Initializing the Devopis Api Client
// It can be accessed from the global AstraClient
AstraClient          astraClient = ....;
AstraDevopsApiClient apiDevopsClient          =  astraClient.apiDevops();
AstraDbClient        apiDevopsClientDb        = astraClient.apiDevopsDatabases();
AstraStreamingClient apiDevopsClientStreaming = astraClient.apiDevopsStreaming();

// You can only setup the devops part
AstraDevopsApiClient apiDevopsDirect = new AstraDevopsApiClient(getToken());

5.1 - Astra DB

The SDK is extensively tested a lot of samples can be found in the database unit tests

Sample Code
String token = "<your_token>";
AstraDbClient devopsDbsClient = new AstraDbClient(token);

// Create DB
devopsDbsClient.create(DatabaseCreationRequest
                    .builder()
                    .name("my_db")
                    .keyspace("my_keyspace")
                    .cloudRegion("my_region")
                    //.withVector() to enable vector preview
                    .build());

Stream<Database> dbList = devopsDbsClient.findByName("my_db");

// Working with 1 db
DatabaseClient dbCli = devopsDbsClient.databaseByName("my_db"));

// Keyspaces
dbCli.keyspaces().exist(SDK_TEST_KEYSPACE2)
dbCli.keyspaces().create(SDK_TEST_KEYSPACE2)
dbCli.keyspaces().delete("invalid")

// Scb
dbCli.downloadDefaultSecureConnectBundle(randomFile);
dbCli.downloadSecureConnectBundle(SDK_TEST_DB_REGION, randomFile);
dbCli.downloadAllSecureConnectBundles("/invalid"));

 // Multi-Regions
 dbCli.datacenters().create("serverless", CloudProviderType.AWS, "eu-central-1");
 dbCli.datacenters().delete("eu-central-1");

 // Classic Ops
 dbCli.park()
 dbCli.unpark()
 dbCli.resize(2)
 dbCli.resetPassword("token", "cedrick1")

 // Access-list
 dbCli.accessLists().addAddress(a1, a2);

5.2 - Astra Streaming

The SDK is extensively tested a lot of samples can be found in the streaming unit tests

Sample Code
// Lists Tenants for a users
 Set<String> tenants = cli.findAll()
            .map(Tenant::getTenantName)
            .collect(Collectors.toSet());

5.3 - Organization

The SDK is extensively tested a lot of samples can be found in the control unit tests

Sample Code
Organization org = getApiDevopsClient().getOrganization();

6. Extra Resources

6.1 - Source Code and Issues

6.2 - JavaDoc

The javadocs are available here:


Last update: 2023-06-16