Skip to content
Cedrick Lunven edited this page May 3, 2021 · 51 revisions

License Apache2

Overview

The SDK makes it easy to call Stargate and/or Astra services using idiomatic Java APIs. On top of the SDK the repository provides a Spring Boot starter to ease integration with Spring Application.

Installation

You need JDK 11.0.9+ and a dependency management tool such as Maven or Gradle. (The SDK has been build with the HttpClient provided in JDK 11) It is a single library providing support for the 5 API(s) listed above. Please change the sdk-version with the latest version.

Maven dependency in pom.xml

<dependency>
  <groupId>com.datastax.astra</groupId>
  <artifactId>astra-sdk-java</artifactId>
  <version>${sdk-version}</version>
</dependency>

Gradle dependency in build.gradle

dependencies {
    astra_sdk 'com.datastax.astra:astra-sdk-java:${sdk-version}'
}

Initialising the SDK with Astra

a. Setup Astra Instance

To use Astra you need an Astra account and credentials with Astra Token. Then, based on the values you provided the underlying Apis will be enable or not.

Please follow those 2 tutorials to setup your instance

b. Sample Code

AstraClient client = AstraClient.builder()
 .appToken("AstraCS:......").              // App Token will be used as ApiKey for Devops, Docs and REST Api.
 .databaseId("astra_cluster_id").          // Unique identifier for your instance
 .cloudProviderRegion("astra_db_region")   // Cloud Provider region picked for you instance

 // (For CqlSession only)
 .clientId("TWRvjlcrgfZYfhcxGZhUlAAA")     // Will be used as your username
 .clientSecret("7xKSrZPLbWxDJ0WXyj..")     // Will be used as your password
 .keyspace("ks1")                          // (optional) Set your keyspace
 .secureConnectBundle("/tmp/sec.zip").     // (optional) if not provided download in ~/.astra
 .build();

c. Overview of parameters in the builder

Param Name Devops API REST.Document API CqlSession API
application Token required -- --
databaseId -- required required
database Cloud Region -- required required
client Id (part of token) optional -- required
client Secret (part of token) optional -- required
Keyspace -- -- optional
Secure Connect Bundle -- -- optional

Initialising the SDK with Local Stargate

Astra is not required to work with the SDK. A standalone installation of Stargate expose the Rest/Document/Graph Apis and the CqlSession.

a. Setup Stargate

Instead of a token you will use a user and a password and will authenticated against a dedicated authenticationUrl. Make sure to create a user at Cassandra level and enable RBAC

b. Sample Code

StargateClient client = StargateClient.builder()
  .username("k8ssandra-superuser")           // Mandatory username
  .password("JxzrPOnvDGqfEOQ0EySQ")          // Mandatory password
  .endPointAuth("http://localhost:8081")     // Mandatory authencation url, defaulting to http://localhost:8081
  .endPointRest("http://localhost:8082")     // Rest and Document Apis
  .endPointGraphQL("http://localhost:8080")  // GraphQL Api
  
  // Cqlsession Only
  .addCqlContactPoint("127.0.0.", 9042)      // Contact Point
  .localDc("dc1")                            // Local Datacenter is mandatory driver 4x+
  .keypace("ks1")                            // (optional) Set your keyspace
  .build();

c. Overview of parameters in the builder

Param Name REST.Document API GraphQL API CqlSession API
username required required required
password required required required
Authentication endpoint required required required
Rest Api endpoint required -- --
GraphQL Api endpoint -- required --
Contact Points -- -- required
Local DataCenter Name -- -- required
keyspace -- -- optional

Preview of REST API

// Fluent Api

// First level will be keyspacce
Stream<String> ksNames = stargate.apiRest().keyspaceNames();



SearchTableQuery query = SearchTableQuery.builder()
  .select("a","b")
  .where("c").isEqualsTo(1)
  .where("d").isGreaterOrEqualsThan(2)
  .sortBy(new SortField("d", Ordering.ASC))
  .withPageSize(10)
  .build();
RowResultPage page = stargate.apiRest().keyspace("ks1").table("tt").search(query);


ApiDocumentClient apiDocClient = astraClient.apiDocument();
String workingNamespace = "five_min_namespace";
String workingCollection = "person";

// DOC1. Create Namespace
if (!apiDocClient.namespace(workingNamespace).exist()) {
  // apiDocClient.namespace(workingNamespace).create();
  // We use the devops API with higher privileges
  astraClient.apiDevops().createNamespace(dbId, workingNamespace);
}

// DOC2. Create a collection
if (!apiDocClient.namespace(workingNamespace)
                 .collection(workingCollection)
                 .exist()) {
   apiDocClient.namespace(workingNamespace)
               .collection(workingCollection)
               .create();
}

/* 
 * Note that I can avoid keep repeating 
 * apiDocClient.namespace(workingNamespace)
 *             .collection(workingCollection)
 */
CollectionClient personCollect = 
   apiDocClient.namespace(workingNamespace)
               .collection(workingCollection);

// DOC3. Create a document Insert a Person and system generates id
String johnId = personCollect
               .save(new Person("John", "Doe", 20, new Address("Paris", 75000)));

// DOC4. Upsert a document by providing id
personCollect.document("saradoe")
             .save(new Person("Sara", "Doe", 20, new Address("Paris", 75000)));

// DOC5. Find all (notice that everything is paged)
ResultListPage<Person> results = personCollect
    .findAll(Person.class);

// DOC6. Search: Find with a where Clause
ResultListPage<Person> results = personCollect.search(QueryDocument.builder()
                .where("lastname").isEqualsTo("Doe").build(), Person.class);

// -------------------------------------------------------------
// Working with the Devops API
// -------------------------------------------------------------

ApiDevopsClient apiDevops = astraClient.apiDevops();
Stream<AstraDatabaseInfos> dbs = apiDevops.databases();
Optional<AstraDatabaseInfos > dbInfo = apiDevops.findDatabaseById(dbId);

// -------------------------------------------------------------
// Working with the Rest API (keyspace/table/record)
// -------------------------------------------------------------
ApiRestClient apiRest = astraClient.apiRest();

// -------------------------------------------------------------
// Working with the Cql API (CqlSession)
// -------------------------------------------------------------
ApiCqlClient apiCql = astraClient.apiCql();

Initializing Astra Client

Overview

Astra use the open source data gateway Stargate to expose REST, Document and GraphQL APIs, design is done to work with both. Depending on which API we want to use and if we use Astra or Stargate required parameters are not the same.

Parameters required in Astra for each API

Parameters required in Stargate for each API

Settings

Philosophy of the SDK is either to use AstraClientand fill the parameters you need to work with the API you need or instanciate the sub client you need.

Illustration to use either AstraClient facade or sub clients.

// Use AstraClient
AstraClient astraClient = AstraClient.builder()
                .astraDatabaseId(dbId)
                .astraDatabaseRegion(dbRegion)
                .username(dbUser)
                .password(dbPasswd)
                .build();
ApiDocumentClient apiDocClient1 = astraClient.apiDocument();

// Create subclient direct
ApiDocumentClient apiDocClient2 = 
  new ApiDocumentClient(dbId, dbRegion, dbUser, dbPasswd);

πŸ–₯️ Expected Output:

- Initializing Client: BaseUrl=https://e92195f2-159f-492e-9777-3dadda3ff1a3-europe-west1.apps.astra.datastax.com/api/rest, username=todouser,passwordLenght=13
- Successfully Authenticated, token will live for 300 second(s).

πŸ“˜ astraDatabaseId: It is the default identifier of a database hosted in Astra.

  • Used only when working with Astra
  • Mandatory to work with Doc, Rest or GraphQL APIS.
  • Environment Variable lookup for initial value ASTRA_DB_ID
  • Sample Use
AstraClient.builder().astraDatabaseId("1111111-1111-1111-1111-111111111111");
  • Property found on the summary page

πŸ“˜ astraDatabaseRegion: It is the default identifier of a database hosted in Astra

  • Used only when working with Astra
  • Mandatory to work with Doc, Rest or GraphQL APIS.
  • Environment Variable lookup for initial value ASTRA_DB_REGION
  • Sample Use
AstraClient.builder().astraDatabaseRegion("europe-west-1");
  • Property found on the summary page

πŸ“˜ baseUrl: It is the endpoint for Apis when working with Stargate

  • Used only when working with Stargate
  • Mandatory to work with Doc, Rest or GraphQL APIS.
  • Environment Variable lookup for initial value STARGATE_BASE_URL
  • Sample Use
AstraClient.builder().baseUrl("http://localhost:8082/api");
!If you provide `baseUrl` but also `astraDatabaseId` and 
!`astraDatabaseId` the client will use `baseUrl`.

πŸ“˜ username: It is the... username

  • Used both for Stargate and Astra
  • Mandatory to work with Doc, Rest or GraphQL APIS.
  • Environment Variable lookup for initial value STARGATE_USERNAME, then if not found, ASTRA_DB_USERNAME
  • Sample Use
AstraClient.builder().username("astraUser");

πŸ“˜ password: It is the... password

  • Used both for Stargate and Astra
  • Mandatory to work with Doc, Rest or GraphQL APIS.
  • Environment Variable lookup for initial value STARGATE_PASSWORD then, if not found, ASTRA_DB_PASSWORD
  • Sample Use
AstraClient.builder().password("astraPassword1");

πŸ“˜ clientId: is part of a service Account and stands as an unique identifier for the client.

  • Used only when working with Astra
  • Mandatory to work with Devops API.
  • Environment Variable lookup for initial value ASTRA_CLIENT_ID
  • Sample Use
AstraClient.builder().clientId("1111111-1111-1111-11111111111");
  • Property found on the Security Account page, use the ellipsis to copy the JSON.

Go to Security Account page using the drop down

Scroll and pick your credentials with the ellipsis


πŸ“˜ clientName: is part of a service Account and stands as client email.

  • Used only when working with Astra
  • Mandatory to work with Devops API.
  • Environment Variable lookup for initial value ASTRA_CLIENT_NAME
  • Sample Use
AstraClient.builder().clientName("[email protected]");

πŸ“˜ clientSecret: is part of a service Account and is used as a key to authenticate.

  • Used only when working with Astra
  • Mandatory to work with Devops API.
  • Environment Variable lookup for initial value ASTRA_CLIENT_SECRET
  • Sample Use
AstraClient.builder().clientSecret("1111111-1111-1111-11111111111");

πŸ“˜ contactPoints: is used to work with Drivers (cql API)

  • Used only when working with Stargate
  • Mandatory to work with Driver API.
  • Environment Variable lookup for initial value CONTACT_POINTS
  • Sample Use
AstraClient.builder().addContactPoint("127.0.0.1", 9042);

πŸ“˜ driverConfigFile: is used to work with Drivers (cql API)

  • Used both for Stargate and Astra
  • Mandatory to work with Driver API.
  • Environment Variable lookup for initial value DRIVER_CONFIG_FILE
  • Sample Use
AstraClient.builder().driverConfigFile("/tmp/application.conf");

πŸ“˜ secureConnectBundle: is used to work with Drivers (cql API). NOt that this file can be downloaded with the DevopsAPI.

  • Used only when working with Astra
  • Mandatory to work with Driver API.
  • Environment Variable lookup for initial value ASTRA_SECURE_BUNDLE
  • Sample Use
AstraClient.builder().secureConnectBundle("/tmp/mybundle.zip");

What's NEXT?

How do you want to connect?

Options Description
I don't want to create a schema. Just let me get started. Use schemaless JSON Documents with the Document API
I want to start using my database now with APIs. Use the REST API or GraphQL API to begin interacting with your database.
I have an application and want to use the DataStax drivers. Use the CQL API leveraging DataStax drivers to manage database connections for your application.
I want to operate Astra, work with my instances. Use the Devops API

For any choice you will see that you only need to setup the class AstraClient with a builder and you are good to go.