• Glossary
  • Support
  • Downloads
  • DataStax Home
Get Live Help
Expand All
Collapse All

DataStax Astra DB Serverless Documentation

    • Overview
      • Release notes
      • Astra DB FAQs
      • Astra DB glossary
      • Get support
    • Getting Started
      • Grant a user access
      • Load and retrieve data
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
      • Connect a driver
      • Build sample apps
      • Use integrations
        • Connect with DataGrip
        • Connect with DBSchema
        • Connect with JanusGraph
        • Connect with Strapi
    • Planning
      • Plan options
      • Database regions
    • Securing
      • Security highlights
      • Security guidelines
      • Default user permissions
      • Change your password
      • Reset your password
      • Authentication and Authorization
      • Astra DB Plugin for HashiCorp Vault
    • Connecting
      • Connecting private endpoints
        • AWS Private Link
        • Azure Private Link
        • GCP Private Endpoints
        • Connecting custom DNS
      • Connecting Change Data Capture (CDC)
      • Connecting CQL console
      • Connect the Spark Cassandra Connector to Astra
      • Drivers for Astra DB
        • Connecting C++ driver
        • Connecting C# driver
        • Connecting Java driver
        • Connecting Node.js driver
        • Connecting Python driver
        • Drivers retry policies
      • Connecting Legacy drivers
      • Get Secure Connect Bundle
    • Migrating
      • FAQs
      • Preliminary steps
        • Feasibility checks
        • Deployment and infrastructure considerations
        • Create target environment for migration
        • Understand rollback options
      • Phase 1: Deploy ZDM Proxy and connect client applications
        • Set up the ZDM Automation with ZDM Utility
        • Deploy the ZDM Proxy and monitoring
          • Configure Transport Layer Security
        • Connect client applications to ZDM Proxy
        • Manage your ZDM Proxy instances
      • Phase 2: Migrate and validate data
      • Phase 3: Enable asynchronous dual reads
      • Phase 4: Change read routing to Target
      • Phase 5: Connect client applications directly to Target
      • Troubleshooting
        • Troubleshooting tips
        • Troubleshooting scenarios
      • Additional resources
        • Glossary
        • Contribution guidelines
        • Release Notes
    • Managing
      • Managing your organization
        • User permissions
        • Pricing and billing
        • Audit Logs
        • Bring Your Own Key
          • BYOK AWS Astra DB console
          • BYOK GCP Astra DB console
          • BYOK AWS DevOps API
          • BYOK GCP DevOps API
        • Configuring SSO
          • Configure SSO for Microsoft Azure AD
          • Configure SSO for Okta
          • Configure SSO for OneLogin
      • Managing your database
        • Create your database
        • View your databases
        • Database statuses
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
        • Monitor your databases
        • Export metrics to third party
          • Export metrics via Astra Portal
          • Export metrics via DevOps API
        • Manage access lists
        • Manage multiple keyspaces
        • Using multiple regions
        • Terminate your database
      • Managing with DevOps API
        • Managing database lifecycle
        • Managing roles
        • Managing users
        • Managing tokens
        • Managing BYOK AWS
        • Managing BYOK GCP
        • Managing access list
        • Managing multiple regions
        • Get private endpoints
        • AWS PrivateLink
        • Azure PrivateLink
        • GCP Private Service
    • Astra CLI
    • DataStax Astra Block
      • FAQs
      • About NFTs
      • DataStax Astra Block for Ethereum quickstart
    • Developing with Stargate APIs
      • Develop with REST
      • Develop with Document
      • Develop with GraphQL
        • Develop with GraphQL (CQL-first)
        • Develop with GraphQL (Schema-first)
      • Develop with gRPC
        • gRPC Rust client
        • gRPC Go client
        • gRPC Node.js client
        • gRPC Java client
      • Develop with CQL
      • Tooling Resources
      • Node.js Document API client
      • Node.js REST API client
    • Stargate QuickStarts
      • Document API QuickStart
      • REST API QuickStart
      • GraphQL API CQL-first QuickStart
    • API References
      • DevOps REST API v2
      • Stargate Document API v2
      • Stargate REST API v2
  • DataStax Astra DB Serverless Documentation
  • Developing with Stargate APIs
  • Develop with gRPC
  • gRPC Java client

gRPC Java Client

gRPC Java client setup

Install software

You’ll need to install the following software if it is not already installed:

  • Install a Java Development Kit (JDK)

  • Install Apache Maven

Add dependencies

To begin, add the required dependency to your project pom.xml:

<dependencies>
  <dependency>
    <groupId>io.stargate.grpc</groupId>
    <artifactId>grpc-proto</artifactId>
    <version>1.0.41</version>
  </dependency>
  <dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty-shaded</artifactId>
    <version>1.41.0</version>
  </dependency>
</dependencies>

If you do not add it, you will observe the following error:

No functional channel service provider found.
Try adding a dependency on the grpc-okhttp, grpc-netty, or grpc-netty-shaded artifact.

Java connecting

Authentication

This example assumes that you’re running Stargate locally with the default credentials of cassandra/cassandra. For more information regarding authentication please see the Stargate authentication and authorization docs.

The following code snippet can be used to generate the table-based auth token in the client code:

// Stargate OSS configuration for locally hosted docker image
private static final String STARGATE_USERNAME      = "cassandra";
private static final String STARGATE_PASSWORD      = "cassandra";
private static final String STARGATE_HOST          = "localhost";
private static final int    STARGATE_GRPC_PORT     = 8090;
private static final String STARGATE_AUTH_ENDPOINT = "http://" + STARGATE_HOST+ ":8081/v1/auth";

// Authenticate to get a token (http client jdk11)
String token = getTokenFromAuthEndpoint(STARGATE_USERNAME, STARGATE_PASSWORD);

private static String getTokenFromAuthEndpoint(String username, String password) {
    try {
        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create(STARGATE_AUTH_ENDPOINT))
                .setHeader("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString("{"
                        + " \"username\": \"" + STARGATE_USERNAME+ "\",\n"
                        + " \"password\": \"" + STARGATE_PASSWORD + "\"\n"
                        + "}'"))
                .build();
        HttpResponse<String> response = HttpClient.newBuilder().build()
                .send(request, HttpResponse.BodyHandlers.ofString());
        return response.body().split(":")[1].replaceAll("\"", "").replaceAll("}", "");
    } catch(Exception e) {
        throw new IllegalArgumentException(e);
    }
}

Creating a client

To connect to your Stargate instance, create the client. For a local Stargate instance, for instance, the following client code will fetch an auth token with a REST call:

// Stargate OSS configuration for locally hosted docker image
private static final String STARGATE_USERNAME      = "cassandra";
private static final String STARGATE_PASSWORD      = "cassandra";
private static final String STARGATE_HOST          = "localhost";
private static final int    STARGATE_GRPC_PORT     = 8090;
private static final String STARGATE_AUTH_ENDPOINT = "http://" + STARGATE_HOST+ ":8081/v1/auth";

public static void main(String[] args)
throws Exception {

    // Create Grpc Channel
    ManagedChannel channel = ManagedChannelBuilder
            .forAddress(STARGATE_HOST, STARGATE_GRPC_PORT).usePlaintext().build();

    // blocking stub version
    StargateGrpc.StargateBlockingStub blockingStub =
        StargateGrpc.newBlockingStub(channel)
            .withDeadlineAfter(10, TimeUnit.SECONDS)
            .withCallCredentials(new StargateBearerToken(token));

Java querying

A simple query can be performed by passing a CQL query to the client using the ExecuteQuery() function for standard query execution:

QueryOuterClass.Response queryString = blockingStub.executeQuery(QueryOuterClass
        .Query.newBuilder()
        .setCql("SELECT firstname, lastname FROM test.users")
        .build());

Data definition (DDL) queries are supported in the same manner:

blockingStub.executeQuery(
        QueryOuterClass.Query.newBuilder()
            .setCql(""
                + "CREATE KEYSPACE IF NOT EXISTS test "
                + "WITH REPLICATION = {"
                + " 'class' : 'SimpleStrategy', "
                + " 'replication_factor' : 1"
                + "};")
            .build());
System.out.println("Keyspace 'test' has been created.");

blockingStub.executeQuery(
        QueryOuterClass.Query.newBuilder()
            .setCql("CREATE TABLE IF NOT EXISTS test.users (firstname text PRIMARY KEY, lastname text);")
            .build());
System.out.println("Table 'users' has been created.");

In general, users will create a keyspace and table first.

If you would like to use a batch statement, the client also provides an ExecuteBatch() function to execute a batch query:

blockingStub.executeBatch(
        QueryOuterClass.Batch.newBuilder()
            .addQueries(
                QueryOuterClass.BatchQuery.newBuilder()
                    .setCql("INSERT INTO test.users (firstname, lastname) VALUES('Jane', 'Doe')")
                    .build())
            .addQueries(
                QueryOuterClass.BatchQuery.newBuilder()
                    .setCql("INSERT INTO test.users (firstname, lastname) VALUES('Serge', 'Provencio')")
                    .build())
            .build());
System.out.println("2 rows have been inserted in table users.");

The ExecuteQuery function can be used to execute a single query.

This example inserts two values into the keyspace table test.users. Only INSERT, UPDATE, and DELETE operations can be used in a batch query.

Java gRPC processing result set

After executing a query, a response returns rows that match the SELECT statement. If there are no rows, the returned payload is unset. The convenience function getResultSet() is provided to help transform this response into a result set that’s easier to work with.

QueryOuterClass.ResultSet rs = queryString.getResultSet();

for (Row row : rs.getRowsList()) {
    System.out.println(""
            + "FirstName=" + row.getValues(0).getString() + ", "
            + "lastname=" + row.getValues(1).getString());
}

Since the result type is known, the getString function transforms the value into a native string. Additional functions also exist for other types such as int, map, and blob. The full list can be found in Values.java.

Java full sample script

To put all the pieces together, here is a sample script that combines all the pieces shown above:

  • Sample script

  • Result

package com.datastax.tutorial;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.stargate.grpc.StargateBearerToken;
import io.stargate.proto.QueryOuterClass;
import io.stargate.proto.QueryOuterClass.Row;
import io.stargate.proto.StargateGrpc;

public class ConnectStargate {

    // Stargate OSS configuration for locally hosted docker image
    private static final String STARGATE_USERNAME      = "cassandra";
    private static final String STARGATE_PASSWORD      = "cassandra";
    private static final String STARGATE_HOST          = "localhost";
    private static final int    STARGATE_GRPC_PORT     = 8090;
    private static final String STARGATE_AUTH_ENDPOINT = "http://" + STARGATE_HOST+ ":8081/v1/auth";

    public static void main(String[] args)
    throws Exception {

        //-------------------------------------
        // 1. Initializing Connectivity
        //-------------------------------------

        // Authenticate to get a token (http client jdk11)
        String token = getTokenFromAuthEndpoint(STARGATE_USERNAME, STARGATE_PASSWORD);

        // Create Grpc Channel
        ManagedChannel channel = ManagedChannelBuilder
                .forAddress(STARGATE_HOST, STARGATE_GRPC_PORT).usePlaintext().build();

        // blocking stub version
        StargateGrpc.StargateBlockingStub blockingStub =
            StargateGrpc.newBlockingStub(channel)
                .withDeadlineAfter(10, TimeUnit.SECONDS)
                .withCallCredentials(new StargateBearerToken(token));

        //-------------------------------------
        // 2. Create Schema
        //-------------------------------------

        blockingStub.executeQuery(
                QueryOuterClass.Query.newBuilder()
                    .setCql(""
                        + "CREATE KEYSPACE IF NOT EXISTS test "
                        + "WITH REPLICATION = {"
                        + " 'class' : 'SimpleStrategy', "
                        + " 'replication_factor' : 1"
                        + "};")
                    .build());
        System.out.println("Keyspace 'test' has been created.");

        blockingStub.executeQuery(
                QueryOuterClass.Query.newBuilder()
                    .setCql("CREATE TABLE IF NOT EXISTS test.users (firstname text PRIMARY KEY, lastname text);")
                    .build());
        System.out.println("Table 'users' has been created.");

        //-------------------------------------
        // 3. Insert 2 rows with Batch
        //-------------------------------------

        blockingStub.executeBatch(
                QueryOuterClass.Batch.newBuilder()
                    .addQueries(
                        QueryOuterClass.BatchQuery.newBuilder()
                            .setCql("INSERT INTO test.users (firstname, lastname) VALUES('Jane', 'Doe')")
                            .build())
                    .addQueries(
                        QueryOuterClass.BatchQuery.newBuilder()
                            .setCql("INSERT INTO test.users (firstname, lastname) VALUES('Serge', 'Provencio')")
                            .build())
                    .build());
        System.out.println("2 rows have been inserted in table users.");

        //-------------------------------------
        // 4. Retrieving result.
        //-------------------------------------

        QueryOuterClass.Response queryString = blockingStub.executeQuery(QueryOuterClass
                .Query.newBuilder()
                .setCql("SELECT firstname, lastname FROM test.users")
                .build());
        QueryOuterClass.ResultSet rs = queryString.getResultSet();
        for (Row row : rs.getRowsList()) {
            System.out.println(""
                    + "FirstName=" + row.getValues(0).getString() + ", "
                    + "lastname=" + row.getValues(1).getString());
        }

        System.out.println("Everything worked!");
        System.exit(0);
    }

    private static String getTokenFromAuthEndpoint(String username, String password) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .GET()
                    .uri(URI.create(STARGATE_AUTH_ENDPOINT))
                    .setHeader("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString("{"
                            + " \"username\": \"" + STARGATE_USERNAME+ "\",\n"
                            + " \"password\": \"" + STARGATE_PASSWORD + "\"\n"
                            + "}'"))
                    .build();
            HttpResponse<String> response = HttpClient.newBuilder().build()
                    .send(request, HttpResponse.BodyHandlers.ofString());
            return response.body().split(":")[1].replaceAll("\"", "").replaceAll("}", "");
        } catch(Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

}
Keyspace 'test' has been created.
Table 'users' has been created.
2 rows have been inserted in table users.
FirstName=Serge, lastname=Provencio
FirstName=Jane, lastname=Doe
Everything worked!

Java developing

Generating gRPC code stubs

To see a guide how the Java code is compiled from the proto files see the gRPC setup project dependencies. To update the protobuf files being used, add the new files to the top level proto directory and then run make proto from the root of the project.

More notes on the asynchronous use of the gRPC API

Up to this point, we were using the blocking version of the generated stub. We can also interact with the Stargate API using the async version of the stub. To do so, we need to pass the StreamObserver that will be called asynchronously when the results are available.

Every StreamObserver needs to implement 3 methods: onNext(), onError() and onComplete(). For example:

StreamObserver<QueryOuterClass.Response> streamObserver = new StreamObserver<QueryOuterClass.Response>() {
           @Override
           public void onNext(QueryOuterClass.Response response) {
               try {
                   System.out.println("response:" + response.getResultSet());
               } catch (InvalidProtocolBufferException e) {
                   throw new RuntimeException(e);
               }
           }
           @Override
           public void onError(Throwable throwable) {
               System.out.println("Error: " + throwable);
           }
           @Override
           public void onCompleted() {
               // close resources, finish processing
               System.out.println("completed");
           }
       };

Please note that this is a very simplified version only for demonstration purposes and should not be used on production.

Once we have the Observer, we can pass it to the executeQuery method on the async stub:

stub.executeQuery(QueryOuterClass.Query
  .newBuilder()
  .setCql("SELECT k, v FROM ks.test")
  .build(), streamObserver);

This query will return immediately because it is non-blocking. If your program (or test) is progressing to the end, you may not be able to see the results. Your program may exit before the data arrives. After some time, when the data arrives, the streamObserver will be called.

The output of our program will look like this:

response:columns {
  type {
    basic: VARCHAR
  }
  name: "k"
}
columns {
  type {
    basic: INT
  }
  name: "v"
}
rows {
  values {
    string: "a"
  }
  values {
    int: 1
  }
}

completed

Please note, that at the end we have a completed emitted. This is called by the onCompleted method.

The Stargate gRPC Java Client repository is located at https://github.com/stargate/stargate-grpc-java-client.

gRPC Node.js client Develop with CQL

General Inquiries: +1 (650) 389-6000 info@datastax.com

© DataStax | Privacy policy | Terms of use

DataStax, Titan, and TitanDB are registered trademarks of DataStax, Inc. and its subsidiaries in the United States and/or other countries.

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries.

Kubernetes is the registered trademark of the Linux Foundation.

landing_page landingpage