Step 2: Test connectivity to the ledger - Amazon Quantum Ledger Database (Amazon QLDB)

Step 2: Test connectivity to the ledger

In this step, you verify that you can connect to the vehicle-registration ledger in Amazon QLDB using the transactional data API endpoint.

To test connectivity to the ledger
  1. Review the following program (ConnectToLedger.java), which creates a data session connection to the vehicle-registration ledger.

    2.x
    /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import java.net.URI; import java.net.URISyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.services.qldbsession.QldbSessionClient; import software.amazon.awssdk.services.qldbsession.QldbSessionClientBuilder; import software.amazon.qldb.QldbDriver; import software.amazon.qldb.RetryPolicy; /** * Connect to a session for a given ledger using default settings. * <p> * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class ConnectToLedger { public static final Logger log = LoggerFactory.getLogger(ConnectToLedger.class); public static AwsCredentialsProvider credentialsProvider; public static String endpoint = null; public static String ledgerName = Constants.LEDGER_NAME; public static String region = null; public static QldbDriver driver; private ConnectToLedger() { } /** * Create a pooled driver for creating sessions. * * @param retryAttempts How many times the transaction will be retried in * case of a retryable issue happens like Optimistic Concurrency Control exception, * server side failures or network issues. * @return The pooled driver for creating sessions. */ public static QldbDriver createQldbDriver(int retryAttempts) { QldbSessionClientBuilder builder = getAmazonQldbSessionClientBuilder(); return QldbDriver.builder() .ledger(ledgerName) .transactionRetryPolicy(RetryPolicy .builder() .maxRetries(retryAttempts) .build()) .sessionClientBuilder(builder) .build(); } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static QldbDriver createQldbDriver() { QldbSessionClientBuilder builder = getAmazonQldbSessionClientBuilder(); return QldbDriver.builder() .ledger(ledgerName) .transactionRetryPolicy(RetryPolicy.builder() .maxRetries(Constants.RETRY_LIMIT).build()) .sessionClientBuilder(builder) .build(); } /** * Creates a QldbSession builder that is passed to the QldbDriver to connect to the Ledger. * * @return An instance of the AmazonQLDBSessionClientBuilder */ public static QldbSessionClientBuilder getAmazonQldbSessionClientBuilder() { QldbSessionClientBuilder builder = QldbSessionClient.builder(); if (null != endpoint && null != region) { try { builder.endpointOverride(new URI(endpoint)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } if (null != credentialsProvider) { builder.credentialsProvider(credentialsProvider); } return builder; } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static QldbDriver getDriver() { if (driver == null) { driver = createQldbDriver(); } return driver; } public static void main(final String... args) { Iterable<String> tables = ConnectToLedger.getDriver().getTableNames(); log.info("Existing tables in the ledger:"); for (String table : tables) { log.info("- {} ", table); } } }
    Note
    • To run data operations on your ledger, you must create an instance of the QldbDriver class to connect to a specific ledger. This is a different client object than the AmazonQLDB client that you used in the previous step to create the ledger. That previous client is only used to run the management API operations listed in the Amazon QLDB API reference.

    • First, create a QldbDriver object. You must specify a ledger name when you create this driver.

      Then, you can use this driver's execute method to run PartiQL statements.

    • Optionally, you can specify a maximum number of retry attempts for transaction exceptions. The execute method automatically retries optimistic concurrency control (OCC) conflicts and other common transient exceptions up to this configurable limit. The default value is 4.

      If the transaction still fails after the limit is reached, then the driver throws the exception. To learn more, see Understanding retry policy with the driver in Amazon QLDB.

    1.x
    /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package software.amazon.qldb.tutorial; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.qldbsession.AmazonQLDBSessionClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.qldb.PooledQldbDriver; import software.amazon.qldb.QldbDriver; import software.amazon.qldb.QldbSession; import software.amazon.qldb.exceptions.QldbClientException; /** * Connect to a session for a given ledger using default settings. * <p> * This code expects that you have AWS credentials setup per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ public final class ConnectToLedger { public static final Logger log = LoggerFactory.getLogger(ConnectToLedger.class); public static AWSCredentialsProvider credentialsProvider; public static String endpoint = null; public static String ledgerName = Constants.LEDGER_NAME; public static String region = null; private static PooledQldbDriver driver; private ConnectToLedger() { } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static PooledQldbDriver createQldbDriver() { AmazonQLDBSessionClientBuilder builder = AmazonQLDBSessionClientBuilder.standard(); if (null != endpoint && null != region) { builder.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region)); } if (null != credentialsProvider) { builder.setCredentials(credentialsProvider); } return PooledQldbDriver.builder() .withLedger(ledgerName) .withRetryLimit(Constants.RETRY_LIMIT) .withSessionClientBuilder(builder) .build(); } /** * Create a pooled driver for creating sessions. * * @return The pooled driver for creating sessions. */ public static PooledQldbDriver getDriver() { if (driver == null) { driver = createQldbDriver(); } return driver; } /** * Connect to a ledger through a {@link QldbDriver}. * * @return {@link QldbSession}. */ public static QldbSession createQldbSession() { return getDriver().getSession(); } public static void main(final String... args) { try (QldbSession qldbSession = createQldbSession()) { log.info("Listing table names "); for (String tableName : qldbSession.getTableNames()) { log.info(tableName); } } catch (QldbClientException e) { log.error("Unable to create session.", e); } } }
    Note
    • To run data operations on your ledger, you must create an instance of the PooledQldbDriver or QldbDriver class to connect to a specific ledger. This is a different client object than the AmazonQLDB client that you used in the previous step to create the ledger. That previous client is only used to run the management API operations listed in the Amazon QLDB API reference.

      We recommend using PooledQldbDriver unless you need to implement a custom session pool with QldbDriver. The default pool size for PooledQldbDriver is the maximum number of open HTTP connections that the session client allows.

    • First, create a PooledQldbDriver object. You must specify a ledger name when you create this driver.

      Then, you can use this driver's execute method to run PartiQL statements. Or, you can manually create a session from this pooled driver object and use the session's execute method. A session represents a single connection with the ledger.

    • Optionally, you can specify a maximum number of retry attempts for transaction exceptions. The execute method automatically retries optimistic concurrency control (OCC) conflicts and other common transient exceptions up to this configurable limit. The default value is 4.

      If the transaction still fails after the limit is reached, then the driver throws the exception. To learn more, see Understanding retry policy with the driver in Amazon QLDB.

  2. Compile and run the ConnectToLedger.java program to test your data session connectivity to the vehicle-registration ledger.

Overriding the AWS Region

The sample application connects to QLDB in your default AWS Region, which you can set as described in the prerequisite step Setting your default AWS credentials and Region. You can also change the Region by modifying the QLDB session client builder properties.

2.x

The following code example instantiates a new QldbSessionClientBuilder object.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.qldbsession.QldbSessionClientBuilder; // This client builder will default to US East (Ohio) QldbSessionClientBuilder builder = QldbSessionClient.builder() .region(Region.US_EAST_2);

You can use the region method to run your code against QLDB in any Region where it's available. For a complete list, see Amazon QLDB endpoints and quotas in the AWS General Reference.

1.x

The following code example instantiates a new AmazonQLDBSessionClientBuilder object.

import com.amazonaws.regions.Regions; import com.amazonaws.services.qldbsession.AmazonQLDBSessionClientBuilder; // This client builder will default to US East (Ohio) AmazonQLDBSessionClientBuilder builder = AmazonQLDBSessionClientBuilder.standard() .withRegion(Regions.US_EAST_2);

You can use the withRegion method to run your code against QLDB in any Region where it's available. For a complete list, see Amazon QLDB endpoints and quotas in the AWS General Reference.

To create tables in the vehicle-registration ledger, proceed to Step 3: Create tables, indexes, and sample data.