Skip to content

Commit

Permalink
chore: add docs examples for PreviewStorageClient (#384)
Browse files Browse the repository at this point in the history
* chore: add docs examples for PreviewStorageClient
  • Loading branch information
cprice404 committed Jul 11, 2024
1 parent 7f07993 commit 95a7765
Show file tree
Hide file tree
Showing 18 changed files with 452 additions and 19 deletions.
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,24 @@ jobs:
sdk_language: Java
dev_docs_slug: java

- name: Verify examples README generation
uses: momentohq/standards-and-practices/github-actions/oss-readme-template@gh-actions-v2
with:
project_status: official
project_stability: beta
project_type: other
template_file: ./examples/README.template.md
output_file: ./examples/README.md

- name: Verify Storage examples README generation
uses: momentohq/standards-and-practices/github-actions/oss-readme-template@gh-actions-v2
with:
project_status: official
project_stability: beta
project_type: other
template_file: ./examples/storage/README.template.md
output_file: ./examples/storage/README.md

- name: Commitlint and Other Shared Build Steps
uses: momentohq/standards-and-practices/github-actions/shared-build@gh-actions-v1
env:
Expand Down
18 changes: 18 additions & 0 deletions .github/workflows/on-push-to-main-branch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,21 @@ jobs:
project_type: sdk
sdk_language: Java
dev_docs_slug: java

- name: Verify Storage examples README generation
uses: momentohq/standards-and-practices/github-actions/generate-and-commit-oss-readme@gh-actions-v2
with:
project_status: official
project_stability: beta
project_type: other
template_file: ./examples/storage/README.template.md
output_file: ./examples/storage/README.md

- name: Verify examples README generation
uses: momentohq/standards-and-practices/github-actions/generate-and-commit-oss-readme@gh-actions-v2
with:
project_status: official
project_stability: beta
project_type: other
template_file: ./examples/README.template.md
output_file: ./examples/README.md
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,3 @@ examples/lib/.classpath
examples/lib/.project
examples/lib/bin
.vscode/
*logback.xml
10 changes: 0 additions & 10 deletions examples/README.md

This file was deleted.

13 changes: 13 additions & 0 deletions examples/README.template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{{ ossHeader }}

# Momento Java SDK Examples

## Examples

All examples are in different subdirectories for different use-cases, and minimizes the dependencies required to run them.

- [Examples to get started with Momento Cache](https://github.com/momentohq/client-sdk-java/tree/main/examples/cache)
- [Examples that uses Momento Cache with one or more AWS integrations, such as AWS Secrets Manager to store your Momento auth token](https://github.com/momentohq/client-sdk-java/tree/main/examples/cache-with-aws)
- [Examples to get started with Momento Storage](https://github.com/momentohq/client-sdk-java/tree/main/examples/storage)

{{ ossFooter }}
2 changes: 1 addition & 1 deletion examples/cache-with-aws/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.11.0")
implementation("software.momento.java:sdk:1.14.1")

// For examples to store secrets in AWS Secrets Manager
implementation("software.amazon.awssdk:secretsmanager:2.20.93")
Expand Down
2 changes: 1 addition & 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.11.0")
implementation("software.momento.java:sdk:1.14.1")

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import momento.sdk.CacheClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.Configurations;
import momento.sdk.exceptions.AlreadyExistsException;
import momento.sdk.exceptions.MomentoErrorCode;
import momento.sdk.responses.cache.DeleteResponse;
import momento.sdk.responses.cache.GetResponse;
import momento.sdk.responses.cache.IncrementResponse;
Expand Down Expand Up @@ -95,7 +95,7 @@ public static void example_API_CreateCache(CacheClient cacheClient) {
if (response instanceof CacheCreateResponse.Success) {
System.out.println("Cache 'test-cache' created");
} else if (response instanceof CacheCreateResponse.Error error) {
if (error.getCause() instanceof AlreadyExistsException) {
if (error.getErrorCode() == MomentoErrorCode.ALREADY_EXISTS_ERROR) {
System.out.println("Cache 'test-cache' already exists");
} else {
throw new RuntimeException(
Expand Down
4 changes: 2 additions & 2 deletions examples/lambda/docker/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ repositories {

dependencies {
implementation("com.amazonaws:aws-lambda-java-core:1.2.1")
implementation("software.momento.java:sdk:1.11.0")
implementation("software.momento.java:sdk:1.14.1")
}

tasks.jar {
Expand All @@ -25,4 +25,4 @@ tasks.shadowJar {
archiveBaseName.set("docker")
archiveClassifier.set("all")
mergeServiceFiles()
}
}
1 change: 1 addition & 0 deletions examples/settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ include("cache-with-aws")
include("lambda:docker")
include("token")
include("topic")
include("storage")
34 changes: 34 additions & 0 deletions examples/storage/README.template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{{ ossHeader }}

# Momento Java SDK - Storage Client Examples

## Running the Examples

- 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 API key. You can get one from the
[Momento Console](https://console.gomomento.com).

### Basic

```bash
MOMENTO_API_KEY=<YOUR API KEY> ./gradlew basic
```

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

## Using the Java SDK in your project

### Gradle Configuration

Update your Gradle build to include the components

#### build.gradle.kts

```kotlin
dependencies {
implementation("software.momento.java:sdk:1.x.x")
}
```

{{ ossFooter }}
64 changes: 64 additions & 0 deletions examples/storage/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java library project to get you started.
* For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
* User Manual available at https://docs.gradle.org/7.2/userguide/building_java_projects.html
*/

plugins {
application
id("com.diffplug.spotless") version "5.15.1"
}

repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}

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

// Logging framework to log and enable logging in the Momento client.
implementation("ch.qos.logback:logback-classic:1.4.7")

// Use JUnit Jupiter for testing.
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
}

spotless {
java {
removeUnusedImports()
googleJavaFormat("1.11.0")
}
}

tasks.test {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}

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

task("docExamples", JavaExec::class) {
description = "Validate that the API doc examples run"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("momento.client.example.doc_examples.DocExamplesJavaAPIs")
}

task("docCheatSheet", JavaExec::class) {
description = "Validate that the doc cheat sheet runs"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("momento.client.example.doc_examples.CheatSheet")
}

task("docsTasks") {
dependsOn("docCheatSheet")
dependsOn("docExamples")
}

task("prepareKotlinBuildScriptModel") {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package momento.client.example;

import java.nio.charset.StandardCharsets;
import momento.sdk.PreviewStorageClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.StorageConfigurations;
import momento.sdk.exceptions.StoreAlreadyExistsException;
import momento.sdk.responses.storage.CreateStoreResponse;
import momento.sdk.responses.storage.GetResponse;
import momento.sdk.responses.storage.ListStoresResponse;
import momento.sdk.responses.storage.StoreInfo;

public class BasicExample {

private static final String API_KEY_ENV_VAR = "MOMENTO_API_KEY";

private static final String STORE_NAME = "store";
private static final String KEY = "key";
private static final String VALUE = "value";

public static void main(String[] args) {
printStartBanner();

final CredentialProvider credentialProvider = CredentialProvider.fromEnvVar(API_KEY_ENV_VAR);

try (final var client =
new PreviewStorageClient(credentialProvider, StorageConfigurations.Laptop.latest())) {

createStore(client, STORE_NAME);

listStores(client);

System.out.printf("Putting key '%s', value '%s'%n", KEY, VALUE);
// store a string value
client.put(STORE_NAME, KEY, VALUE).join();

// you can also store values of type byte[], long, or double:
byte[] bytesValue = "value".getBytes(StandardCharsets.UTF_8);
client.put(STORE_NAME, "bytes-key", bytesValue).join();
client.put(STORE_NAME, "long-key", 42L).join();
client.put(STORE_NAME, "double-key", 3.14).join();

System.out.printf("Getting value for key '%s'%n", KEY);

final GetResponse getResponse = client.get(STORE_NAME, KEY).join();

// simplified style, if you are confident the value exists and is a String:
final String value = getResponse.valueWhenFound().get().getString().get();

// pattern-matching style, more suitable for production code:
if (getResponse instanceof GetResponse.Found hit) {
// if you're confident it's a String:
System.out.printf("Found value for key '%s': '%s'%n", KEY, hit.value().getString().get());

// you're not sure of the type:
switch (hit.value().getType()) {
case BYTE_ARRAY -> {
System.out.println("Got a byte array: " + hit.value().getByteArray().get());
}
case STRING -> {
System.out.println("Got a string: " + hit.value().getString().get());
}
case LONG -> {
System.out.println("Got a long: " + hit.value().getLong().get());
}
case DOUBLE -> {
System.out.println("Got a double: " + hit.value().getDouble().get());
}
}
} else if (getResponse instanceof GetResponse.NotFound) {
System.out.println("Found no value for key " + KEY);
} else if (getResponse instanceof GetResponse.Error error) {
System.out.printf(
"Unable to look up value for key '%s' with error %s\n", KEY, error.getErrorCode());
System.out.println(error.getMessage());
}
}
printEndBanner();
}

private static void createStore(PreviewStorageClient storageClient, String storeName) {
final CreateStoreResponse createResponse = storageClient.createStore(storeName).join();
if (createResponse instanceof CreateStoreResponse.Error error) {
if (error.getCause() instanceof StoreAlreadyExistsException) {
System.out.println("Store with name '" + storeName + "' already exists.");
} else {
System.out.println("Unable to create store with error " + error.getErrorCode());
System.out.println(error.getMessage());
}
}
}

private static void listStores(PreviewStorageClient storageClient) {
System.out.println("Listing caches:");
final ListStoresResponse listResponse = storageClient.listStores().join();
if (listResponse instanceof ListStoresResponse.Success success) {
for (StoreInfo storeInfo : success.getStores()) {
System.out.println(storeInfo.getName());
}
} else if (listResponse instanceof ListStoresResponse.Error error) {
System.out.println("Unable to list caches with error " + error.getErrorCode());
System.out.println(error.getMessage());
}
}

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

private static void printEndBanner() {
System.out.println("******************************************************************");
System.out.println("Basic Example End");
System.out.println("******************************************************************");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package momento.client.example.doc_examples;

import momento.sdk.PreviewStorageClient;
import momento.sdk.auth.CredentialProvider;
import momento.sdk.config.StorageConfigurations;

public class CheatSheet {
public static void main(String[] args) {
try (final var storageClient =
new PreviewStorageClient(
CredentialProvider.fromEnvVar("MOMENTO_API_KEY"),
StorageConfigurations.Laptop.latest())) {
// ...
}
}
}
Loading

0 comments on commit 95a7765

Please sign in to comment.