

# Get a Secrets Manager secret value using Java
<a name="retrieving-secrets-java"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

To connect to a database using the credentials in a secret, you can use the Secrets Manager SQL Connection drivers, which wrap the base JDBC driver. This also uses client-side caching, so it can reduce the cost for calling Secrets Manager APIs.

**Topics**
+ [

# Get a Secrets Manager secret value using Java with client-side caching
](retrieving-secrets_cache-java.md)
+ [

# Connect to a SQL database using JDBC with credentials in an AWS Secrets Manager secret
](retrieving-secrets_jdbc.md)
+ [

# Get a Secrets Manager secret value using the Java AWS SDK
](retrieving-secrets-java-sdk.md)

# Get a Secrets Manager secret value using Java with client-side caching
<a name="retrieving-secrets_cache-java"></a>

When you retrieve a secret, you can use the Secrets Manager Java-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is Least Recently Used (LRU), so when the cache must discard a secret, it discards the least recently used secret. By default, the cache refreshes secrets every hour. You can configure [how often the secret is refreshed](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md#retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getCacheItemTTL) in the cache, and you can [hook into the secret retrieval](retrieving-secrets_cache-java-ref_SecretCacheHook.md) to add more functionality.

The cache does not force garbage collection once cache references are freed. The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the interfaces and abstract methods provided.

To use the component, you must have the following: 
+ A Java 8 or higher development environment. See [Java SE Downloads](https://www.oracle.com/technetwork/java/javase/downloads/index.html) on the Oracle website.

To download the source code, see [Secrets Manager Java-based caching client component](https://github.com/aws/aws-secretsmanager-caching-java) on GitHub.

To add the component to your project, in your Maven pom.xml file, include the following dependency. For more information about Maven, see the [Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) on the Apache Maven Project website.

```
<dependency>
  <groupId>com.amazonaws.secretsmanager</groupId>
  <artifactId>aws-secretsmanager-caching-java</artifactId>
  <version>1.0.2</version>
</dependency>
```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [

# SecretCache
](retrieving-secrets_cache-java-ref_SecretCache.md)
+ [

# SecretCacheConfiguration
](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md)
+ [

# SecretCacheHook
](retrieving-secrets_cache-java-ref_SecretCacheHook.md)

**Example Retrieve a secret**  
The following code example shows a Lambda function that retrieves a secret string. It follows the [best practice](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html) of instantiating the cache outside of the function handler, so it doesn't keep calling the API if you call the Lambda function again.  

```
package com.amazonaws.secretsmanager.caching.examples;
    
    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.RequestHandler;
    import com.amazonaws.services.lambda.runtime.LambdaLogger;
    
    import com.amazonaws.secretsmanager.caching.SecretCache;
    
    public class SampleClass implements RequestHandler<String, String> {
    
         private final SecretCache cache  = new SecretCache();
    
         @Override public String handleRequest(String secretId,  Context context) {
             final String secret  = cache.getSecretString(secretId);
    
            // Use the secret, return success;
    
        }
    }
```

# SecretCache
<a name="retrieving-secrets_cache-java-ref_SecretCache"></a>

An in-memory cache for secrets requested from Secrets Manager. You use [getSecretString](#retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretString) or [getSecretBinary](#retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretBinary) to retrieve a secret from the cache. You can configure the cache settings by passing in a [SecretCacheConfiguration](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md) object in the constructor. 

For more information, including examples, see [Get a Secrets Manager secret value using Java with client-side caching](retrieving-secrets_cache-java.md).

## Constructors
<a name="retrieving-secrets_cache-java-ref_SecretCache-constructors"></a>

`public SecretCache()`  
Default constructor for a `SecretCache` object.

`public SecretCache(AWSSecretsManagerClientBuilder builder)`  
Constructs a new cache using a Secrets Manager client created using the provided [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClientBuilder.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClientBuilder.html). Use this constructor to customize the Secrets Manager client, for example to use a specific Region or endpoint.

`public SecretCache(AWSSecretsManager client)`  
Constructs a new secret cache using the provided [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). Use this constructor to customize the Secrets Manager client, for example to use a specific Region or endpoint.

`public SecretCache(SecretCacheConfiguration config)`  
Constructs a new secret cache using the provided `SecretCacheConfiguration`.

## Methods
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods"></a>

### getSecretString
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretString"></a>

`public String getSecretString(final String secretId)`

Retrieves a string secret from Secrets Manager. Returns a [https://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true).

### getSecretBinary
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretBinary"></a>

`public ByteBuffer getSecretBinary(final String secretId)`

Retrieves a binary secret from Secrets Manager. Returns a [https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html).

### refreshNow
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-refreshNow"></a>

`public boolean refreshNow(final String secretId) throws InterruptedException`

Forces the cache to refresh. Returns `true` if the refresh completed without error, otherwise `false`.

### close
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-close"></a>

`public void close()`

Closes the cache.

# SecretCacheConfiguration
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration"></a>

Cache configuration options for a [SecretCache](retrieving-secrets_cache-java-ref_SecretCache.md), such as max cache size and Time to Live (TTL) for cached secrets.

## Constructor
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_constructor"></a>

`public SecretCacheConfiguration`

Default constructor for a `SecretCacheConfiguration` object.

## Methods
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods"></a>

### getClient
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getClient"></a>

`public AWSSecretsManager getClient()`

Returns the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html) that the cache retrieves secrets from.

### setClient
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setClient"></a>

`public void setClient(AWSSecretsManager client)`

Sets the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html) client that the cache retrieves secrets from.

### getCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getCacheHook"></a>

`public SecretCacheHook getCacheHook()`

Returns the [SecretCacheHook](retrieving-secrets_cache-java-ref_SecretCacheHook.md) interface used to hook cache updates.

### setCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setCacheHook"></a>

`public void setCacheHook(SecretCacheHook cacheHook)`

Sets the [SecretCacheHook](retrieving-secrets_cache-java-ref_SecretCacheHook.md) interface used to hook cache updates.

### getMaxCacheSize
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getMaxCacheSize"></a>

`public int getMaxCacheSize()`

Returns the maximum cache size. The default is 1024 secrets.

### setMaxCacheSize
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setMaxCacheSize"></a>

`public void setMaxCacheSize(int maxCacheSize)`

Sets the maximum cache size. The default is 1024 secrets.

### getCacheItemTTL
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getCacheItemTTL"></a>

`public long getCacheItemTTL()`

Returns the TTL in milliseconds for the cached items. When a cached secret exceeds this TTL, the cache retrieves a new copy of the secret from the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). The default is 1 hour in milliseconds. 

The cache refreshes the secret synchronously when the secret is requested after the TTL. If the synchronous refresh fails, the cache returns the stale secret. 

### setCacheItemTTL
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setCacheItemTTL"></a>

`public void setCacheItemTTL(long cacheItemTTL)`

Sets the TTL in milliseconds for the cached items. When a cached secret exceeds this TTL, the cache retrieves a new copy of the secret from the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). The default is 1 hour in milliseconds.

### getVersionStage
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getVersionStage"></a>

`public String getVersionStage()`

Returns the version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is` "AWSCURRENT"`.

### setVersionStage
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setVersionStage"></a>

`public void setVersionStage(String versionStage)`

Sets the version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is `"AWSCURRENT"`.

### SecretCacheConfiguration withClient
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withClient"></a>

`public SecretCacheConfiguration withClient(AWSSecretsManager client)`

Sets the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html) to retrieve secrets from. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withCacheHook"></a>

`public SecretCacheConfiguration withCacheHook(SecretCacheHook cacheHook)`

Sets the interface used to hook the in-memory cache. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withMaxCacheSize
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withMaxCacheSize"></a>

`public SecretCacheConfiguration withMaxCacheSize(int maxCacheSize)`

Sets the maximum cache size. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withCacheItemTTL
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withCacheItemTTL"></a>

`public SecretCacheConfiguration withCacheItemTTL(long cacheItemTTL)`

Sets the TTL in milliseconds for the cached items. When a cached secret exceeds this TTL, the cache retrieves a new copy of the secret from the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). The default is 1 hour in milliseconds. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withVersionStage
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withVersionStage"></a>

`public SecretCacheConfiguration withVersionStage(String versionStage)`

Sets the version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). Returns the updated `SecretCacheConfiguration` object with the new setting.

# SecretCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheHook"></a>

An interface to hook into a [SecretCache](retrieving-secrets_cache-java-ref_SecretCache.md) to perform actions on the secrets being stored in the cache. 

## put
<a name="retrieving-secrets_cache-java-ref_SecretCacheHook-put"></a>

`Object put(final Object o)`

Prepare the object for storing in the cache.

Returns the object to store in the cache.

## get
<a name="retrieving-secrets_cache-java-ref_SecretCacheHook-get"></a>

`Object get(final Object cachedObject)`

Derive the object from the cached object.

Returns the object to return from the cache

# Connect to a SQL database using JDBC with credentials in an AWS Secrets Manager secret
<a name="retrieving-secrets_jdbc"></a>

In Java applications, you can use the Secrets Manager SQL Connection drivers to connect to MySQL, PostgreSQL, Oracle, MSSQLServer, Db2, and Redshift databases using credentials stored in Secrets Manager. Each driver wraps the base JDBC driver, so you can use JDBC calls to access your database. However, instead of passing a username and password for the connection, you provide the ID of a secret. The driver calls Secrets Manager to retrieve the secret value, and then uses the credentials in the secret to connect to the database. The driver also caches the credentials using the [Java client-side caching library](retrieving-secrets_cache-java.md), so future connections don't require a call to Secrets Manager. By default, the cache refreshes every hour and also when the secret is rotated. To configure the cache, see [SecretCacheConfiguration](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md).

You can download the source code from [GitHub](https://github.com/aws/aws-secretsmanager-jdbc ).

To use the Secrets Manager SQL Connection drivers:
+ Your application must be in Java 8 or higher.
+ Your secret must be one of the following:
  + A [database secret in the expected JSON structure](reference_secret_json_structure.md). To check the format, in the Secrets Manager console, view your secret and choose **Retrieve secret value**. Alternatively, in the AWS CLI, call [get-secret-value](https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/get-secret-value.html).
  + An Amazon RDS [managed secret](integrating_how-services-use-secrets_RDS.md). For this type of secret, you must specify an endpoint and port when you establish the connection.
  + An Amazon Redshift [managed secret](integrating_how-services-use-secrets_RS.md). For this type of secret, you must specify an endpoint and port when you establish the connection.

If your database is replicated to other Regions, to connect to a replica database in another Region, you specify the regional endpoint and port when you create the connection. You can store regional connection information in the secret as extra key/value pairs, in SSM Parameter Store parameters, or in your code configuration. 

To add the driver to your project, in your Maven build file `pom.xml`, add the following dependency for the driver. For more information, see [Secrets Manager SQL Connection Library](https://search.maven.org/artifact/com.amazonaws.secretsmanager/aws-secretsmanager-jdbc) on the Maven Central Repository website.

```
<dependency>
    <groupId>com.amazonaws.secretsmanager</groupId>
    <artifactId>aws-secretsmanager-jdbc</artifactId>
    <version>1.0.12</version>
</dependency>
```

The driver uses the [https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). If you run the driver on Amazon EKS, it might pick up the credentials of the node it is running on instead of the service account role. To address this, add version 1 of `com.amazonaws:aws-java-sdk-sts` to your Gradle or Maven project file as a dependency.

To set an AWS PrivateLink DNS endpoint URL and a region in the `secretsmanager.properties` file:

```
drivers.vpcEndpointUrl = endpoint URL
drivers.vpcEndpointRegion = endpoint region
```

To override the primary region, set the `AWS_SECRET_JDBC_REGION` environment variable or make the following change to the `secretsmanager.properties` file:

```
drivers.region = region
```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [

## Establish a connection to a database
](#retrieving-secrets_jdbc_example)
+ [

## Establish a connection by specifying the endpoint and port
](#retrieving-secrets_jdbc_example_replica)
+ [

## Use c3p0 connection pooling to establish a connection
](#retrieving-secrets_jdbc_example_c3po)
+ [

## Use c3p0 connection pooling to establish a connection by specifying the endpoint and port
](#retrieving-secrets_jdbc_example_c3p0_replica)

## Establish a connection to a database
<a name="retrieving-secrets_jdbc_example"></a>

The following example shows how to establish a connection to a database using the credentials and connection information in a secret. Once you have the connection, you can use JDBC calls to access the database. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

------
#### [ MySQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ PostgreSQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Oracle ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ MSSQLServer ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Db2 ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Redshift ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------

## Establish a connection by specifying the endpoint and port
<a name="retrieving-secrets_jdbc_example_replica"></a>

The following example shows how to establish a connection to a database using the credentials in a secret with an endpoint and port that you specify. 

[Amazon RDS managed secrets](integrating_how-services-use-secrets_RDS.md) don't include the endpoint and port of the database. To connect to a database using master credentials in a secret that's managed by Amazon RDS, you specify them in your code. 

[Secrets that are replicated to other Regions](replicate-secrets.md) can improve latency for the connection to the regional database, but they do not contain different connection information from the source secret. Each replica is a copy of the source secret. To store regional connection information in the secret, add more key/value pairs for the endpoint and port information for the Regions. 

Once you have the connection, you can use JDBC calls to access the database. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

------
#### [ MySQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:mysql://example.com:3306";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ PostgreSQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:postgresql://example.com:5432/database";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Oracle ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:oracle:thin:@example.com:1521/ORCL";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ MSSQLServer ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:sqlserver://example.com:1433";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Db2 ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.com.rproxy.goskope.com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:db2://example.com:50000";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Redshift ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.com.rproxy.goskope.com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:redshift://example.com:5439";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------

## Use c3p0 connection pooling to establish a connection
<a name="retrieving-secrets_jdbc_example_c3po"></a>

The following example shows how to establish a connection pool with a `c3p0.properties` file that uses the driver to retrieve credentials and connection information from the secret. For `user` and `jdbcUrl`, enter the secret ID to configure the connection pool. Then you can retrieve connections from the pool and use them as any other database connections. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

For more information about c3p0, see [c3p0](https://www.mchange.com/projects/c3p0/) on the Machinery For Change website. 

------
#### [ MySQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver
c3p0.jdbcUrl=secretId
```

------
#### [ PostgreSQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver
c3p0.jdbcUrl=secretId
```

------
#### [ Oracle ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver
c3p0.jdbcUrl=secretId
```

------
#### [ MSSQLServer ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver
c3p0.jdbcUrl=secretId
```

------
#### [ Db2 ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver
c3p0.jdbcUrl=secretId
```

------
#### [ Redshift ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver
c3p0.jdbcUrl=secretId
```

------

## Use c3p0 connection pooling to establish a connection by specifying the endpoint and port
<a name="retrieving-secrets_jdbc_example_c3p0_replica"></a>

The following example shows how to establish a connection pool with a `c3p0.properties` file that uses the driver to retrieve credentials in a secret with an endpoint and port that you specify. Then you can retrieve connections from the pool and use them as any other database connections. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

[Amazon RDS managed secrets](integrating_how-services-use-secrets_RDS.md) don't include the endpoint and port of the database. To connect to a database using master credentials in a secret that's managed by Amazon RDS, you specify them in your code. 

[Secrets that are replicated to other Regions](replicate-secrets.md) can improve latency for the connection to the regional database, but they do not contain different connection information from the source secret. Each replica is a copy of the source secret. To store regional connection information in the secret, add more key/value pairs for the endpoint and port information for the Regions. 

------
#### [ MySQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver
c3p0.jdbcUrl=jdbc-secretsmanager:mysql://example.com:3306
```

------
#### [ PostgreSQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver
c3p0.jdbcUrl=jdbc-secretsmanager:postgresql://example.com:5432/database
```

------
#### [ Oracle ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver
c3p0.jdbcUrl=jdbc-secretsmanager:oracle:thin:@example.com:1521/ORCL
```

------
#### [ MSSQLServer ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver
c3p0.jdbcUrl=jdbc-secretsmanager:sqlserver://example.com:1433
```

------
#### [ Db2 ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver
c3p0.jdbcUrl=jdbc-secretsmanager:db2://example.com:50000
```

------
#### [ Redshift ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver
c3p0.jdbcUrl=jdbc-secretsmanager:redshift://example.com:5439
```

------

# Get a Secrets Manager secret value using the Java AWS SDK
<a name="retrieving-secrets-java-sdk"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.
+ If you store database credentials in the secret, use the [Secrets Manager SQL connection drivers](retrieving-secrets_jdbc.md) to connect to a database using the credentials in the secret. 
+ For other types of secrets, use the [Secrets Manager Java-based caching component](retrieving-secrets_cache-java.md) or call the SDK directly with [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/GetSecretValueResult.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/GetSecretValueResult.html) or [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/BatchGetSecretValueResult.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/BatchGetSecretValueResult.html).

The following code examples show how to use `GetSecretValue`.

**Required permissions: **`secretsmanager:GetSecretValue`

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * We recommend that you cache your secret values by using client-side caching.
 *
 * Caching secrets improves speed and reduces your costs. For more information,
 * see the following documentation topic:
 *
 * https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html
 */
public class GetSecretValue {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <secretName>\s

                Where:
                    secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String secretName = args[0];
        Region region = Region.US_EAST_1;
        SecretsManagerClient secretsClient = SecretsManagerClient.builder()
                .region(region)
                .build();

        getValue(secretsClient, secretName);
        secretsClient.close();
    }

    public static void getValue(SecretsManagerClient secretsClient, String secretName) {
        try {
            GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                    .secretId(secretName)
                    .build();

            GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
            String secret = valueResponse.secretString();
            System.out.println(secret);

        } catch (SecretsManagerException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```