-
Notifications
You must be signed in to change notification settings - Fork 4
Coding Applications for Astra in JAVA
🏠 Back to home | Written by Cedrick Lunven, Last Update 3/10/2022
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.
Drivers reference documentation can be found HERE, this page is focused on connectivity with Astra DB only.
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.xand want to migrate you can have a look the upgrade guide but you can also keep using3.xas described below
- You should have an Astra account
- You should Create and Astra Database
- You should Have an Astra Token
- You should Download your Secure bundle
- You should install Java Development Kit (JDK) 8: Use the reference documentation to install a Java Development Kit, Validate your installation with
java --version- You should install Apache Maven: Use the reference documentation and validate your installation with
mvn -version-
Any version
4.xshould be compatible with Astra. -
Update your
pom.xmlfile with the latest version of the 4.x libraries:
<!-- (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);
}
}- Multiple Standalone Classes using driver 4.x
- Spring PetClinic in Reactive and specially the mapper
- You should have an Astra account
- You should Create and Astra Database
- You should Have an Astra Token
- You should Download your Secure bundle
- You should install Java Development Kit (JDK) 8: Use the reference documentation to install a Java Development Kit, Validate your installation with
java --version- You should install Apache Maven: Use the reference documentation and validate your installation with
mvn -version-
Please note that version 3.8+ is required to connect to Astra.
-
Update your
pom.xmlfile with the latest version of the 3.x libraries:
<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);
}
}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 versionV2(with V2 in the URL) as it covers more features and the V1 would be deprecated sooner.

- You should have an Astra account
- You should Create and Astra Database
- You should Have an Astra Token
-
You should install Java Development Kit (JDK) 8: Use the reference documentation to install a Java Development Kit.
-
You should install Apache Maven: Use the reference documentation and validate your installation with
mvn -version-
You simple need an
HTTP Clientto use the Rest API. There are a lot in the Java languages like HttpURLConnection, HttpClient introduced in Java 11, Apache HTTPClient, OkHttpClient, Jetty HttpClient. A comparison is provided is this blogpost to make your choice. In this tutorial we will go withApache HttpClient, this is the one used in the SDK, you should adapt the code depending on the framework you choosed. -
Import relevant dependencies for
Apache Http Clientin yourpom.xml
<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

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

Query used is
createTableJsonhere:
{
"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

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\" : \"c.lunven@gmail.com\","
+ " \"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

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);
}
}
}api XXX
- You should have an Astra account
- You should Create and Astra Database
- You should Have an Astra Token
-
You should install Java Development Kit (JDK) 8: Use the reference documentation to install a Java Development Kit.
-
You should install Apache Maven: Use the reference documentation and validate your installation with
mvn -version- Import relevant dependencies for
Apache Http Clientin yourpom.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).
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO
TODO










