instanceCheckFuture;
+ private static NeptuneAsyncClient neptuneAsyncClient;
+ private final Region region = Region.US_EAST_1;
+ private static final Logger logger = LoggerFactory.getLogger(NeptuneActions.class);
+ private final NeptuneClient neptuneClient = NeptuneClient.builder().region(region).build();
+
+ /**
+ * Retrieves an instance of the NeptuneAsyncClient.
+ *
+ * This method initializes and returns a singleton instance of the NeptuneAsyncClient. The client
+ * is configured with the following settings:
+ *
+ * - Maximum concurrency: 100
+ * - Connection timeout: 60 seconds
+ * - Read timeout: 60 seconds
+ * - Write timeout: 60 seconds
+ * - API call timeout: 2 minutes
+ * - API call attempt timeout: 90 seconds
+ * - Retry strategy: STANDARD
+ *
+ * The client is built using the NettyNioAsyncHttpClient.
+ *
+ * @return the singleton instance of the NeptuneAsyncClient
+ */
+ private static NeptuneAsyncClient getAsyncClient() {
+ if (neptuneAsyncClient == null) {
+ SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
+ .maxConcurrency(100)
+ .connectionTimeout(Duration.ofSeconds(60))
+ .readTimeout(Duration.ofSeconds(60))
+ .writeTimeout(Duration.ofSeconds(60))
+ .build();
+
+ ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
+ .apiCallTimeout(Duration.ofMinutes(2))
+ .apiCallAttemptTimeout(Duration.ofSeconds(90))
+ .retryStrategy(RetryMode.STANDARD)
+ .build();
+
+ neptuneAsyncClient = NeptuneAsyncClient.builder()
+ .httpClient(httpClient)
+ .overrideConfiguration(overrideConfig)
+ .build();
+ }
+ return neptuneAsyncClient;
+ }
+
+ /**
+ * Asynchronously deletes a set of Amazon Neptune resources in a defined order.
+ *
+ * The method performs the following operations in sequence:
+ *
+ * - Deletes the Neptune DB instance identified by {@code dbInstanceId}.
+ * - Waits until the DB instance is fully deleted.
+ * - Deletes the Neptune DB cluster identified by {@code dbClusterId}.
+ * - Deletes the Neptune DB subnet group identified by {@code subnetGroupName}.
+ *
+ *
+ * If any step fails, the subsequent operations are not performed, and the exception
+ * is logged. This method blocks the calling thread until all operations complete.
+ *
+ * @param dbInstanceId the ID of the Neptune DB instance to delete
+ * @param dbClusterId the ID of the Neptune DB cluster to delete
+ * @param subnetGroupName the name of the Neptune DB subnet group to delete
+ */
+ public void deleteNeptuneResourcesAsync(String dbInstanceId, String dbClusterId, String subnetGroupName) {
+ deleteDBInstanceAsync(dbInstanceId)
+ .thenCompose(v -> waitUntilInstanceDeletedAsync(dbInstanceId))
+ .thenCompose(v -> deleteDBClusterAsync(dbClusterId))
+ .thenCompose(v -> deleteDBSubnetGroupAsync(subnetGroupName))
+ .whenComplete((v, ex) -> {
+ if (ex != null) {
+ logger.info("Failed to delete Neptune resources: " + ex.getMessage());
+ } else {
+ logger.info("Neptune resources deleted successfully.");
+ }
+ })
+ .join(); // Waits for the entire async chain to complete
+ }
+
+ // snippet-start:[neptune.java2.delete.subnet.group.main]
+ /**
+ * Deletes a subnet group.
+ *
+ * @param subnetGroupName the identifier of the subnet group to delete
+ * @return a {@link CompletableFuture} that completes when the cluster has been deleted
+ */
+ public CompletableFuture deleteDBSubnetGroupAsync(String subnetGroupName) {
+ DeleteDbSubnetGroupRequest request = DeleteDbSubnetGroupRequest.builder()
+ .dbSubnetGroupName(subnetGroupName)
+ .build();
+
+ return getAsyncClient().deleteDBSubnetGroup(request)
+ .thenAccept(response -> logger.info("🗑️ Deleting Subnet Group: " + subnetGroupName));
+ }
+ // snippet-end:[neptune.java2.delete.subnet.group.main]
+
+ // snippet-start:[neptune.java2.delete.cluster.main]
+ /**
+ * Deletes a DB instance asynchronously.
+ *
+ * @param clusterId the identifier of the cluster to delete
+ * @return a {@link CompletableFuture} that completes when the cluster has been deleted
+ */
+ public CompletableFuture deleteDBClusterAsync(String clusterId) {
+ DeleteDbClusterRequest request = DeleteDbClusterRequest.builder()
+ .dbClusterIdentifier(clusterId)
+ .skipFinalSnapshot(true)
+ .build();
+
+ return getAsyncClient().deleteDBCluster(request)
+ .thenAccept(response -> System.out.println("🗑️ Deleting DB Cluster: " + clusterId));
+ }
+ // snippet-end:[neptune.java2.delete.cluster.main]
+
+ public CompletableFuture waitUntilInstanceDeletedAsync(String instanceId) {
+ CompletableFuture future = new CompletableFuture<>();
+ long startTime = System.currentTimeMillis();
+ checkInstanceDeletedRecursive(instanceId, startTime, future);
+ return future;
+ }
+
+ // snippet-start:[neptune.java2.delete.instance.main]
+ /**
+ * Deletes a DB instance asynchronously.
+ *
+ * @param instanceId the identifier of the DB instance to be deleted
+ * @return a {@link CompletableFuture} that completes when the DB instance has been deleted
+ */
+ public CompletableFuture deleteDBInstanceAsync(String instanceId) {
+ DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
+ .dbInstanceIdentifier(instanceId)
+ .skipFinalSnapshot(true)
+ .build();
+
+ return getAsyncClient().deleteDBInstance(request)
+ .thenAccept(response -> System.out.println("🗑️ Deleting DB Instance: " + instanceId));
+ }
+ // snippet-end:[neptune.java2.delete.instance.main]
+
+
+ private void checkInstanceDeletedRecursive(String instanceId, long startTime, CompletableFuture future) {
+ DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder()
+ .dbInstanceIdentifier(instanceId)
+ .build();
+
+ getAsyncClient().describeDBInstances(request)
+ .whenComplete((response, exception) -> {
+ if (exception != null) {
+ Throwable cause = exception.getCause();
+ if (cause instanceof NeptuneException &&
+ ((NeptuneException) cause).awsErrorDetails().errorCode().equals("DBInstanceNotFound")) {
+ long elapsed = (System.currentTimeMillis() - startTime) / 1000;
+ logger.info("\r Instance %s deleted after %ds%n", instanceId, elapsed);
+ future.complete(null);
+ return;
+ }
+ future.completeExceptionally(new CompletionException("Error polling DB instance", cause));
+ return;
+ }
+
+ String status = response.dbInstances().get(0).dbInstanceStatus();
+ long elapsed = (System.currentTimeMillis() - startTime) / 1000;
+ System.out.printf("\r Waiting: Instance %s status: %-10s (%ds elapsed)", instanceId, status, elapsed);
+ System.out.flush();
+
+ CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
+ .execute(() -> checkInstanceDeletedRecursive(instanceId, startTime, future));
+ });
+ }
+
+
+ public void waitForClusterStatus(String clusterId, String desiredStatus) {
+ System.out.printf("Waiting for cluster '%s' to reach status '%s'...\n", clusterId, desiredStatus);
+ CompletableFuture future = new CompletableFuture<>();
+ checkClusterStatusRecursive(clusterId, desiredStatus, System.currentTimeMillis(), future);
+ future.join();
+ }
+
+ private void checkClusterStatusRecursive(String clusterId, String desiredStatus, long startTime, CompletableFuture future) {
+ DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
+ .dbClusterIdentifier(clusterId)
+ .build();
+
+ getAsyncClient().describeDBClusters(request)
+ .whenComplete((response, exception) -> {
+ if (exception != null) {
+ Throwable cause = exception.getCause();
+ future.completeExceptionally(
+ new CompletionException("Error checking Neptune cluster status", cause)
+ );
+ return;
+ }
+
+ List clusters = response.dbClusters();
+ if (clusters.isEmpty()) {
+ future.completeExceptionally(new RuntimeException("Cluster not found: " + clusterId));
+ return;
+ }
+
+ String currentStatus = clusters.get(0).status();
+ long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000;
+ System.out.printf("\r Elapsed: %-20s Cluster status: %-20s", formatElapsedTime((int) elapsedSeconds), currentStatus);
+ System.out.flush();
+
+ if (desiredStatus.equalsIgnoreCase(currentStatus)) {
+ System.out.printf("\r Neptune cluster reached desired status '%s' after %s.\n", desiredStatus, formatElapsedTime((int) elapsedSeconds));
+ future.complete(null);
+ } else {
+ CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
+ .execute(() -> checkClusterStatusRecursive(clusterId, desiredStatus, startTime, future));
+ }
+ });
+ }
+
+
+ // snippet-start:[neptune.java2.start.cluster.main]
+ /**
+ * Starts an Amazon Neptune DB cluster.
+ *
+ * @param clusterIdentifier the unique identifier of the DB cluster to be stopped
+ */
+ public CompletableFuture startDBClusterAsync(String clusterIdentifier) {
+ StartDbClusterRequest clusterRequest = StartDbClusterRequest.builder()
+ .dbClusterIdentifier(clusterIdentifier)
+ .build();
+
+ return getAsyncClient().startDBCluster(clusterRequest)
+ .whenComplete((response, error) -> {
+ if (error != null) {
+ Throwable cause = error.getCause() != null ? error.getCause() : error;
+
+ if (cause instanceof ResourceNotFoundException) {
+ throw (ResourceNotFoundException) cause;
+ }
+
+ throw new RuntimeException("Failed to start DB cluster: " + cause.getMessage(), cause);
+ } else {
+ logger.info("DB Cluster starting: " + clusterIdentifier);
+ }
+ });
+ }
+ // snippet-end:[neptune.java2.start.cluster.main]
+
+ // snippet-start:[neptune.java2.stop.cluster.main]
+ /**
+ * Stops an Amazon Neptune DB cluster.
+ *
+ * @param clusterIdentifier the unique identifier of the DB cluster to be stopped
+ */
+ public CompletableFuture stopDBClusterAsync(String clusterIdentifier) {
+ StopDbClusterRequest clusterRequest = StopDbClusterRequest.builder()
+ .dbClusterIdentifier(clusterIdentifier)
+ .build();
+
+ return getAsyncClient().stopDBCluster(clusterRequest)
+ .whenComplete((response, error) -> {
+ if (error != null) {
+ Throwable cause = error.getCause() != null ? error.getCause() : error;
+
+ if (cause instanceof ResourceNotFoundException) {
+ throw (ResourceNotFoundException) cause;
+ }
+
+ throw new RuntimeException("Failed to stop DB cluster: " + cause.getMessage(), cause);
+ } else {
+ logger.info("DB Cluster stopped: " + clusterIdentifier);
+ }
+ });
+ }
+
+ // snippet-end:[neptune.java2.stop.cluster.main]
+
+ // snippet-start:[neptune.java2.describe.cluster.main]
+
+ /**
+ * Asynchronously describes the specified Amazon RDS DB cluster.
+ *
+ * @param clusterId the identifier of the DB cluster to describe
+ * @return a {@link CompletableFuture} that completes when the operation is done, or throws a {@link RuntimeException}
+ * if an error occurs
+ */
+ public CompletableFuture describeDBClustersAsync(String clusterId) {
+ DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
+ .dbClusterIdentifier(clusterId)
+ .build();
+
+ return getAsyncClient().describeDBClusters(request)
+ .thenAccept(response -> {
+ for (DBCluster cluster : response.dbClusters()) {
+ logger.info("Cluster Identifier: " + cluster.dbClusterIdentifier());
+ logger.info("Status: " + cluster.status());
+ logger.info("Engine: " + cluster.engine());
+ logger.info("Engine Version: " + cluster.engineVersion());
+ logger.info("Endpoint: " + cluster.endpoint());
+ logger.info("Reader Endpoint: " + cluster.readerEndpoint());
+ logger.info("Availability Zones: " + cluster.availabilityZones());
+ logger.info("Subnet Group: " + cluster.dbSubnetGroup());
+ logger.info("VPC Security Groups:");
+ cluster.vpcSecurityGroups().forEach(vpcGroup ->
+ logger.info(" - " + vpcGroup.vpcSecurityGroupId()));
+ logger.info("Storage Encrypted: " + cluster.storageEncrypted());
+ logger.info("IAM DB Auth Enabled: " + cluster.iamDatabaseAuthenticationEnabled());
+ logger.info("Backup Retention Period: " + cluster.backupRetentionPeriod() + " days");
+ logger.info("Preferred Backup Window: " + cluster.preferredBackupWindow());
+ logger.info("Preferred Maintenance Window: " + cluster.preferredMaintenanceWindow());
+ logger.info("------");
+ }
+ })
+ .exceptionally(ex -> {
+ Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
+
+ if (cause instanceof ResourceNotFoundException) {
+ throw (ResourceNotFoundException) cause;
+ }
+
+ throw new RuntimeException("Failed to describe the DB cluster: " + cause.getMessage(), cause);
+ });
+ }
+ // snippet-end:[neptune.java2.describe.cluster.main]
+
+
+ public CompletableFuture checkInstanceStatus(String instanceId, String desiredStatus) {
+ CompletableFuture future = new CompletableFuture<>();
+ long startTime = System.currentTimeMillis();
+ checkStatusRecursive(instanceId, desiredStatus.toLowerCase(), startTime, future);
+ return future;
+ }
+
+ // snippet-start:[neptune.java2.describe.dbinstance.main]
+ /**
+ * Checks the status of a Neptune instance recursively until the desired status is reached or a timeout occurs.
+ *
+ * @param instanceId the ID of the Neptune instance to check
+ * @param desiredStatus the desired status of the Neptune instance
+ * @param startTime the start time of the operation, used to calculate the elapsed time
+ * @param future a {@link CompletableFuture} that will be completed when the desired status is reached
+ */
+ private void checkStatusRecursive(String instanceId, String desiredStatus, long startTime, CompletableFuture future) {
+ DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder()
+ .dbInstanceIdentifier(instanceId)
+ .build();
+
+ getAsyncClient().describeDBInstances(request)
+ .whenComplete((response, exception) -> {
+ if (exception != null) {
+ Throwable cause = exception.getCause();
+ future.completeExceptionally(
+ new CompletionException("Error checking Neptune instance status", cause)
+ );
+ return;
+ }
+
+ List instances = response.dbInstances();
+ if (instances.isEmpty()) {
+ future.completeExceptionally(new RuntimeException("Instance not found: " + instanceId));
+ return;
+ }
+
+ String currentStatus = instances.get(0).dbInstanceStatus();
+ long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000;
+ System.out.printf("\r Elapsed: %-20s Status: %-20s", formatElapsedTime((int) elapsedSeconds), currentStatus);
+ System.out.flush();
+
+ if (desiredStatus.equalsIgnoreCase(currentStatus)) {
+ System.out.printf("\r Neptune instance reached desired status '%s' after %s.\n", desiredStatus, formatElapsedTime((int) elapsedSeconds));
+ future.complete(null);
+ } else {
+ CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
+ .execute(() -> checkStatusRecursive(instanceId, desiredStatus, startTime, future));
+ }
+ });
+ }
+ // snippet-end:[neptune.java2.describe.dbinstance.main]
+
+
+ private String formatElapsedTime(int seconds) {
+ int minutes = seconds / 60;
+ int remainingSeconds = seconds % 60;
+
+ if (minutes > 0) {
+ return minutes + (minutes == 1 ? " min" : " mins") + ", " +
+ remainingSeconds + (remainingSeconds == 1 ? " sec" : " secs");
+ } else {
+ return remainingSeconds + (remainingSeconds == 1 ? " sec" : " secs");
+ }
+ }
+
+ // snippet-start:[neptune.java2.create.dbinstance.main]
+
+ /**
+ * Creates a new Amazon Neptune DB instance asynchronously.
+ *
+ * @param dbInstanceId the identifier for the new DB instance
+ * @param dbClusterId the identifier for the DB cluster that the new instance will be a part of
+ * @return a {@link CompletableFuture} that completes with the identifier of the newly created DB instance
+ * @throws CompletionException if the operation fails, with a cause of either:
+ * - {@link ServiceQuotaExceededException} if the request would exceed the maximum quota, or
+ * - a general exception with the failure message
+ */
+ public CompletableFuture createDBInstanceAsync(String dbInstanceId, String dbClusterId) {
+ CreateDbInstanceRequest request = CreateDbInstanceRequest.builder()
+ .dbInstanceIdentifier(dbInstanceId)
+ .dbInstanceClass("db.r5.large")
+ .engine("neptune")
+ .dbClusterIdentifier(dbClusterId)
+ .build();
+
+ return getAsyncClient().createDBInstance(request)
+ .whenComplete((response, exception) -> {
+ if (exception != null) {
+ Throwable cause = exception.getCause();
+ if (cause instanceof ServiceQuotaExceededException) {
+ throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
+ }
+ throw new CompletionException("Failed to create Neptune DB instance: " + exception.getMessage(), exception);
+ }
+ })
+ .thenApply(response -> {
+ String instanceId = response.dbInstance().dbInstanceIdentifier();
+ logger.info("Created Neptune DB Instance: " + instanceId);
+ return instanceId;
+ });
+ }
+ // snippet-end:[neptune.java2.create.dbinstance.main]
+
+ // snippet-start:[neptune.java2.create.cluster.main]
+
+ /**
+ * Creates a new Amazon Neptune DB cluster asynchronously.
+ *
+ * @param dbName the name of the DB cluster to be created
+ * @return a CompletableFuture that, when completed, provides the ID of the created DB cluster
+ * @throws CompletionException if the operation fails for any reason, including if the request would exceed the maximum quota
+ */
+ public CompletableFuture createDBClusterAsync(String dbName) {
+ CreateDbClusterRequest request = CreateDbClusterRequest.builder()
+ .dbClusterIdentifier(dbName)
+ .engine("neptune")
+ .deletionProtection(false)
+ .backupRetentionPeriod(1)
+ .build();
+
+ return getAsyncClient().createDBCluster(request)
+ .whenComplete((response, exception) -> {
+ if (exception != null) {
+ Throwable cause = exception.getCause();
+ if (cause instanceof ServiceQuotaExceededException) {
+ throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
+ }
+ throw new CompletionException("Failed to create Neptune DB cluster: " + exception.getMessage(), exception);
+ }
+ })
+ .thenApply(response -> {
+ String clusterId = response.dbCluster().dbClusterIdentifier();
+ logger.info("DB Cluster created: " + clusterId);
+ return clusterId;
+ });
+ }
+ // snippet-end:[neptune.java2.create.cluster.main]
+
+ // snippet-start:[neptune.java2.create.subnet.main]
+
+ /**
+ * Creates a new DB subnet group asynchronously.
+ *
+ * @param groupName the name of the subnet group to create
+ * @return a CompletableFuture that, when completed, returns the Amazon Resource Name (ARN) of the created subnet group
+ * @throws CompletionException if the operation fails, with a cause that may be a ServiceQuotaExceededException if the request would exceed the maximum quota
+ */
+ public CompletableFuture createSubnetGroupAsync(String groupName) {
+
+ // Get the Amazon Virtual Private Cloud (VPC) where the Neptune cluster and resources will be created
+ String vpcId = getDefaultVpcId();
+ logger.info("VPC is : " + vpcId);
+
+ List subnetList = getSubnetIds(vpcId);
+ for (String subnetId : subnetList) {
+ System.out.println("Subnet group:" +subnetId);
+ }
+
+ CreateDbSubnetGroupRequest request = CreateDbSubnetGroupRequest.builder()
+ .dbSubnetGroupName(groupName)
+ .dbSubnetGroupDescription("Subnet group for Neptune cluster")
+ .subnetIds(subnetList)
+ .build();
+
+ return getAsyncClient().createDBSubnetGroup(request)
+ .whenComplete((response, exception) -> {
+ if (exception != null) {
+ Throwable cause = exception.getCause();
+ if (cause instanceof ServiceQuotaExceededException) {
+ throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
+ }
+ throw new CompletionException("Failed to create subnet group: " + exception.getMessage(), exception);
+ }
+ })
+ .thenApply(response -> {
+ String name = response.dbSubnetGroup().dbSubnetGroupName();
+ String arn = response.dbSubnetGroup().dbSubnetGroupArn();
+ logger.info("Subnet group created: " + name);
+ return arn;
+ });
+ }
+ // snippet-end:[neptune.java2.create.subnet.main]
+
+ private List getSubnetIds(String vpcId) {
+ try (Ec2Client ec2 = Ec2Client.builder().region(region).build()) {
+ DescribeSubnetsRequest request = DescribeSubnetsRequest.builder()
+ .filters(builder -> builder.name("vpc-id").values(vpcId))
+ .build();
+
+ DescribeSubnetsResponse response = ec2.describeSubnets(request);
+ return response.subnets().stream()
+ .map(Subnet::subnetId)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public static String getDefaultVpcId() {
+ Ec2Client ec2 = Ec2Client.builder()
+ .region(Region.US_EAST_1)
+ .build();
+
+ Filter myFilter = Filter.builder()
+ .name("isDefault")
+ .values("true")
+ .build();
+
+ List filterList = new ArrayList<>();
+ filterList.add(myFilter);
+
+ DescribeVpcsRequest request = DescribeVpcsRequest.builder()
+ .filters(filterList)
+ .build();
+
+
+ DescribeVpcsResponse response = ec2.describeVpcs(request);
+ if (!response.vpcs().isEmpty()) {
+ Vpc defaultVpc = response.vpcs().get(0);
+ return defaultVpc.vpcId();
+ } else {
+ throw new RuntimeException("No default VPC found in this region.");
+ }
+ }
+}
+// snippet-end:[neptune.java2.actions.main]
\ No newline at end of file
diff --git a/javav2/example_code/neptune/src/main/java/com/example/neptune/scenerio/NeptuneScenario.java b/javav2/example_code/neptune/src/main/java/com/example/neptune/scenerio/NeptuneScenario.java
new file mode 100644
index 00000000000..e61efdff508
--- /dev/null
+++ b/javav2/example_code/neptune/src/main/java/com/example/neptune/scenerio/NeptuneScenario.java
@@ -0,0 +1,252 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package com.example.neptune.scenerio;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.neptunegraph.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.neptunegraph.model.ServiceQuotaExceededException;
+
+import java.util.Scanner;
+import java.util.concurrent.CompletionException;
+
+// snippet-start:[neptune.java2.scenario.main]
+public class NeptuneScenario {
+ public static final String DASHES = new String(new char[80]).replace("\0", "-");
+ private static final Logger logger = LoggerFactory.getLogger(NeptuneScenario.class);
+ static Scanner scanner = new Scanner(System.in);
+ static NeptuneActions neptuneActions = new NeptuneActions();
+
+ public static void main(String[] args) {
+ final String usage =
+ """
+ Usage:
+
+
+ Where:
+ subnetGroupName - The name of an existing Neptune DB subnet group that includes subnets in at least two Availability Zones.
+ clusterName - The unique identifier for the Neptune DB cluster.
+ dbInstanceId - The identifier for a specific Neptune DB instance within the cluster.
+ """;
+ String subnetGroupName = "neptuneSubnetGroup65";
+ String clusterName = "neptuneCluster65";
+ String dbInstanceId = "neptuneDB65";
+
+ logger.info("""
+ Amazon Neptune is a fully managed graph
+ database service by AWS, designed specifically
+ for handling complex relationships and connected
+ datasets at scale. It supports two popular graph models:
+ property graphs (via openCypher and Gremlin) and RDF
+ graphs (via SPARQL). This makes Neptune ideal for
+ use cases such as knowledge graphs, fraud detection,
+ social networking, recommendation engines, and
+ network management, where relationships between
+ entities are central to the data.
+
+ Being fully managed, Neptune handles database
+ provisioning, patching, backups, and replication,
+ while also offering high availability and durability
+ within AWS's infrastructure.
+
+ For developers, programming with Neptune allows
+ for building intelligent, relationship-aware
+ applications that go beyond traditional tabular
+ databases. Developers can use the AWS SDK for Java
+ to automate infrastructure operations (via NeptuneClient).
+
+ Let's get started...
+ """);
+ waitForInputToContinue(scanner);
+ runScenario(subnetGroupName, dbInstanceId, clusterName);
+ }
+
+ public static void runScenario(String subnetGroupName, String dbInstanceId, String clusterName) {
+ logger.info(DASHES);
+ logger.info("1. Create a Neptune DB Subnet Group");
+ logger.info("The Neptune DB subnet group is used when launching a Neptune cluster");
+ waitForInputToContinue(scanner);
+ try {
+ neptuneActions.createSubnetGroupAsync(subnetGroupName).join();
+
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ServiceQuotaExceededException) {
+ logger.error("The request failed due to service quota exceeded: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("2. Create a Neptune Cluster");
+ logger.info("A Neptune Cluster allows you to store and query highly connected datasets with low latency.");
+ waitForInputToContinue(scanner);
+ String dbClusterId;
+ try {
+ dbClusterId = neptuneActions.createDBClusterAsync(clusterName).join();
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ServiceQuotaExceededException) {
+ logger.error("The request failed due to service quota exceeded: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("3. Create a Neptune DB Instance");
+ logger.info("In this step, we add a new database instance to the Neptune cluster");
+ waitForInputToContinue(scanner);
+ try {
+ neptuneActions.createDBInstanceAsync(dbInstanceId, dbClusterId).join();
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ServiceQuotaExceededException) {
+ logger.error("The request failed due to service quota exceeded: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("4. Check the status of the Neptune DB Instance");
+ logger.info("""
+ In this step, we will wait until the DB instance
+ becomes available. This may take around 10 minutes.
+ """);
+ waitForInputToContinue(scanner);
+ try {
+ neptuneActions.checkInstanceStatus(dbInstanceId, "available").join();
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ logger.error("An unexpected error occurred.", cause);
+ return;
+ }
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("5.Show Neptune Cluster details");
+ waitForInputToContinue(scanner);
+ try {
+ neptuneActions.describeDBClustersAsync(clusterName).join();
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ResourceNotFoundException) {
+ logger.error("The request failed due to the resource not found: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("6. Stop the Amazon Neptune cluster");
+ logger.info("""
+ Once stopped, this step polls the status
+ until the cluster is in a stopped state.
+ """);
+ waitForInputToContinue(scanner);
+ try {
+ neptuneActions.stopDBClusterAsync(dbClusterId);
+ neptuneActions.waitForClusterStatus(dbClusterId, "stopped");
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ResourceNotFoundException) {
+ logger.error("The request failed due to the resource not found: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("7. Start the Amazon Neptune cluster");
+ logger.info("""
+ Once started, this step polls the clusters
+ status until it's in an available state.
+ We will also poll the instance status.
+ """);
+ waitForInputToContinue(scanner);
+ try {
+ neptuneActions.startDBClusterAsync(dbClusterId);
+ neptuneActions.waitForClusterStatus(dbClusterId, "available");
+ neptuneActions.checkInstanceStatus(dbInstanceId, "available").join();
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ResourceNotFoundException) {
+ logger.error("The request failed due to the resource not found: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info("8. Delete the Neptune Assets");
+ logger.info("Would you like to delete the Neptune Assets? (y/n)");
+ String delAns = scanner.nextLine().trim();
+ if (delAns.equalsIgnoreCase("y")) {
+ logger.info("You selected to delete the Neptune assets.");
+ try {
+ neptuneActions.deleteNeptuneResourcesAsync(dbInstanceId, clusterName, subnetGroupName);
+ } catch (CompletionException ce) {
+ Throwable cause = ce.getCause();
+ if (cause instanceof ResourceNotFoundException) {
+ logger.error("The request failed due to the resource not found: {}", cause.getMessage());
+ } else {
+ logger.error("An unexpected error occurred.", cause);
+ }
+ return;
+ }
+ } else {
+ logger.info("You selected not to delete Neptune assets.");
+ }
+ waitForInputToContinue(scanner);
+ logger.info(DASHES);
+
+ logger.info(DASHES);
+ logger.info(
+ """
+ Thank you for checking out the Amazon Neptune Service Use demo. We hope you
+ learned something new, or got some inspiration for your own apps today.
+ For more AWS code examples, have a look at:
+ https://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html
+ """);
+ logger.info(DASHES);
+ }
+
+ private static void waitForInputToContinue(Scanner scanner) {
+ while (true) {
+ logger.info("");
+ logger.info("Enter 'c' followed by to continue:");
+ String input = scanner.nextLine();
+
+ if (input.trim().equalsIgnoreCase("c")) {
+ logger.info("Continuing with the program...");
+ logger.info("");
+ break;
+ } else {
+ logger.info("Invalid input. Please try again.");
+ }
+ }
+ }
+}
+// snippet-end:[neptune.java2.scenario.main]
\ No newline at end of file
diff --git a/javav2/example_code/neptune/src/main/resources/log4j2.xml b/javav2/example_code/neptune/src/main/resources/log4j2.xml
new file mode 100644
index 00000000000..914470047e7
--- /dev/null
+++ b/javav2/example_code/neptune/src/main/resources/log4j2.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/javav2/example_code/neptune/src/test/java/NeptuneTest.java b/javav2/example_code/neptune/src/test/java/NeptuneTest.java
new file mode 100644
index 00000000000..15fe4a8a4d7
--- /dev/null
+++ b/javav2/example_code/neptune/src/test/java/NeptuneTest.java
@@ -0,0 +1,106 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+import com.example.neptune.scenerio.NeptuneActions;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+@TestInstance(TestInstance.Lifecycle.PER_METHOD)
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+public class NeptuneTest {
+ private static String subnetGroupName = "neptuneSubnetGroupTest" ;
+ private static String clusterName = "neptuneClusterTest" ;
+ private static String dbInstanceId = "neptuneDBTest" ;
+ private static NeptuneActions neptuneActions = new NeptuneActions();
+ private static String dbClusterId = "";
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(1)
+ public void testCreateSubnetGroup() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.createSubnetGroupAsync(subnetGroupName).join();
+ });
+ System.out.println("Test 1 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(2)
+ public void testCreateCluster() {
+ assertDoesNotThrow(() -> {
+ dbClusterId = neptuneActions.createDBClusterAsync(clusterName).join();
+ assertFalse(dbClusterId.trim().isEmpty(), "DB Cluster ID should not be empty");
+ });
+ System.out.println("Test 2 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(3)
+ public void testCreateDBInstance() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.createDBInstanceAsync(dbInstanceId, dbClusterId).join();
+ });
+ System.out.println("Test 3 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(4)
+ public void testCheckInstance() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.checkInstanceStatus(dbInstanceId, "available").join();
+ });
+ System.out.println("Test 4 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(5)
+ public void testDescribeDBCluster() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.describeDBClustersAsync(clusterName).join();
+ });
+ System.out.println("Test 5 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(6)
+ public void testStopDBCluster() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.stopDBClusterAsync(dbClusterId);
+ neptuneActions.waitForClusterStatus(dbClusterId,"stopped");
+ });
+ System.out.println("Test 6 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(7)
+ public void testStartDBCluster() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.startDBClusterAsync(dbClusterId);
+ neptuneActions.waitForClusterStatus(dbClusterId,"available");
+ neptuneActions.checkInstanceStatus(dbInstanceId, "available").join();
+ });
+ System.out.println("Test 7 passed");
+ }
+
+ @Test
+ @Tag("IntegrationTest")
+ @Order(8)
+ public void testDeleteResources() {
+ assertDoesNotThrow(() -> {
+ neptuneActions.deleteNeptuneResourcesAsync(dbInstanceId, clusterName, subnetGroupName);
+ });
+ System.out.println("Test 8 passed");
+ }
+}
diff --git a/javav2/usecases/creating_neptune_lambda/README.md b/javav2/usecases/creating_neptune_lambda/README.md
new file mode 100644
index 00000000000..e91bb8e63ae
--- /dev/null
+++ b/javav2/usecases/creating_neptune_lambda/README.md
@@ -0,0 +1,339 @@
+# Accessing Neptune Graph Data from Lambda in a VPC Using the AWS SDK for Java
+
+## Overview
+
+| Heading | Description |
+| ----------- | ----------- |
+| Description | Discusses how to develop an AWS Lambda function that queries Amazon Neptune data within the VPC using the AWS SDK for Java (v2). |
+| Audience | Developer (intermediate) |
+| Required skills | Java, Maven |
+
+This guide provides a step-by-step walkthrough for creating and deploying an AWS Lambda function that queries an Amazon Neptune graph database using the Neptune Data API.
+
+Amazon Neptune is a fully managed graph database service designed to operate within a Virtual Private Cloud (VPC). Because of this, any Lambda function that needs to access Neptune must also run inside the same VPC and be granted appropriate network and IAM permissions. External access is not supported.
+
+To ensure secure and reliable communication between Lambda and Neptune, you’ll configure key AWS infrastructure components, including VPC subnets, security groups, and IAM roles. This guide covers all necessary setup and configuration tasks to help you successfully connect your Lambda function to Neptune using the Neptune Data API.
+
+**Note**: Lambda is a compute service that you can use to run code without provisioning or managing servers. You can create Lambda functions in various programming languages. For more information about Lambda, see
+[What is AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html).
+
+#### Topics
++ Prerequisites
++ Set Up the Amazon Neptune Cluster and VPC
++ Create an AWS Identity and Access Management (IAM) role that is used to execute Lambda functions
++ Create an IntelliJ project
++ Add the POM dependencies to your project
++ Create a Lambda function by using the Lambda runtime API
++ Package the project that contains the Lambda function
++ Deploy the Lambda function
+
+## Prerequisites
+To follow along with this tutorial, you need the following:
++ An Amazon Neptune DB instance in a VPC. You can get this by running the Neptune Basics scenario located in AWS Code Library.
++ A security group that allows traffic from Lambda to Neptune (typically on port 8182).
++ An AWS account with proper credentials.
++ AWS CLI configured with permissions for Lambda, IAM, EC2 (VPC), S3, Neptune. For information about setting up AWS CLI, see [Setting up the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html)
++ A Java IDE. (For this tutorial, the IntelliJ IDE is used.)
++ Java 21 JDK.
++ Maven 3.6 or higher.
+
+### Important
+
++ The AWS services included in this document are included in the [AWS Free Tier](https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc).
++ This code has not been tested in all AWS Regions. Some AWS services are available only in specific Regions. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
++ Running this code might result in charges to your AWS account.
++ Be sure to delete all of the resources that you create during this tutorial so that you won't be charged.
+
+## Set Up the Amazon Neptune Cluster and VPC
+
+Amazon Neptune requires a VPC with at least two subnets in different Availability Zones (AZs) to ensure high availability and fault tolerance.
+
+If you're unsure which VPC or subnets to use, you can easily generate the required resources by running the Amazon Neptune Basics scenario from the AWS Code Library. This setup will provision:
+
+ - A suitable VPC with subnets in multiple AZs
+
+ - A Neptune DB cluster and instance
+
+ - All necessary networking and security configurations
+
+This is a quick way to get a working Neptune environment that you can immediately use for this use case.
+
+### Add data to the database
+
+Once your Amazon Neptune cluster and database are set up, the next step is to load data into it. This data will be accessed by the AWS Lambda function created as part of this guide.
+
+Amazon Neptune supports multiple data loading methods, including bulk loading from Amazon S3, Gremlin and SPARQL queries, and integration with AWS Database Migration Service.
+
+To efficiently populate your Neptune database, use the Neptune bulk loader, which imports data stored in Amazon S3 using formats such as CSV, RDF, or Turtle.
+For information on how to add data to the Amazon Neptune database, see [Loading Data into a Neptune DB Instance](https://docs.aws.amazon.com/neptune/latest/userguide/bulk-load-data.html).
+
+## Create the Lambda Execution IAM Role
+
+### Create trust policy JSON file
+
+You need to create the trust polciy used for this IAM role. Name the file **trust-policy-lambda.json**.
+
+```json
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": { "Service": "lambda.amazonaws.com" },
+ "Action": "sts:AssumeRole"
+ }
+ ]
+}
+
+```
+
+### Create the lambda-execution-role role
+
+You can create the **lambda-execution-role** role by using this CLI command.
+
+```bash
+aws iam create-role \
+ --role-name lambda-execution-role \
+ --assume-role-policy-document file://trust-policy-lambda.json
+```
+### Attach the required managed policies
+
+Run each of the following AWS CLI commands to attach the necessary managed policies to the Lambda execution role:
+
+```bash
+aws iam attach-role-policy \
+ --role-name lambda-execution-role \
+ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
+
+aws iam attach-role-policy \
+ --role-name lambda-execution-role \
+ --policy-arn arn:aws:iam::aws:policy/AWSNeptuneFullAccess
+
+aws iam attach-role-policy \
+ --role-name lambda-execution-role \
+ --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
+
+aws iam attach-role-policy \
+ --role-name lambda-execution-role \
+ --policy-arn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess
+
+```
+
+
+## Create an IntelliJ project
+
+1. In the IntelliJ IDE, choose **File**, **New**, **Project**.
+
+2. In the **New Project** dialog box, choose **Maven**, and then choose **Next**.
+
+3. For **GroupId**, enter **org.example**.
+
+4. For **ArtifactId**, enter **NeptuneLambda**.
+
+5. Choose **Next**.
+
+6. Choose **Finish**.
+
+## Add the POM dependencies to your project
+
+At this point, you have a new project named **NeptuneLambda**. Make sure that your project's **pom.xml** file looks like the POM file in this Github repository.
+
+## Create a Lambda function by using the Lambda runtime Java API
+
+Use the Lambda runtime Java API to create the Java class that defines the Lamdba function. In this example, there is one Java class for the Lambda function named **NeptuneLambdaHandler**.
+
+
+### NeptuneLambdaHandler class
+
+This Java code represents the **NeptuneLambdaHandler** class. The class use the Neptune Data Client API to query data from the Neptune graph database.
+
+```java
+package org.example;
+
+import com.amazonaws.services.lambda.runtime.Context;
+import com.amazonaws.services.lambda.runtime.LambdaLogger;
+import com.amazonaws.services.lambda.runtime.RequestHandler;
+import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
+import software.amazon.awssdk.http.apache.ApacheHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.neptunedata.NeptunedataClient;
+import software.amazon.awssdk.services.neptunedata.model.ExecuteGremlinQueryRequest;
+import software.amazon.awssdk.services.neptunedata.model.ExecuteGremlinQueryResponse;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.net.URI;
+import java.time.Duration;
+import java.util.Map;
+
+public class NeptuneLambdaHandler implements RequestHandler