Skip to content

Commit

Permalink
chore: add examples for batch utils and rename auth token to API key (#…
Browse files Browse the repository at this point in the history
…325)

* chore: add examples for batch utils and rename auth token to API key
  • Loading branch information
pratik151192 authored Nov 29, 2023
1 parent 16dfda7 commit 4522e96
Show file tree
Hide file tree
Showing 16 changed files with 183 additions and 40 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ jobs:
build-examples:
runs-on: ubuntu-latest
env:
MOMENTO_AUTH_TOKEN: ${{ secrets.ALPHA_TEST_AUTH_TOKEN }}
MOMENTO_API_KEY: ${{ secrets.ALPHA_TEST_AUTH_TOKEN }}

steps:
- name: Checkout project
Expand Down
6 changes: 3 additions & 3 deletions examples/cache-with-aws/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

- You do not need gradle to be installed
- JDK 14 or above is required to run the example
- To get started with Momento you will need a Momento Auth Token. You can get one from the
- To get started with Momento you will need a Momento API Key. You can get one from the
[Momento Console](https://console.gomomento.com).
- This demo is similar to the Basic demo under the ```cache``` directory where it creates a cache, lists
all the existing caches, and sets and gets a key. However, it fetches your Momento authentication token
from AWS secrets manager rather than the environment variable. As a pre-requisite, you need to store your
Momento auth token retrieved from the console in AWS Secrets Manager. Refer to our [documentation](https://docs.momentohq.com/develop/integrations/aws-secrets-manager)
Momento API Key retrieved from the console in AWS Secrets Manager. Refer to our [documentation](https://docs.momentohq.com/develop/integrations/aws-secrets-manager)
for a walkthrough of storing the token in Secrets Manager.

### Basic
Expand All @@ -31,4 +31,4 @@ dependencies {
implementation("software.momento.java:sdk:0.24.0")
implementation("software.amazon.awssdk:secretsmanager:2.20.93")
}
```
```
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

public class BasicExample {

private static final String AUTH_TOKEN_SECRET_NAME = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_SECRET_NAME = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final Logger logger = LoggerFactory.getLogger(BasicExample.class);
Expand Down Expand Up @@ -97,7 +97,7 @@ public static CredentialProvider getCredentialsFromSecretsManagerAuthToken() {
.build();

final GetSecretValueRequest getSecretValueRequest =
GetSecretValueRequest.builder().secretId(AUTH_TOKEN_SECRET_NAME).build();
GetSecretValueRequest.builder().secretId(API_KEY_SECRET_NAME).build();

final GetSecretValueResponse getSecretValueResponse;

Expand All @@ -116,7 +116,7 @@ public static CredentialProvider getCredentialsFromSecretsManagerAuthToken() {
logger.error(
"An error occured while parsing the secrets manager vended"
+ " authentication token , key: "
+ AUTH_TOKEN_SECRET_NAME,
+ API_KEY_SECRET_NAME,
e);
throw e;
}
Expand Down
21 changes: 14 additions & 7 deletions examples/cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,56 @@ _Read this in other languages_: [日本語](README.ja.md)

- You do not need gradle to be installed
- JDK 14 or above is required to run the example
- To get started with Momento you will need a Momento Auth Token. You can get one from the
- To get started with Momento you will need a Momento API key. You can get one from the
[Momento Console](https://console.gomomento.com).

### Basic
```bash
MOMENTO_AUTH_TOKEN=<YOUR AUTH TOKEN> ./gradlew basic
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew basic
```

Example Code: [BasicExample.java](cache/src/main/java/momento/client/example/BasicExample.java)


### List
```bash
MOMENTO_AUTH_TOKEN=<YOUR AUTH TOKEN> ./gradlew list
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew list
```

Example Code: [ListExample.java](cache/src/main/java/momento/client/example/ListExample.java)

### Set
```bash
MOMENTO_AUTH_TOKEN=<YOUR AUTH TOKEN> ./gradlew set
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew set
```

Example Code: [SetExample.java](cache/src/main/java/momento/client/example/SetExample.java)

### Dictionary
```bash
MOMENTO_AUTH_TOKEN=<YOUR AUTH TOKEN> ./gradlew dictionary
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew dictionary
```

Example Code: [DictionaryExample.java](cache/src/main/java/momento/client/example/DictionaryExample.java)

### Sorted Set
```bash
MOMENTO_AUTH_TOKEN=<YOUR AUTH TOKEN> ./gradlew sortedSet
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew sortedSet
```

Example Code: [SortedSetExample.java](cache/src/main/java/momento/client/example/SortedSetExample.java)

### Batch Util
```bash
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew sortedSet
```

Example Code: [SortedSetExample.java](cache/src/main/java/momento/client/example/SortedSetExample.java)


### With a Backing Database
```bash
MOMENTO_AUTH_TOKEN=<YOUR AUTH TOKEN> ./gradlew withDatabase
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew withDatabase
```

Example Code: [WithDatabaseExample.java](cache/src/main/java/momento/client/example/advanced/WithDatabaseExample.java)
Expand Down
8 changes: 7 additions & 1 deletion examples/cache/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repositories {
}

dependencies {
implementation("software.momento.java:sdk:1.3.1")
implementation("software.momento.java:sdk:1.5.0")

implementation("com.google.guava:guava:31.1-android")

Expand Down Expand Up @@ -85,6 +85,12 @@ task("sortedSet", JavaExec::class) {
mainClass.set("momento.client.example.SortedSetExample")
}

task("batchUtil", JavaExec::class) {
description = "Run the batch util example"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("momento.client.example.BatchUtilsExample")
}

task("docExamples", JavaExec::class) {
description = "Validate that the API doc examples run"
classpath = sourceSets.main.get().runtimeClasspath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

public class BasicExample {

private static final String AUTH_TOKEN_ENV_VAR = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final String CACHE_NAME = "cache";
Expand All @@ -23,7 +23,7 @@ public class BasicExample {
public static void main(String[] args) {
printStartBanner();

final CredentialProvider credentialProvider = new EnvVarCredentialProvider(AUTH_TOKEN_ENV_VAR);
final CredentialProvider credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);

try (final CacheClient client =
CacheClient.create(credentialProvider, Configurations.Laptop.latest(), DEFAULT_ITEM_TTL)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package momento.client.example;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import momento.sdk.CacheClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.auth.EnvVarCredentialProvider;
import momento.sdk.batchutils.MomentoBatchUtils;
import momento.sdk.batchutils.request.BatchGetRequest;
import momento.sdk.batchutils.response.BatchGetResponse;
import momento.sdk.config.Configurations;
import momento.sdk.exceptions.AlreadyExistsException;
import momento.sdk.responses.cache.GetResponse;
import momento.sdk.responses.cache.control.CacheCreateResponse;

/**
* BatchUtilsExample demonstrates the use of MomentoBatchUtils for performing batch operations with
* the Momento SDK. This class includes examples of setting up a cache, adding test data, and
* performing batch get operations.
*
* <p>The example covers: - Creating a cache if it does not exist. - Adding a set of key-value pairs
* to the cache. - Performing a batch get operation to retrieve multiple keys in a single call. -
* Handling responses and displaying the results.
*
* <p>It utilizes the Momento SDK's CacheClient for cache operations and the MomentoBatchUtils for
* handling batch operations efficiently.
*/
public class BatchUtilsExample {

private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final String CACHE_NAME = "cache";

// represents the concurrency level for the batch of requests we send to Momento
private static final int MAX_CONCURRENT_REQUESTS = 5;

private static final int TOTAL_KEYS = 20;

public static void main(String[] args) {

final CredentialProvider credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);

try (final CacheClient client =
CacheClient.create(credentialProvider, Configurations.Laptop.latest(), DEFAULT_ITEM_TTL)) {

createCache(client, CACHE_NAME);

printStartBanner();

setupTestData(client);
performBatchGet(client);

printEndBanner();
}
}

private static void setupTestData(CacheClient cacheClient) {
for (int i = 0; i < TOTAL_KEYS; i++) {
final String key = "key" + i;
final String value = "value" + i;
cacheClient.set(CACHE_NAME, key, value).join();
System.out.println("Added " + key + " -> " + value);
}
}

private static void performBatchGet(final CacheClient client) {

// Building the util client using try-with-resources semantic to auto-close the client. Doing so
// shuts down
// and cleans up the executor
try (final MomentoBatchUtils momentoBatchUtils =
MomentoBatchUtils.builder(client)
.withMaxConcurrentRequests(MAX_CONCURRENT_REQUESTS)
.build()) {

final List<String> keys = new ArrayList<>();

for (int i = 0; i < TOTAL_KEYS; i++) {
final String key = "key" + i;
keys.add(key);
}

final BatchGetRequest.StringKeyBatchGetRequest request =
new BatchGetRequest.StringKeyBatchGetRequest(keys);

System.out.println("Performing batchGet for " + TOTAL_KEYS + " number of keys");

final BatchGetResponse response = momentoBatchUtils.batchGet(CACHE_NAME, request).join();

if (response instanceof BatchGetResponse.StringKeyBatchGetSummary summary) {
for (BatchGetResponse.StringKeyBatchGetSummary.GetSummary getSummary :
summary.getSummaries()) {
System.out.println(
"Key: "
+ getSummary.getKey()
+ ", Value: "
+ ((GetResponse.Hit) getSummary.getGetResponse()).valueString());
}
} else {
System.out.println("Error occurred during batch get operation.");
}
}
}

private static void createCache(CacheClient cacheClient, String cacheName) {
final CacheCreateResponse createResponse = cacheClient.createCache(cacheName).join();
if (createResponse instanceof CacheCreateResponse.Error error) {
if (error.getCause() instanceof AlreadyExistsException) {
System.out.println("Cache with name '" + cacheName + "' already exists.");
} else {
System.out.println("Unable to create cache with error " + error.getErrorCode());
System.out.println(error.getMessage());
}
}
}

private static void printStartBanner() {
System.out.println("******************************************************************");
System.out.println("BatchUtils Example Start");
System.out.println("******************************************************************");
}

private static void printEndBanner() {
System.out.println("******************************************************************");
System.out.println("BatchUtils Example End");
System.out.println("******************************************************************");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

public class DictionaryExample {

private static final String AUTH_TOKEN_ENV_VAR = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final String CACHE_NAME = "dictionary-example-cache";
Expand All @@ -32,9 +32,9 @@ public static void main(String[] args) {

final CredentialProvider credentialProvider;
try {
credentialProvider = new EnvVarCredentialProvider(AUTH_TOKEN_ENV_VAR);
credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);
} catch (SdkException e) {
logger.error("Unable to load credential from environment variable " + AUTH_TOKEN_ENV_VAR, e);
logger.error("Unable to load credential from environment variable " + API_KEY_ENV_VAR, e);
throw e;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

public class ListExample {

private static final String AUTH_TOKEN_ENV_VAR = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final String CACHE_NAME = "list-example-cache";
Expand All @@ -32,9 +32,9 @@ public static void main(String[] args) {

final CredentialProvider credentialProvider;
try {
credentialProvider = new EnvVarCredentialProvider(AUTH_TOKEN_ENV_VAR);
credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);
} catch (SdkException e) {
logger.error("Unable to load credential from environment variable " + AUTH_TOKEN_ENV_VAR, e);
logger.error("Unable to load credential from environment variable " + API_KEY_ENV_VAR, e);
throw e;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

@SuppressWarnings("UnstableApiUsage")
public class LoadGenerator {
private static final String AUTH_TOKEN_ENV_VAR = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);
private static final String CACHE_NAME = "java-loadgen";
private static final Logger logger = LoggerFactory.getLogger(LoadGenerator.class);
Expand Down Expand Up @@ -58,9 +58,9 @@ public LoadGenerator(

final CredentialProvider credentialProvider;
try {
credentialProvider = new EnvVarCredentialProvider(AUTH_TOKEN_ENV_VAR);
credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);
} catch (SdkException e) {
logger.error("Unable to load credential from environment variable " + AUTH_TOKEN_ENV_VAR, e);
logger.error("Unable to load credential from environment variable " + API_KEY_ENV_VAR, e);
throw e;
}
client = CacheClient.create(credentialProvider, Configurations.Laptop.v1(), DEFAULT_ITEM_TTL);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

public class SetExample {

private static final String AUTH_TOKEN_ENV_VAR = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final String CACHE_NAME = "set-example-cache";
Expand All @@ -31,9 +31,9 @@ public static void main(String[] args) {

final CredentialProvider credentialProvider;
try {
credentialProvider = new EnvVarCredentialProvider(AUTH_TOKEN_ENV_VAR);
credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);
} catch (SdkException e) {
logger.error("Unable to load credential from environment variable " + AUTH_TOKEN_ENV_VAR, e);
logger.error("Unable to load credential from environment variable " + API_KEY_ENV_VAR, e);
throw e;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

public class SortedSetExample {

private static final String AUTH_TOKEN_ENV_VAR = "MOMENTO_AUTH_TOKEN";
private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";
private static final Duration DEFAULT_ITEM_TTL = Duration.ofSeconds(60);

private static final String CACHE_NAME = "set-example-cache";
Expand All @@ -35,9 +35,9 @@ public static void main(String[] args) {

final CredentialProvider credentialProvider;
try {
credentialProvider = new EnvVarCredentialProvider(AUTH_TOKEN_ENV_VAR);
credentialProvider = new EnvVarCredentialProvider(API_KEY_ENV_VAR);
} catch (SdkException e) {
logger.error("Unable to load credential from environment variable " + AUTH_TOKEN_ENV_VAR, e);
logger.error("Unable to load credential from environment variable " + API_KEY_ENV_VAR, e);
throw e;
}

Expand Down
Loading

0 comments on commit 4522e96

Please sign in to comment.