> ## Documentation Index
> Fetch the complete documentation index at: https://support.locker.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Usages

> Guide to using the Locker Secrets Manager SDK for Java

## Configure Access Keys

The SDK needs to be configured with your access key id and your secret access key, which is available in your Locker Secrets Dashboard. These keys must not be disclosed. If you reveal these keys, you need to revoke them immediately. Environment variables are a good solution and they are easy to consume in most programming languages.

### Set up credentials on Linux/MacOS

```bash theme={null}
export ACCESS_KEY_ID=<YOUR_ACCESS_KEY_ID>
export SECRET_ACCESS_KEY=<YOUR_SECRET_ACCESS_KEY>
```

### Set up credentials on Windows

**PowerShell**

```powershell theme={null}
$Env:ACCESS_KEY_ID = '<YOUR_ACCESS_KEY_ID>'
$Env:SECRET_ACCESS_KEY = '<SECRET_ACCESS_KEY>'
```

**Command Prompt**

```bash theme={null}
set ACCESS_KEY_ID=<YOUR_ACCESS_KEY_ID>
set SECRET_ACCESS_KEY=<YOUR_SECRET_ACCESS_KEY>
```

You also need to set `api_base` value (default is `https://api.locker.io/locker_secrets`). If you need to set your custom headers, you also need to set `headers` value in the `options` param:

Now, you can use SDK to get or set values:

```java theme={null}
Map<String, String> headers = new HashMap<String, String>() {
    {
        put("CF-Access-Client-Id", "YOUR_CF_ACCESS_CLIENT_ID");
        put("CF-Access-Client-Secret", "YOUR_CF_ACCESS_CLIENT_SECRET");
    }
};
LockerResponseGetterOptions responseGetter = new LockerClient.LockerClientBuilder()
        .setApiBase("YOUR_API_BASE")
        .setHeaders(headers)
        .buildOptions();
LockerClient client = new LockerClient(new LiveLockerResponseGetter(responseGetter));
```

You can also pass parameters or use the shared credential file ( `~/.locker/credentials` ), but we do not recommend these ways.

```java theme={null}
import locker.LockerClient;
import locker.exception.LockerError;
import locker.model.Secret;
import locker.param.secret.SecretRetrieveParams;

public class LockerExample {
    public static void main(String[] args) {
        LockerClient client = new LockerClient("YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET");
        try {
            Secret secret = client.secrets().retrieve("YOUR_SECRET_KEY", Secret.class);
            System.out.println(secret);
        } catch (LockerError e) {
            e.printStackTrace();
        }
    }
}
```

***

## List Secrets

Use `.list()` method to list all secrets in project

```java theme={null}
String secrets = client.secrets().list(String.class);

/**
 *  return a list of secrets
 * */

Class<? super LockerCollection<Secret>> type = new TypeToken<LockerCollection<Secret>>() {
}.getRawType();
LockerCollection<Secret> secretList = (LockerCollection<Secret>) client.secrets().list(type);
```

***

## Get Secret Values

### Get a secret by key

This function will get the secret value by a key.

```java theme={null}
// Get a secret by secret key
Secret secret = client.secrets().retrieve("java_key_1", Secret.class);
String secretValue = client.secrets().retrieve("java_key_1", String.class);
```

### Get a secret by key and environment name

You could get a secret value by a secret key and specific environment name

```java theme={null}
// Get a secret by secret key and specific environment name
Secret secret = client.secrets().retrieve("java_key_1", Secret.class, "env_name");
String secretValue = client.secrets().retrieve("java_key_1", String.class, "env_name");
```

***

## Create Secrets

Use the `.create()` function to create a new secret:

```java theme={null}
SecretCreateParams createParams = new SecretCreateParams.Builder()
        .setKey("key")
        .setValue("value")
        .setDescription("description")
        .build();
Secret newSecret = client.secrets().create(createParams, Secret.class);
```

Create a new secret with a specific environment:

```java theme={null}
SecretCreateParams createParams = new SecretCreateParams.Builder()
        .setKey("key")
        .setValue("value")
        .setDescription("description")
        .setEnvironment("environment")
        .build();
Secret newSecret = client.secrets().create(createParams, Secret.class);
```

***

## Update Secrets

```java theme={null}
SecretUpdateParams updateParams = new SecretUpdateParams.Builder()
        .setKey("your_update_secret_key")
        .setValue("your_update_secret_value")
        .setDescription("your_update_secret_description")
        .build();

// Update a secret by secret key
Secret updatedSecret = client.secrets().modify("your_secret_key", updateParams, Secret.class);

// Update a secret by secret key and specific environment name
Secret updatedSecret = client.secrets().modify("your_secret_key", updateParams, Secret.class, "your_secret_env_name");
```

***

## List Environments

Use the `.list()` function to retrieve all environments in your project:

```java theme={null}
Class<? super LockerCollection<Environment>> type = new TypeToken<LockerCollection<Environment>>() {
}.getRawType();
LockerCollection<Environment> listEnvs = (LockerCollection<Environment>) client.environments().list(type);

// Or retrieve as a JSON string
String envs = client.environments().list(String.class);
```

***

## Retrieve an Environment

To retrieve an environment by name, use `.retrieve()`:

```java theme={null}
Environment environment = client.environments().retrieve("your_env_name", Environment.class);
```

***

## Create an Environment

To create a new environment, use `.create()`:

```java theme={null}
EnvironmentCreateParams createEnvParams = EnvironmentCreateParams.builder()
        .setName("your_env_name")
        .setExternalUrl("your_env_external_url")
        .setDescription("your_env_description")
        .build();
Environment newEnv = client.environments().create(createEnvParams, Environment.class);
```

***

## Update an Environment

```java theme={null}
EnvironmentUpdateParams params = EnvironmentUpdateParams.builder()
        .setName("your_update_env_name")
        .setExternalUrl("your_update_env_external_url")
        .setDescription("your_update_env_description")
        .build();
Environment updatedEnv = client.environments().modify("your_env_name", params, Environment.class);
```

***

## Error Handling

Locker Secret SDK offers some kinds of errors. They can reflect external events, like invalid credentials, network
interruptions, or code problems, like invalid API calls.

If an immediate problem prevents a function from continuing, the SDK raises an exception. It’s a best practice to catch
and handle exceptions. To catch an exception, use Java’s `try/catch` syntax. Catch `LockerError` or its
subclasses to handle Locker-specific exceptions only. Each subclass represents a different kind of exception. When you
catch an exception, you can use its class to choose a response.

Example:

```java theme={null}
LockerClient client = new LockerClient(
    "95443edf-eb33-4fae-a66d-c264d14e7217",
    "C+NCA5fwzJeCh3R4O3Dw4YLAbJrrvgJt1bJSe1BEhrY="
);
SecretCreateParams params = SecretCreateParams.builder()
    .setValue("your_secret_value")
    .setKey("your_secret_key")
    .setDescription("your_secret_description")
    .build();
try {
    Secret newSecret = client.secrets().create(params, Secret.class);
} catch (LockerError e) {
    e.printStackTrace();
}
```

In the SDK, error objects belong to `LockerError` and its subclasses. Use the documentation for each class for advice about how to respond.

| **Name**                | **Class**                            | **Description**                                                                                                                   |
| ----------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| Authentication Error    | `locker.error.AuthenticationError`   | Invalid `access_client_id` or invalid `secret_access_key`                                                                         |
| Permission Denied Error | `locker.error.PermissionDeniedError` | Your credential does not have enough permission to execute this operation                                                         |
| RateLimit Error         | `locker.error.RateLimitError`        | Too many requests                                                                                                                 |
| API Error               | `locker.error.APIError`              | You made an API call with the wrong parameters, in the wrong state, or in an invalid way, or something went wrong on Locker's end |
| CLI Run Error           | `locker.error.CliRunError`           | The encryption/decryption binary runs errors by invalid local data, process interruptions, or invalid `secret_access_key`         |

***

## Logging

The library can be configured to emit logging that will give you better insight into what it's doing. There are some levels: `debug`, `info`, `warning`, `error`.

The `info` logging level is usually most appropriate for production use, but `debug` is also available for more verbosity.

There are a few options for enabling it:

1. Set the environment variable `LOCKER_LOG` to the value `debug`, `info`, `warning` or `error`

```bash theme={null}
$ export LOCKER_LOG=debug
```

2. Set `log` when initializing the Locker object

```python theme={null}
from locker import Locker

locker = Locker(log="debug")
```

3. Enable it through Python's logging module:

```python theme={null}
import logging
logging.basicConfig()
logging.getLogger('locker').setLevel(logging.DEBUG)
```
