Coding Applications for Astra in JAVA - datastaxdevs/awesome-astra GitHub Wiki

🏠 Back to home | Written by Cedrick Lunven, Last Update 3/10/2022

Working with Java

Astra provides include multiple components, and, for each, there are multiple interfaces as shown on the schema on the right. Frameworks and tools and methods to integrate with Astra are related to the interface used.

Pick the interface in the table to get relevant instructions. In most case you download a working sample. Those are standalone examples designed as simple as possible. please note that a Software developement KIT (SDK) is also available for you to reduce boilerplate. More information here.

Pick the interface you need to use

Component Interface Description
Astra DB cql Main connection to Cassandra
Astra DB cql CQL exposes as stateless rest resources
Astra DB cql Use Cassandra as a Document DB
Astra DB cql Create tables and use generated CRUD
Astra DB cql CQL exposes through serialized protobuf
Astra Streaming cql Create Producer, Consumers, Subscriptions..
Astra Streaming cql Administrate your Pulsar cluster
Astra Core cql Manage users and roles
Astra Core cql Manage Databases
Astra Core cql Manage Streaming

CQL Cassandra Drivers

Drivers reference documentation can be found HERE, this page is focused on connectivity with Astra DB only.

Using Java Cassandra Drivers version 4.x (recommended)

Version 4 is major redesign of the internal architecture. As such, it is not binary compatible with previous versions. However, most of the concepts remain unchanged, and the new API will look very familiar to 2.x and 3.x users.

  • If you want to know more the rational is explained in this blogpost.
  • If you are still using 3.x and want to migrate you can have a look the upgrade guide but you can also keep using 3.x as described below

📦. Prerequisites [ASTRA]

📦. Prerequisites [Development Environment]

  • You should install Java Development Kit (JDK) 8: Use the reference documentation to install a Java Development Kit, Validate your installation with
java --version
mvn -version

📦. Setup Project

  • Any version 4.x should be compatible with Astra.

  • Update your pom.xml file with the latest version of the 4.x libraries: Maven Central

<!-- (REQUIRED) -->
<dependency>
 <groupId>com.datastax.oss</groupId>
 <artifactId>java-driver-core</artifactId>
<version>${latest4x}</version>
</dependency>
		
<!-- OPTIONAL -->
<dependency>
 <groupId>com.datastax.oss</groupId>
 <artifactId>java-driver-query-builder</artifactId>
 <version>${latest4x}</version>
</dependency>
<dependency>
 <groupId>com.datastax.oss</groupId>
 <artifactId>java-driver-mapper-runtime</artifactId>
<version>${latest4x}</version>
</dependency>

🖥️ . Sample Code (project astra-driver4x)

import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraDriver4x {
 
 static final String ASTRA_ZIP_FILE = "<path_to_secureConnectBundle.zip>";
 static final String ASTRA_USERNAME = "<provide_a_clientId>";
 static final String ASTRA_PASSWORD = "<provide_a_clientSecret>";
 static final String ASTRA_KEYSPACE = "<provide_your_keyspace>";
    
 public static void main(String[] args) {
   Logger logger = LoggerFactory.getLogger(AstraDriver4x.class);
   try (CqlSession cqlSession = CqlSession.builder()
     .withCloudSecureConnectBundle(Paths.get(ASTRA_ZIP_FILE))
     .withAuthCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
     .withKeyspace(ASTRA_KEYSPACE)
     .build()) {
     logger.info("[OK] Welcome to ASTRA. Connected to Keyspace {}", cqlSession.getKeyspace().get());
   }
   logger.info("[OK] Success");
   System.exit(0);
 }

}

dl

🔗. Extra Resources for Cassandra Drivers 4.x

⏫ Back to top

Using Java Cassandra Drivers version 3.x

📦. Prerequisites [ASTRA]

📦. Prerequisites [Development Environment]

  • You should install Java Development Kit (JDK) 8: Use the reference documentation to install a Java Development Kit, Validate your installation with
java --version
mvn -version

📦. Setup Project

  • Please note that version 3.8+ is required to connect to Astra.

  • Update your pom.xml file with the latest version of the 3.x libraries: Maven Central

<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-core</artifactId>
  <version>${latest3x}</version>
</dependency>

🖥️. Sample Code (project astra-driver3x)

import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

public class AstraDriver3x {    
 
 // Define inputs
 static final String ASTRA_ZIP_FILE = "<path_to_secureConnectBundle.zip>";
 static final String ASTRA_USERNAME = "<provide_a_clientId>";
 static final String ASTRA_PASSWORD = "<provide_a_clientSecret>";
 static final String ASTRA_KEYSPACE = "<provide_your_keyspace>";    
    
 public static void main(String[] args) {
  Logger logger = LoggerFactory.getLogger(AstraDriver3x.class);
  try(Cluster cluster = Cluster.builder()
    .withCloudSecureConnectBundle(new File(ASTRA_ZIP_FILE))
    .withCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
    .build() ) {
      Session session = cluster.connect(ASTRA_KEYSPACE);
      logger.info("[OK] Welcome to ASTRA. Connected to Keyspace {}", session.getLoggedKeyspace());
  }
  logger.info("[OK] Success");
  System.exit(0);
 }

}

dl

🔗. Extra Resources for Cassandra Drivers 3.x

⏫ Back to top

Stargate REST Api

ℹ️ Overview

Stargate is a data gateway (Proxy) on top of Apache Cassandra exposing new interface to ease the integration. It is a way to create stateless components (1) and ease the integration with 4 different HTTP Apis (rest, doc, graphQL, gRPC). In this chapter we will cover integration with REST Apis also called DATA in the swagger specifications.

To know more regarding this interface specially you can have a look to dedicated section of the wiki or reference Stargate Rest Api Quick Start Guide.

⚠️ We recommend to use version V2 (with V2 in the URL) as it covers more features and the V1 would be deprecated sooner.

v2

📦 . Prerequisites [ASTRA]

📦 . Prerequisites [Development Environment]

mvn -version

📦 . Setup Project

<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>

🖥️. Sample Code (project astra-httpclient-restapi).

public class AstraRestApiHttpClient {
    
    static final String ASTRA_TOKEN       = "<change_with_your_token>";
    static final String ASTRA_DB_ID       = "<change_with_your_database_identifier>";
    static final String ASTRA_DB_REGION   = "<change_with_your_database_region>";
    static final String ASTRA_DB_KEYSPACE = "<change_with_your_keyspace>";
    
    static  Logger logger = LoggerFactory.getLogger(AstraRestApiHttpClient.class);
    
    public static void main(String[] args) throws Exception {
        
        String apiRestEndpoint = new StringBuilder("https://")
                .append(ASTRA_DB_ID).append("-")
                .append(ASTRA_DB_REGION)
                .append(".apps.astra.datastax.com/api/rest")
                .toString();
        logger.info("Rest Endpoint is {}", apiRestEndpoint);
        
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            listKeyspaces(httpClient, apiRestEndpoint);
            createTable(httpClient, apiRestEndpoint);
            insertRow(httpClient, apiRestEndpoint);
            retrieveRow(httpClient, apiRestEndpoint);
        }
        logger.info("[OK] Success");
        System.exit(0);
    }
  • List keyspaces

listks

private static void listKeyspaces(CloseableHttpClient httpClient, String apiRestEndpoint) 
throws Exception {
 // Build Request
 HttpGet listKeyspacesReq = new HttpGet(apiRestEndpoint + "/v2/schemas/keyspaces");
 listKeyspacesReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
 
 // Execute Request
 try(CloseableHttpResponse res = httpClient.execute(listKeyspacesReq)) {
   if (200 == res.getCode()) {
     logger.info("[OK] Keyspaces list retrieved");
     logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
   }
 }
}
  • Create a Table

table

Query used is createTableJson here:

{
  "name": "users",
  "columnDefinitions":
    [
        {
        "name": "firstname",
        "typeDefinition": "text"
      },
        {
        "name": "lastname",
        "typeDefinition": "text"
      },
      {
        "name": "email",
        "typeDefinition": "text"
      },
        {
        "name": "color",
        "typeDefinition": "text"
      }
    ],
  "primaryKey":
    {
      "partitionKey": ["firstname"],
      "clusteringKey": ["lastname"]
    },
  "tableOptions":
    {
      "defaultTimeToLive": 0,
      "clusteringExpression":
        [{ "column": "lastname", "order": "ASC" }]
    }
}

Create Table code

private static void createTable(CloseableHttpClient httpClient, String apiRestEndpoint) 
throws Exception {
  HttpPost createTableReq = new HttpPost(apiRestEndpoint 
       + "/v2/schemas/keyspaces/" + ASTRA_DB_KEYSPACE + "/tables");
  createTableReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
  String createTableJson = "{...JSON.....}";
  createTableReq.setEntity(new StringEntity(createTableJson, ContentType.APPLICATION_JSON));
  
  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(createTableReq)) {
    if (201 == res.getCode()) {
      logger.info("[OK] Table Created (if needed)");
      logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
    }
  }
}
  • Insert a Row

row

private static void insertRow(CloseableHttpClient httpClient, String apiRestEndpoint) 
throws Exception {
  HttpPost insertCedrick = new HttpPost(apiRestEndpoint + "/v2/keyspaces/" 
   + ASTRA_DB_KEYSPACE + "/users" );
  insertCedrick.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
  insertCedrick.setEntity(new StringEntity("{"
    + " \"firstname\": \"Cedrick\","
    + " \"lastname\" : \"Lunven\","
    + " \"email\"    : \"[email protected]\","
    + " \"color\"    : \"blue\" }", ContentType.APPLICATION_JSON));
        
  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(insertCedrick)) {
    if (201 == res.getCode()) {
      logger.info("[OK] Row inserted");
      logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
    }
  }
}
  • Retrieve a row

row

private static void retrieveRow(CloseableHttpClient httpClient, String apiRestEndpoint) 
throws Exception {

  // Build Request
  HttpGet rowReq = new HttpGet(apiRestEndpoint + "/v2/keyspaces/" 
    + ASTRA_DB_KEYSPACE + "/users/Cedrick/Lunven" );
  rowReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
        
  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(rowReq)) {
    if (200 == res.getCode()) {
      String payload =  EntityUtils.toString(res.getEntity());
      logger.info("[OK] Row retrieved");
      logger.info("Row retrieved : {}", payload);
    }
  }
}

dl

⏫ Back to top

Stargate Document Api

ℹ️ Overview

api XXX

📦. Prerequisites [ASTRA]

📦. Prerequisites [Development Environment]

mvn -version

📦. Setup Project

  • Import relevant dependencies for Apache Http Client in your pom.xml. Jackon is also helpful to serialize or unserialized Java Objects as JSON.
<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>

🖥️. Sample Code (project astra-httpclient-docapi).

⏫ Back to top

Stargate GraphQL

5.1 Cql First

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

5.2 GraphQl Types First

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

Stargate gRPC

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

Pulsar Client

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

Pulsar Admin

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

Devops API

Devops Database API

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

Devops Streaming API

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

Devops Organization Apis

ℹ️ Overview

TODO

📦. Prerequisites [ASTRA]

TODO

📦. Prerequisites [Development Environment]

TODO

📦. Setup Project

TODO

🖥️. Sample Code

TODO

⏫ Back to top

⚠️ **GitHub.com Fallback** ⚠️