From fc8f09eaf37461dba35e47c19fa644ac1d08693c Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 09:48:02 -0400 Subject: [PATCH 1/9] add the OpenSearch Basics scenario --- .doc_gen/metadata/opensearch_metadata.yaml | 81 +++++ .../opensearch_scenario/README.md | 51 +++ .../opensearch_scenario/SPECIFICATION.md | 303 ++++++++++++++++ javav2/example_code/opensearch/pom.xml | 34 +- .../com/example/search/HelloOpenSearch.java | 65 ++++ .../search/scenario/OpenSearchActions.java | 333 ++++++++++++++++++ .../search/scenario/OpenSearchScenario.java | 323 +++++++++++++++++ .../opensearch/src/main/resources/log4j2.xml | 15 + .../src/test/java/OpenSearchTest.java | 144 ++++++-- 9 files changed, 1320 insertions(+), 29 deletions(-) create mode 100644 basics_scenarios/opensearch_scenario/README.md create mode 100644 basics_scenarios/opensearch_scenario/SPECIFICATION.md create mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java create mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchActions.java create mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchScenario.java create mode 100644 javav2/example_code/opensearch/src/main/resources/log4j2.xml diff --git a/.doc_gen/metadata/opensearch_metadata.yaml b/.doc_gen/metadata/opensearch_metadata.yaml index 57d67c31eda..8dffa93f35a 100644 --- a/.doc_gen/metadata/opensearch_metadata.yaml +++ b/.doc_gen/metadata/opensearch_metadata.yaml @@ -65,6 +65,58 @@ opensearch_ListDomainNames: - opensearch.java2.list_domains.main services: opensearch: {ListDomainNames} +opensearch_ListTags: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/opensearch + sdkguide: + excerpts: + - description: + snippet_tags: + - opensearch.java2.add_tags.main + services: + opensearch: {ListTags} +opensearch_AddTags: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/opensearch + sdkguide: + excerpts: + - description: + snippet_tags: + - opensearch.java2.add_tags.main + services: + opensearch: {AddTags} +opensearch_ChangeProgress: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/opensearch + sdkguide: + excerpts: + - description: + snippet_tags: + - opensearch.java2.change_process.main + services: + opensearch: {ChangeProgress} +opensearch_DescribeDomain: + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/opensearch + sdkguide: + excerpts: + - description: + snippet_tags: + - opensearch.java2.update_domain.main + services: + opensearch: {DescribeDomain} opensearch_UpdateDomainConfig: languages: Kotlin: @@ -87,3 +139,32 @@ opensearch_UpdateDomainConfig: - opensearch.java2.update_domain.main services: opensearch: {UpdateDomainConfig} +opensearch_Scenario: + title: Learn core operations for &ESlong; using an &AWS; SDK + title_abbrev: Learn &ES; core operations + synopsis_list: + - Create an &ES; domain. + - Provides detailed information about a specific &ES; domain. + - Lists all the &ES; domains owned by the account. + - Waits until the &ES; domain's change status reaches a completed state. + - Modifies the configuration of an existing &ES; domain. + - Add a tag to the &ES; domain. + - Lists the tags associated with an &ES; domain. + - Removes tags from an &ES; domain. + - Deletes the &ES; domain. + category: Basics + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/batch + sdkguide: + excerpts: + - description: Run an interactive scenario demonstrating &ES; features. + snippet_tags: + - opensearch.java2.scenario.main + - description: A wrapper class for &ES; SDK methods. + snippet_tags: + - opensearch.java2.actions.main + services: + opensearch: {CreateDomain, DeleteDomain, DescribeDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainChangeProgress, AddTags, ListTags} diff --git a/basics_scenarios/opensearch_scenario/README.md b/basics_scenarios/opensearch_scenario/README.md new file mode 100644 index 00000000000..8308cb63ba0 --- /dev/null +++ b/basics_scenarios/opensearch_scenario/README.md @@ -0,0 +1,51 @@ +# Amazon OpenSearch Service Basic Scenario + +## Overview + + This Amazon OpenSearch Service (Amazon ECR) basic scenario demonstrates how to interact with the Amazon OpenSearch service using an AWS SDK. The scenario covers various operations such as creating an OpenSearch domain, modifying a domain, waiting for changes to the domain to enter a complete state, and so on. + + Here are the top five service operations this scenario covers. + +**Create an Amazon OpenSearch Domain**: + - Description: This operation creates a new Amazon OpenSearch domain, which is a managed instance of the OpenSearch engine. + +2. **Describe the Amazon OpenSearch Domain**: + - Description: This operation retrieves information about the specified Amazon OpenSearch domain. + - The method `describeDomain(domainName)` is called to obtain the Amazon Resource Name (ARN) of the specified OpenSearch domain. + +3. **List the Domains in Your Account**: + - Description: This operation lists all the Amazon OpenSearch domains in the current AWS account. + - The method `listAllDomains()` is called to retrieve a list of all the OpenSearch domains available in the account. + +4. **Wait until the Domain's Change Status Reaches a Completed State**: + - Description: This operation waits until the change status of the specified Amazon OpenSearch domain reaches a completed state. + - When making changes to an OpenSearch domain, such as scaling the number of data nodes or updating the OpenSearch version, the domain goes through a change process. This method, `domainChangeProgress(domainName)`, waits until the change status of the specified domain reaches a completed state, which can take several minutes to several hours, depending on the complexity of the change and the current load on the OpenSearch service. + Note this operation may take up to 20 minutes. + +5. **Modify the Domain**: + - Description: This operation modifies the cluster configuration of the specified Amazon OpenSearch domain, such as the instance count. + - The flexibility to modify the OpenSearch domain's configuration is particularly useful when the data or usage patterns change over time, as you can easily scale the domain to meet the new requirements without having to recreate the entire domain. + - The method `updateSpecificDomain(domainName)` is called to update the configuration of the specified OpenSearch domain. + +Note: These steps are not the complete program, but summarizes the 5 high-level steps. See the Eng Spec for a complete listing of operations. + +### Resources + +This scenario does not require any additional AWS resources to run. + + +## Implementations + +This scenario example will be implemented in the following languages: + +- Java +- Python +- JavaScript + +## Additional reading + +- [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 diff --git a/basics_scenarios/opensearch_scenario/SPECIFICATION.md b/basics_scenarios/opensearch_scenario/SPECIFICATION.md new file mode 100644 index 00000000000..4fc400f8d36 --- /dev/null +++ b/basics_scenarios/opensearch_scenario/SPECIFICATION.md @@ -0,0 +1,303 @@ +# Amazon OpenSearch Service Scenario Specification + +## Overview +This SDK Basics scenario demonstrates how to interact with Amazon OpenSearch using the AWS SDK. It demonstrates various tasks such as creating a domain, modifying a domain, getting the status of a change request, and so on. Finally this scenario demonstrates how to clean up resources. Its purpose is to demonstrate how to get up and running with Amazon OpenSearch and the AWS SDK. + +## Resources +This Basics scenario does not have a depedency on any AWS resources. + +## Hello Amazon OpenSearch +This program is intended for users not familiar with the Amazon OpenSearch SDK to easily get up and running. The logic is to show use of ` +`listVersions()`. + +## Scenario Program Flow +The Amazon OpenSearch Basics scenario executes the following operations. + +1. **Create an Amazon OpenSearch Domain**: +<<<<<<< HEAD + - Description: This operation creates a new Amazon OpenSearch domain, which is a managed instance of the OpenSearch engine. Invoke the `createDomain` method. + - Exception Handling: Check to see if a `OpenSearchException` is thrown. We tested as group and `ResourceExistsException` is not thrown. Display the message and end the program. +======= + - Description: This operation creates a new Amazon OpenSearch domain, which is a managed instance of the OpenSearch engine. +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +2. **Describe the Amazon OpenSearch Domain**: + - Description: This operation retrieves information about the specified Amazon OpenSearch domain. + - The method `describeDomain(domainName)` is called to obtain the Amazon Resource Name (ARN) of the specified OpenSearch domain. +<<<<<<< HEAD + - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +3. **List the Domains in Your Account**: + - Description: This operation lists all the Amazon OpenSearch domains in the current AWS account. + - The method `listAllDomains()` is called to retrieve a list of all the OpenSearch domains available in the account. +<<<<<<< HEAD + - Exception Handling: Check to see if a `OpenSearchException` is thrown. There are not many other useful exceptions for this specific call. If so, display the message and end the program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +4. **Wait until the Domain's Change Status Reaches a Completed State**: + - Description: This operation waits until the change status of the specified Amazon OpenSearch domain reaches a completed state. + - When making changes to an OpenSearch domain, such as scaling the number of data nodes or updating the OpenSearch version, the domain goes through a change process. This method, `domainChangeProgress(domainName)`, waits until the change status of the specified domain reaches a completed state, which can take several minutes to several hours, depending on the complexity of the change and the current load on the OpenSearch service. +<<<<<<< HEAD + - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. + Note this operation may take up to 20 minutes (I am observering that uses the Java SDK). +======= + Note this operation may take up to 20 minutes. +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +5. **Modify the Domain**: + - Description: This operation modifies the cluster configuration of the specified Amazon OpenSearch domain, such as the instance count. + - The flexibility to modify the OpenSearch domain's configuration is particularly useful when the data or usage patterns change over time, as you can easily scale the domain to meet the new requirements without having to recreate the entire domain. + - The method `updateSpecificDomain(domainName)` is called to update the configuration of the specified OpenSearch domain. +<<<<<<< HEAD + - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +6. **Wait until the Domain's Change Status Reaches a Completed State (Again)**: + - Description: This operation is similar to the previous "Wait until the Domain's Change Status Reaches a Completed State" operation, but it is called after the domain modification to ensure the changes have been fully applied. + - The method `domainChangeProgress(domainName)` is called again to wait until the change status of the specified domain reaches a completed state. +<<<<<<< HEAD + - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +7. **Tag the Domain**: + - Description: This operation adds tags to the specified Amazon OpenSearch domain. + - Tags are key-value pairs that can be used to categorize and filter OpenSearch domains. They can be useful for tracking costs by grouping expenses for similarly tagged resources. + - The method `addDomainTags(arn)` is called to add tags to the OpenSearch domain identified by the provided ARN. +<<<<<<< HEAD + - Exception Handling: Check to see if a `OpenSearchException` is thrown. There are not many other useful exceptions for this specific call. If so, display the message and end the program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +8. **List Domain Tags**: + - Description: This operation lists the tags associated with the specified Amazon OpenSearch domain. + - The method `listDomainTags(arn)` is called to retrieve the tags for the OpenSearch domain identified by the provided ARN. +<<<<<<< HEAD + - Exception Handling: Check to see if a `OpenSearchException` is thrown. There are not many other useful exceptions for this specific call. If so, display the message and end the program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + +9. **Delete the Amazon OpenSearch Domain**: + - Description: This operation deletes the specified Amazon OpenSearch domain. + - The method `deleteSpecificDomain(domainName)` is called to delete the OpenSearch domain with the specified name." +<<<<<<< HEAD + - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. +======= +>>>>>>> 150c02cfd (added OpenSearch Basics Scenario) + + +### Program execution +The following shows the output of the Amazon OpenSearch program in the console. + +``` +These operations exposed by the OpenSearch Service client is focused on managing the OpenSearch Service domains +and their configurations, not the data within the domains (such as indexing or querying documents). +For document management, you typically interact directly with the OpenSearch REST API or use other libraries, +such as the OpenSearch Java client. + +Lets get started... + + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +1. Create an Amazon OpenSearch domain +An Amazon OpenSearch domain is a managed instance of the OpenSearch engine, +which is an open-source search and analytics engine derived from Elasticsearch. +An OpenSearch domain is essentially a cluster of compute resources and storage that hosts +one or more OpenSearch indexes, enabling you to perform full-text searches, data analysis, and +visualizations. + + +Enter 'c' followed by to continue: +c +Continuing with the program... + +Sending domain creation request... +SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". +SLF4J: Defaulting to no-operation (NOP) logger implementation +SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. +Domain status is DomainStatus(DomainId=814548047983/test-domain-1725641905678, DomainName=test-domain-1725641905678, AnonymousAuthEnabled=false), AutoTuneOptions=AutoTuneOptionsOutput(State=DISABLED, UseOffPeakWindow=false), ChangeProgressDetails=ChangeProgressDetails(ChangeId=9ccf4ee9-b924-4615-82b3-3cc5564abb6a), OffPeakWindowOptions=OffPeakWindowOptions(Enabled=true, OffPeakWindow=OffPeakWindow(WindowStartTime=WindowStartTime(Hours=2, Minutes=0))), SoftwareUpdateOptions=SoftwareUpdateOptions(AutoSoftwareUpdateEnabled=false)) +Domain Id is 814548047983/test-domain-1725641905678 +The Id of the domain is 814548047983/test-domain-1725641905678 + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +2. Describe the Amazon OpenSearch domain + +Enter 'c' followed by to continue: +c +Continuing with the program... + +Domain endpoint is: null +ARN: arn:aws:es:us-east-1:814548047983:domain/test-domain-1725641905678 +Engine version OpenSearch_1.0 + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +3. List the domains in your account + +Enter 'c' followed by to continue: +c +Continuing with the program... + +Domain name is test-domain-1725493654227 +Domain name is test-domain-1725565012971 +Domain name is test-domain-1725493860109 +Domain name is test-domain-1725641905678 +Domain name is test-domain-1725493726160 + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +4. Wait until the domain's change status reaches a completed state +In the following method call, the clock counts up until the domain's change status reaches a completed state. + +Roughly, the time it takes for an OpenSearch domain's change status to reach a completed state can range +from a few minutes to several hours, depending on the complexity of the change and the current load on +the OpenSearch service. In general, simple changes, such as scaling the number of data nodes or +updating the OpenSearch version, may take 10-30 minutes, + + +Enter 'c' followed by to continue: +c +Continuing with the program... + +OpenSearch domain state: PROCESSING | Time Elapsed: 19:29 +OpenSearch domain status: Completed + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +5. Modify the domain +You can modify the cluster configuration, such as the instance count, without having to manually +manage the domain's settings. This flexibility is particularly useful when your data or usage patterns +change over time, as you can easily scale the OpenSearch domain to meet the new requirements without +having to recreate the entire domain. + + +Enter 'c' followed by to continue: +c +Continuing with the program... + +Sending domain update request... +Domain update response from Amazon OpenSearch Service: +UpdateDomainConfigResponse(DomainConfig=DomainConfig(EngineVersion=VersionStatus(Options=OpenSearch_1.0, Status=OptionStatus(CreationDate=2024-09-06T16:58:34.731Z, UpdateDate=2024-09-06T17:19:11.915Z, UpdateVersion=10, State=Active, PendingDeletion=false)), ClusterConfig=ClusterConfigStatus(Options=ClusterConfig(InstanceType=t2.small.search, InstanceCount=3, DedicatedMasterEnabled=true, ZoneAwarenessEnabled=false, DedicatedMasterType=t2.small.search, DedicatedMasterCount=3, WarmEnabled=false, ColdStorageOptions=ColdStorageOptions(Enabled=false), MultiAZWithStandbyEnabled=false), Status=OptionStatus(CreationDate=2024-09-06T16:58:34.743Z, UpdateDate=2024-09-06T17:33:27.638Z, UpdateVersion=11, State=Processing, PendingDeletion=false)), EBSOptions=EBSOptionsStatus(Options=EBSOptions(EBSEnabled=true, VolumeType=gp2, VolumeSize=10), Status=OptionStatus(CreationDate=2024-09-06T16:58:34.733Z, UpdateDate=2024-09-06T17:19:11.919Z, UpdateVersion=10, State=Active, PendingDeletion=false)), AccessPolicies=AccessPoliciesStatus(Options=, Status=OptionStatus(CreationDate=2024-09-06T17:33:27.876Z, UpdateDate=2024-09-06T17:33:27.876Z, UpdateVersion=11, State=Active, PendingDeletion=false)), IPAddressType=IPAddressTypeStatus(Options=ipv4, Status=OptionStatus(CreationDate=2024-09-06T16:58:34.727Z, UpdateDate=2024-09-06T17:19:11.909Z, UpdateVersion=10, State=Active, PendingDeletion=false)), SnapshotOptions=SnapshotOptionsStatus(Options=SnapshotOptions(AutomatedSnapshotStartHour=0), Status=OptionStatus(CreationDate=2024-09-06T16:58:34.734Z, UpdateDate=2024-09-06T17:19:11.919Z, UpdateVersion=10, State=Active, PendingDeletion=false)), VPCOptions=VPCDerivedInfoStatus(Options=VPCDerivedInfo(), Status=OptionStatus(CreationDate=2024-09-06T17:33:27.876Z, UpdateDate=2024-09-06T17:33:27.876Z, UpdateVersion=11, State=Active, PendingDeletion=false)))) + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +6. Wait until the domain's change status reaches a completed state +In the following method call, the clock counts up until the domain's change status reaches a completed state. + + + +Enter 'c' followed by to continue: +c +Continuing with the program... + +OpenSearch domain state: PROCESSING | Time Elapsed: 10:42 +OpenSearch domain status: Completed + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +7. Tag the Domain +Tags let you assign arbitrary information to an Amazon OpenSearch Service domain so you can +categorize and filter on that information. A tag is a key-value pair that you define and +associate with an OpenSearch Service domain. You can use these tags to track costs by grouping +expenses for similarly tagged resources. + + +Enter 'c' followed by to continue: +c +Continuing with the program... + +Successfully added tags to the domain + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +8. List Domain tags + +Enter 'c' followed by to continue: +c +Continuing with the program... + +Tag key is instances +Tag value is m3.2xlarge +Tag key is service +Tag value is OpenSearch + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +9. Delete the Amazon OpenSearch + +Enter 'c' followed by to continue: +c +Continuing with the program... + +test-domain-1725641905678 was successfully deleted. +test-domain-1725641905678 has been deleted. + +Enter 'c' followed by to continue: +c +Continuing with the program... + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +This concludes the AWS OpenSearch Scenario +-------------------------------------------------------------------------------- + + +``` + +## SOS Tags + +The following table describes the metadata used in this Basics Scenario. + + +| action | metadata file | metadata key | +|--------------------------------|-----------------------------------|---------------------------------------- | +| `createDomain` | opensearch_metadata.yaml | opensearch_CreateDomain | +| `deleteDomain ` | opensearch_metadata.yaml | opensearch_DeleteDomain | +| `listDomainNames ` | opensearch_metadata.yaml | opensearch_ListDomainNames | +| `updateDomainConfig` | opensearch_metadata.yaml | opensearch_UpdateDomainConfig | +| `describeDomain` | opensearch_metadata.yaml | opensearch_DescribeDomain | +| `describeDomainChangeProgress` | opensearch_metadata.yaml | opensearch_ChangeProgress | +| `listDomainTags` | opensearch_metadata.yaml | opensearch_ListTags | +| `scenario` | opensearch_metadata.yaml | opensearch_Scenario | + diff --git a/javav2/example_code/opensearch/pom.xml b/javav2/example_code/opensearch/pom.xml index 0ca35d89a51..beee1197f62 100644 --- a/javav2/example_code/opensearch/pom.xml +++ b/javav2/example_code/opensearch/pom.xml @@ -35,7 +35,14 @@ software.amazon.awssdk bom - 2.21.20 + 2.27.22 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.23.1 pom import @@ -74,6 +81,31 @@ software.amazon.awssdk opensearch + + software.amazon.awssdk + netty-nio-client + + + software.amazon.awssdk + sso + + + software.amazon.awssdk + ssooidc + + + org.slf4j + slf4j-api + 2.0.13 + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + org.apache.commons commons-io diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java b/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java new file mode 100644 index 00000000000..b85a955e2f6 --- /dev/null +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java @@ -0,0 +1,65 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.search; + +// snippet-start:[opensearch.java2.create_domain.main] +// snippet-start:[opensearch.java2.create_domain.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient; +import software.amazon.awssdk.services.opensearch.OpenSearchClient; +import software.amazon.awssdk.services.opensearch.model.ClusterConfig; +import software.amazon.awssdk.services.opensearch.model.EBSOptions; +import software.amazon.awssdk.services.opensearch.model.ListVersionsRequest; +import software.amazon.awssdk.services.opensearch.model.ListVersionsResponse; +import software.amazon.awssdk.services.opensearch.model.VersionStatus; +import software.amazon.awssdk.services.opensearch.model.VolumeType; +import software.amazon.awssdk.services.opensearch.model.NodeToNodeEncryptionOptions; +import software.amazon.awssdk.services.opensearch.model.CreateDomainRequest; +import software.amazon.awssdk.services.opensearch.model.CreateDomainResponse; +import software.amazon.awssdk.services.opensearch.model.OpenSearchException; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +// snippet-end:[opensearch.java2.create_domain.import] + +/** + * 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 + */ +public class HelloOpenSearch { + public static void main(String[] args) { + try { + CompletableFuture future = listVersionsAsync(); + future.join(); + System.out.println("Versions listed successfully."); + } catch (RuntimeException e) { + System.err.println("Error occurred while listing versions: " + e.getMessage()); + } + } + + private static OpenSearchAsyncClient getAsyncClient() { + return OpenSearchAsyncClient.builder().build(); + } + + public static CompletableFuture listVersionsAsync() { + ListVersionsRequest request = ListVersionsRequest.builder() + .maxResults(10) + .build(); + + return getAsyncClient().listVersions(request).thenAccept(response -> { + List versionList = response.versions(); + for (String version : versionList) { + System.out.println("Version info: " + version); + } + }).exceptionally(ex -> { + // Handle the exception, or propagate it as a RuntimeException + throw new RuntimeException("Failed to list versions", ex); + }); + } +} +// snippet-end:[opensearch.java2.create_domain.main] diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchActions.java b/javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchActions.java new file mode 100644 index 00000000000..51ed3ae5c30 --- /dev/null +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchActions.java @@ -0,0 +1,333 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.search.scenario; + +// snippet-start:[opensearch.java2.actions.main] +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; +import software.amazon.awssdk.core.retry.RetryPolicy; +import software.amazon.awssdk.http.async.SdkAsyncHttpClient; +import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient; +import software.amazon.awssdk.services.opensearch.model.AddTagsRequest; +import software.amazon.awssdk.services.opensearch.model.AddTagsResponse; +import software.amazon.awssdk.services.opensearch.model.ClusterConfig; +import software.amazon.awssdk.services.opensearch.model.CreateDomainRequest; +import software.amazon.awssdk.services.opensearch.model.DeleteDomainRequest; +import software.amazon.awssdk.services.opensearch.model.DeleteDomainResponse; +import software.amazon.awssdk.services.opensearch.model.DescribeDomainChangeProgressRequest; +import software.amazon.awssdk.services.opensearch.model.DescribeDomainChangeProgressResponse; +import software.amazon.awssdk.services.opensearch.model.DescribeDomainRequest; +import software.amazon.awssdk.services.opensearch.model.DomainInfo; +import software.amazon.awssdk.services.opensearch.model.DomainStatus; +import software.amazon.awssdk.services.opensearch.model.EBSOptions; +import software.amazon.awssdk.services.opensearch.model.ListDomainNamesRequest; +import software.amazon.awssdk.services.opensearch.model.ListTagsRequest; +import software.amazon.awssdk.services.opensearch.model.ListTagsResponse; +import software.amazon.awssdk.services.opensearch.model.NodeToNodeEncryptionOptions; +import software.amazon.awssdk.services.opensearch.model.Tag; +import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigRequest; +import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigResponse; +import software.amazon.awssdk.services.opensearch.model.VolumeType; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class OpenSearchActions { + private static final Logger logger = LoggerFactory.getLogger(OpenSearchActions.class); + private static OpenSearchAsyncClient openSearchClientAsyncClient; + private static OpenSearchAsyncClient getAsyncClient() { + if (openSearchClientAsyncClient == 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)) + .retryPolicy(RetryPolicy.builder() + .numRetries(3) + .build()) + .build(); + + openSearchClientAsyncClient = OpenSearchAsyncClient.builder() + .region(Region.US_EAST_1) + .httpClient(httpClient) + .overrideConfiguration(overrideConfig) + .build(); + } + return openSearchClientAsyncClient; + } + + // snippet-start:[opensearch.java2.create_domain.main] + /** + * Creates a new OpenSearch domain asynchronously. + * @param domainName the name of the new OpenSearch domain to create + * @return a {@link CompletableFuture} containing the domain ID of the newly created domain + */ + public CompletableFuture createNewDomainAsync(String domainName) { + ClusterConfig clusterConfig = ClusterConfig.builder() + .dedicatedMasterEnabled(true) + .dedicatedMasterCount(3) + .dedicatedMasterType("t2.small.search") + .instanceType("t2.small.search") + .instanceCount(5) + .build(); + + EBSOptions ebsOptions = EBSOptions.builder() + .ebsEnabled(true) + .volumeSize(10) + .volumeType(VolumeType.GP2) + .build(); + + NodeToNodeEncryptionOptions encryptionOptions = NodeToNodeEncryptionOptions.builder() + .enabled(true) + .build(); + + CreateDomainRequest domainRequest = CreateDomainRequest.builder() + .domainName(domainName) + .engineVersion("OpenSearch_1.0") + .clusterConfig(clusterConfig) + .ebsOptions(ebsOptions) + .nodeToNodeEncryptionOptions(encryptionOptions) + .build(); + logger.info("Sending domain creation request..."); + return getAsyncClient().createDomain(domainRequest) + .handle( (createResponse, throwable) -> { + if (createResponse != null) { + logger.info("Domain status is {}", createResponse.domainStatus().changeProgressDetails().configChangeStatusAsString()); + logger.info("Domain Id is {}", createResponse.domainStatus().domainId()); + return createResponse.domainStatus().domainId(); + } + throw new RuntimeException("Failed to create domain", throwable); + }); + } + // snippet-end:[opensearch.java2.create_domain.main] + + // snippet-start:[opensearch.java2.delete_domain.main] + /** + * Deletes a specific domain asynchronously. + * @param domainName the name of the domain to be deleted + * @return a {@link CompletableFuture} that completes when the domain has been deleted + * or throws a {@link RuntimeException} if the deletion fails + */ + public CompletableFuture deleteSpecificDomainAsync(String domainName) { + DeleteDomainRequest domainRequest = DeleteDomainRequest.builder() + .domainName(domainName) + .build(); + + // Delete domain asynchronously + return getAsyncClient().deleteDomain(domainRequest) + .whenComplete((response, exception) -> { + if (exception != null) { + throw new RuntimeException("Failed to delete the domain: " + domainName, exception); + } + }); + } + // snippet-end:[opensearch.java2.delete_domain.main] + + // snippet-start:[opensearch.java2.describe_domain.main] + /** + * Describes the specified domain asynchronously. + * + * @param domainName the name of the domain to describe + * @return a {@link CompletableFuture} that completes with the ARN of the domain + * @throws RuntimeException if the domain description fails + */ + public CompletableFuture describeDomainAsync(String domainName) { + DescribeDomainRequest request = DescribeDomainRequest.builder() + .domainName(domainName) + .build(); + + return getAsyncClient().describeDomain(request) + .handle((response, exception) -> { // Handle both response and exception + if (exception != null) { + throw new RuntimeException("Failed to describe domain", exception); + } + DomainStatus domainStatus = response.domainStatus(); + String endpoint = domainStatus.endpoint(); + String arn = domainStatus.arn(); + String engineVersion = domainStatus.engineVersion(); + logger.info("Domain endpoint is: " + endpoint); + logger.info("ARN: " + arn); + System.out.println("Engine version: " + engineVersion); + + return arn; // Return ARN when successful + }); + } + // snippet-end:[opensearch.java2.describe_domain.main] + + // snippet-start:[opensearch.java2.list_domains.main] + /** + * Asynchronously lists all the domains in the current AWS account. + * @return a {@link CompletableFuture} that, when completed, contains a list of {@link DomainInfo} objects representing + * the domains in the account. + * @throws RuntimeException if there was a failure while listing the domains. + */ + public CompletableFuture> listAllDomainsAsync() { + ListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder() + .engineType("OpenSearch") + .build(); + + return getAsyncClient().listDomainNames(namesRequest) + .handle((response, exception) -> { + if (exception != null) { + throw new RuntimeException("Failed to list all domains", exception); + } + return response.domainNames(); // Return the list of domain names on success + }); + } + // snippet-end:[opensearch.java2.list_domains.main] + + // snippet-start:[opensearch.java2.update_domain.main] + /** + * Updates the configuration of a specific domain asynchronously. + * @param domainName the name of the domain to update + * @return a {@link CompletableFuture} that represents the asynchronous operation of updating the domain configuration + */ + public CompletableFuture updateSpecificDomainAsync(String domainName) { + ClusterConfig clusterConfig = ClusterConfig.builder() + .instanceCount(3) + .build(); + + UpdateDomainConfigRequest updateDomainConfigRequest = UpdateDomainConfigRequest.builder() + .domainName(domainName) + .clusterConfig(clusterConfig) + .build(); + + return getAsyncClient().updateDomainConfig(updateDomainConfigRequest) + .whenComplete((response, exception) -> { + if (exception != null) { + throw new RuntimeException("Failed to update the domain configuration", exception); + } + // Handle success if needed (e.g., logging or additional actions) + }); + } + // snippet-end:[opensearch.java2.update_domain.main] + + // snippet-start:[opensearch.java2.change_process.main] + /** + * Asynchronously checks the progress of a domain change operation in Amazon OpenSearch Service. + * @param domainName the name of the OpenSearch domain to check the progress for + * @return a {@link CompletableFuture} that completes when the domain change operation is completed + */ + public CompletableFuture domainChangeProgressAsync(String domainName) { + DescribeDomainChangeProgressRequest request = DescribeDomainChangeProgressRequest.builder() + .domainName(domainName) + .build(); + + return CompletableFuture.runAsync(() -> { + boolean isCompleted = false; + long startTime = System.currentTimeMillis(); + + while (!isCompleted) { + try { + // Handle the async client call using `join` to block synchronously for the result + DescribeDomainChangeProgressResponse response = getAsyncClient() + .describeDomainChangeProgress(request) + .handle((resp, ex) -> { + if (ex != null) { + throw new RuntimeException("Failed to check domain progress", ex); + } + return resp; + }).join(); + + String state = response.changeProgressStatus().statusAsString(); // Get the status as string + + if ("COMPLETED".equals(state)) { + logger.info("\nOpenSearch domain status: Completed"); + isCompleted = true; + } else { + for (int i = 0; i < 5; i++) { + long elapsedTimeInSeconds = (System.currentTimeMillis() - startTime) / 1000; + String formattedTime = String.format("%02d:%02d", elapsedTimeInSeconds / 60, elapsedTimeInSeconds % 60); + System.out.print("\rOpenSearch domain state: " + state + " | Time Elapsed: " + formattedTime + " "); + System.out.flush(); + Thread.sleep(1_000); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Thread was interrupted", e); + } + } + }); + } + // snippet-end:[opensearch.java2.change_process.main] + + // snippet-start:[opensearch.java2.add_tags.main] + /** + * Asynchronously adds tags to an Amazon OpenSearch Service domain. + * @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch Service domain to add tags to + * @return a {@link CompletableFuture} that completes when the tags have been successfully added to the domain, + * or throws a {@link RuntimeException} if the operation fails + */ + public CompletableFuture addDomainTagsAsync(String domainARN) { + Tag tag1 = Tag.builder() + .key("service") + .value("OpenSearch") + .build(); + + Tag tag2 = Tag.builder() + .key("instances") + .value("m3.2xlarge") + .build(); + + List tagList = new ArrayList<>(); + tagList.add(tag1); + tagList.add(tag2); + + AddTagsRequest addTagsRequest = AddTagsRequest.builder() + .arn(domainARN) + .tagList(tagList) + .build(); + + return getAsyncClient().addTags(addTagsRequest) + .whenComplete((response, exception) -> { + if (exception != null) { + throw new RuntimeException("Failed to add tags to the domain: " + domainARN, exception); + } else { + logger.info("Added Tags"); + } + }); + } + + // snippet-end:[opensearch.java2.add_tags.main] + + // snippet-start:[opensearch.java2.list_tags.main] + /** + * Asynchronously lists the tags associated with the specified Amazon Resource Name (ARN). + * @param arn the Amazon Resource Name (ARN) of the resource for which to list the tags + * @return a {@link CompletableFuture} that, when completed, will contain a list of the tags associated with the + * specified ARN + * @throws RuntimeException if there is an error listing the tags + */ + public CompletableFuture listDomainTagsAsync(String arn) { + ListTagsRequest tagsRequest = ListTagsRequest.builder() + .arn(arn) + .build(); + + return getAsyncClient().listTags(tagsRequest) + .whenComplete((response, exception) -> { + if (exception != null) { + throw new RuntimeException("Failed to list domain tags", exception); + } + + List tagList = response.tagList(); + for (Tag tag : tagList) { + logger.info("Tag key is " + tag.key()); + logger.info("Tag value is " + tag.value()); + } + }); + } + // snippet-end:[opensearch.java2.list_tags.main] +} +// snippet-end:[opensearch.java2.actions.main] + diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchScenario.java b/javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchScenario.java new file mode 100644 index 00000000000..fc458f1ed26 --- /dev/null +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/scenario/OpenSearchScenario.java @@ -0,0 +1,323 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.search.scenario; +// snippet-start:[opensearch.java2.scenario.main] +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.services.opensearch.model.*; +import java.util.List; +import java.util.Scanner; +import java.util.concurrent.CompletableFuture; + +public class OpenSearchScenario { + + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + + private static final Logger logger = LoggerFactory.getLogger(OpenSearchScenario.class); + static Scanner scanner = new Scanner(System.in); + + static OpenSearchActions openSearchActions = new OpenSearchActions(); + + public static void main(String[] args) throws Throwable { + logger.info(""" + Welcome to the Amazon OpenSearch Service Basics Scenario. + + Use the Amazon OpenSearch Service API to create, configure, and manage OpenSearch Service domains. + + The operations exposed by the AWS OpenSearch Service client are focused on managing the OpenSearch Service domains + and their configurations, not the data within the domains (such as indexing or querying documents). + For document management, you typically interact directly with the OpenSearch REST API or use other libraries, + such as the OpenSearch Java client (https://opensearch.org/docs/latest/clients/java/). + + Let's get started... + """); + waitForInputToContinue(scanner); + try { + runScenario(); + } catch (RuntimeException e) { + e.printStackTrace(); + } + } + + 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."); + } + } + } + + private static void runScenario() throws Throwable { + String currentTimestamp = String.valueOf(System.currentTimeMillis()); + String domainName = "test-domain-" + currentTimestamp; + + logger.info(DASHES); + logger.info("1. Create an Amazon OpenSearch domain"); + logger.info(""" + An Amazon OpenSearch domain is a managed instance of the OpenSearch engine, + which is an open-source search and analytics engine derived from Elasticsearch. + An OpenSearch domain is essentially a cluster of compute resources and storage that hosts + one or more OpenSearch indexes, enabling you to perform full-text searches, data analysis, and + visualizations. + + In this step, we'll initiate the creation of the domain. We'll check on the progress in a later step. + """); + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.createNewDomainAsync(domainName); + String domainId = future.join(); + logger.info("Domain successfully created with ID: {}", domainId); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + if (cause != null) { + if (cause instanceof OpenSearchException openSearchEx) { + logger.error("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.error("An unexpected error occurred: " + cause.getMessage(), cause); + } + } else { + logger.error("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("2. Describe the Amazon OpenSearch domain"); + logger.info("In this step, we get back the Domain ARN which is used in an upcoming step."); + waitForInputToContinue(scanner); + + String arn = ""; + try { + CompletableFuture future = openSearchActions.describeDomainAsync(domainName); + arn = future.join(); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + if (cause instanceof OpenSearchException openSearchEx) { + logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("3. List the domains in your account"); + waitForInputToContinue(scanner); + + try { + CompletableFuture> future = openSearchActions.listAllDomainsAsync(); + List domainInfoList = future.join(); + for (DomainInfo domain : domainInfoList) { + logger.info("Domain name is: " + domain.domainName()); + } + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + while (cause.getCause() != null && !(cause instanceof OpenSearchException)) { + cause = cause.getCause(); + } + if (cause instanceof OpenSearchException openSearchEx) { + logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + } + + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("4. Wait until the domain's change status reaches a completed state"); + logger.info(""" + In this step, we check on the change status of the domain that we initiated in Step 1. + Until we reach a COMPLETED state, we stay in a loop by sending a DescribeDomainChangeProgressRequest. + + The time it takes for a change to an OpenSearch domain to reach a completed state can range + from a few minutes to several hours. In this case the change is creating a new domain that we initiated in Step 1. + The time varies depending on the complexity of the change and the current load on + the OpenSearch service. In general, simple changes, such as scaling the number of data nodes or + updating the OpenSearch version, may take 10-30 minutes. + """); + + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.domainChangeProgressAsync(domainName); + future.join(); + logger.info("Domain change progress completed successfully."); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + while (cause.getCause() != null && !(cause instanceof ResourceNotFoundException)) { + cause = cause.getCause(); + } + if (cause instanceof ResourceNotFoundException resourceNotFoundException) { + logger.info("The specific AWS resource was not found: Error message: {}, Error code {}", resourceNotFoundException.awsErrorDetails().errorMessage(), resourceNotFoundException.awsErrorDetails().errorCode()); + + if (cause instanceof OpenSearchException ex) { + logger.info("An OpenSearch error occurred: Error message: " + ex.getMessage()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + } + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("5. Modify the domain"); + logger.info(""" + You can change your OpenSearch domain's settings, like the number of instances, without starting over from scratch. + This makes it easy to adjust your domain as your needs change, allowing you to scale up or + down quickly without recreating everything. + + We modify the domain in this step by changing the number of instances. + """); + + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.updateSpecificDomainAsync(domainName); + UpdateDomainConfigResponse updateResponse = future.join(); + logger.info("Domain update status: " + updateResponse.domainConfig().changeProgressDetails().configChangeStatusAsString()); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + if (cause instanceof OpenSearchException openSearchEx) { + logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("6. Wait until the domain's change status reaches a completed state"); + logger.info(""" + In this step, we poll the status until the domain's change status reaches a completed state. + """); + + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.domainChangeProgressAsync(domainName); + future.join(); + logger.info("Domain change progress completed successfully."); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + if (cause instanceof OpenSearchException ex) { + logger.info("EC2 error occurred: Error message: " +ex.getMessage()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("7. Tag the Domain"); + logger.info(""" + Tags let you assign arbitrary information to an Amazon OpenSearch Service domain so you can + categorize and filter on that information. A tag is a key-value pair that you define and + associate with an OpenSearch Service domain. You can use these tags to track costs by grouping + expenses for similarly tagged resources. + + In this scenario, we create tags with keys "service" and "instances". + """); + + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.addDomainTagsAsync(arn); + future.join(); + logger.info("Domain tags added successfully."); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + while (cause.getCause() != null && !(cause instanceof OpenSearchException)) { + cause = cause.getCause(); + } + if (cause instanceof OpenSearchException openSearchEx) { + logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + if (cause != null) { + if (cause instanceof OpenSearchException) { + logger.error("OpenSearch error occurred: Error message: " + cause.getMessage(), cause); + } else { + logger.error("An unexpected error occurred: " + cause.getMessage(), cause); + } + } else { + logger.error("An unexpected error occurred: " + rt.getMessage(), rt); + } + throw cause; + } + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("8. List Domain tags"); + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.listDomainTagsAsync(arn); + ListTagsResponse listTagsResponse = future.join(); + listTagsResponse.tagList().forEach(tag -> logger.info("Tag Key: " + tag.key() + ", Tag Value: " + tag.value())); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + while (cause.getCause() != null && !(cause instanceof OpenSearchException)) { + cause = cause.getCause(); + } + if (cause instanceof OpenSearchException openSearchEx) { + logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + + } + + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("9. Delete the domain"); + logger.info(""" + In this step, we'll delete the Amazon OpenSearch domain that we created in Step 1. + Deleting a domain will remove all data and configuration for that domain. + """); + + waitForInputToContinue(scanner); + + try { + CompletableFuture future = openSearchActions.deleteSpecificDomainAsync(domainName); + future.join(); + logger.info("Domain successfully deleted."); + } catch (RuntimeException rt) { + Throwable cause = rt.getCause(); + while (cause.getCause() != null && !(cause instanceof OpenSearchException)) { + cause = cause.getCause(); + } + if (cause instanceof OpenSearchException openSearchEx) { + logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode()); + } else { + logger.info("An unexpected error occurred: " + rt.getMessage()); + } + throw cause; + + } + waitForInputToContinue(scanner); + logger.info(DASHES); + + logger.info("Scenario complete!"); + } + } +// snippet-end:[opensearch.java2.scenario.main] diff --git a/javav2/example_code/opensearch/src/main/resources/log4j2.xml b/javav2/example_code/opensearch/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..4d900326937 --- /dev/null +++ b/javav2/example_code/opensearch/src/main/resources/log4j2.xml @@ -0,0 +1,15 @@ + + + + + + %msg%n + + + + + + + + + \ No newline at end of file diff --git a/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java b/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java index d8b999aadff..0f623d4a4c9 100644 --- a/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java +++ b/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java @@ -1,73 +1,161 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import com.example.search.scenario.OpenSearchActions; +import com.example.search.scenario.OpenSearchScenario; import org.junit.jupiter.api.*; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.opensearch.OpenSearchClient; import java.io.*; import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + import com.example.search.*; +import software.amazon.awssdk.services.opensearch.model.AddTagsResponse; +import software.amazon.awssdk.services.opensearch.model.DeleteDomainResponse; +import software.amazon.awssdk.services.opensearch.model.DomainInfo; +import software.amazon.awssdk.services.opensearch.model.ListTagsResponse; +import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigResponse; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class OpenSearchTest { - private static OpenSearchClient searchClient; + private static OpenSearchActions openSearchActions; private static String domainName = ""; + private static String arn; + @BeforeAll public static void setUp() throws IOException { - searchClient = OpenSearchClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - - try (InputStream input = OpenSearchTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests - prop.load(input); - domainName = "testdomain"; - - } catch (IOException ex) { - ex.printStackTrace(); - } + Random random = new Random(); + openSearchActions = new OpenSearchActions(); + int randomNum = random.nextInt((10000 - 1) + 1) + 1; + domainName = "testdomain" + randomNum; } @Test @Tag("IntegrationTest") @Order(1) - public void createDomainTest() { - CreateDomain.createNewDomain(searchClient, domainName); + public void helloTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = HelloOpenSearch.listVersionsAsync(); + future.join(); + }); System.out.println("Test 1 passed"); } @Test @Tag("IntegrationTest") @Order(2) - public void listDomainNamesTest() { - ListDomainNames.listAllDomains(searchClient); + public void createDomain() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.createNewDomainAsync(domainName); + String domainId = future.join(); + System.out.println("Domain successfully created with ID: " + domainId); + }); System.out.println("Test 2 passed"); } + @Test @Tag("IntegrationTest") @Order(3) - public void UpdateDomain() { - UpdateDomain.updateSpecificDomain(searchClient, domainName); + public void describeDomainTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.describeDomainAsync(domainName); + arn = future.join(); + }); System.out.println("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DeleteDomain() { - DeleteDomain.deleteSpecificDomain(searchClient, domainName); + public void listDomains() { + assertDoesNotThrow(() -> { + CompletableFuture> future = openSearchActions.listAllDomainsAsync(); + List domainInfoList = future.join(); + for (DomainInfo domain : domainInfoList) { + System.out.println("Domain name is: " + domain.domainName()); + } + }); System.out.println("Test 4 passed"); } + + @Test + @Tag("IntegrationTest") + @Order(5) + public void domainChangeTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.domainChangeProgressAsync(domainName); + future.join(); + System.out.println("Domain change progress completed successfully."); + }); + System.out.println("Test 5 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(6) + public void domainModifyTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.updateSpecificDomainAsync(domainName); + UpdateDomainConfigResponse updateResponse = future.join(); // Wait for the task to complete + System.out.println("Domain update response from Amazon OpenSearch Service: " + updateResponse.toString()); + }); + System.out.println("Test 6 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(7) + public void domainChangeTest2() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.domainChangeProgressAsync(domainName); + future.join(); + System.out.println("Domain change progress completed successfully."); + }); + System.out.println("Test 7 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(8) + public void domainTagTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.addDomainTagsAsync(arn); + future.join(); + System.out.println("Domain change progress completed successfully."); + }); + System.out.println("Test 8 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(9) + public void domainListTagsTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.listDomainTagsAsync(arn); + future.join(); + System.out.println("Domain tags listed successfully."); + }); + System.out.println("Test 8 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(10) + public void domainDelTest() { + assertDoesNotThrow(() -> { + CompletableFuture future = openSearchActions.deleteSpecificDomainAsync(domainName); + future.join(); + System.out.println(domainName + " was successfully deleted."); + }); + System.out.println("Test 10 passed"); + } } From e96f075be55d1bf5f96e2ded47f59e5d17ccf5d5 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 09:52:15 -0400 Subject: [PATCH 2/9] updated Readme --- javav2/example_code/opensearch/README.md | 38 ++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/javav2/example_code/opensearch/README.md b/javav2/example_code/opensearch/README.md index f863630965a..99176fb8778 100644 --- a/javav2/example_code/opensearch/README.md +++ b/javav2/example_code/opensearch/README.md @@ -29,13 +29,24 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav +### Basics + +Code examples that show you how to perform the essential operations within a service. + +- [Learn OpenSearch core operations](src/main/java/com/example/search/scenario/OpenSearchScenario.java) + + ### Single actions Code excerpts that show you how to call individual service functions. -- [CreateDomain](src/main/java/com/example/search/CreateDomain.java#L6) -- [DeleteDomain](src/main/java/com/example/search/DeleteDomain.java#L6) -- [ListDomainNames](src/main/java/com/example/search/ListDomainNames.java#L6) +- [AddTags](src/main/java/com/example/search/scenario/OpenSearchActions.java#L265) +- [ChangeProgress](src/main/java/com/example/search/scenario/OpenSearchActions.java#L215) +- [CreateDomain](src/main/java/com/example/search/scenario/OpenSearchActions.java#L69) +- [DeleteDomain](src/main/java/com/example/search/scenario/OpenSearchActions.java#L114) +- [DescribeDomain](src/main/java/com/example/search/UpdateDomain.java#L6) +- [ListDomainNames](src/main/java/com/example/search/scenario/OpenSearchActions.java#L167) +- [ListTags](src/main/java/com/example/search/scenario/OpenSearchActions.java#L265) - [UpdateDomainConfig](src/main/java/com/example/search/UpdateDomain.java#L6) @@ -51,6 +62,27 @@ Code excerpts that show you how to call individual service functions. +#### Learn OpenSearch core operations + +This example shows you how to do the following: + +- Create an OpenSearch domain. +- Provides detailed information about a specific OpenSearch domain. +- Lists all the OpenSearch domains owned by the account. +- Waits until the OpenSearch domain's change status reaches a completed state. +- Modifies the configuration of an existing OpenSearch domain. +- Add a tag to the OpenSearch domain. +- Lists the tags associated with an OpenSearch domain. +- Removes tags from an OpenSearch domain. +- Deletes the OpenSearch domain. + + + + + + + + ### Tests From 338de1190549169fa4e80e53ec391978d51e4b34 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 10:02:22 -0400 Subject: [PATCH 3/9] updated Java files --- .../java/com/example/search/CreateDomain.java | 92 ------------------- .../java/com/example/search/DeleteDomain.java | 63 ------------- .../com/example/search/ListDomainNames.java | 55 ----------- .../java/com/example/search/UpdateDomain.java | 73 --------------- 4 files changed, 283 deletions(-) delete mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java delete mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java delete mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java delete mode 100644 javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java b/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java deleted file mode 100644 index 1f7bef3dc62..00000000000 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.search; - -// snippet-start:[opensearch.java2.create_domain.main] -// snippet-start:[opensearch.java2.create_domain.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.opensearch.OpenSearchClient; -import software.amazon.awssdk.services.opensearch.model.ClusterConfig; -import software.amazon.awssdk.services.opensearch.model.EBSOptions; -import software.amazon.awssdk.services.opensearch.model.VolumeType; -import software.amazon.awssdk.services.opensearch.model.NodeToNodeEncryptionOptions; -import software.amazon.awssdk.services.opensearch.model.CreateDomainRequest; -import software.amazon.awssdk.services.opensearch.model.CreateDomainResponse; -import software.amazon.awssdk.services.opensearch.model.OpenSearchException; -// snippet-end:[opensearch.java2.create_domain.import] - -/** - * 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 - */ -public class CreateDomain { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - domainName - The name of the domain to create. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String domainName = args[0]; - Region region = Region.US_EAST_1; - OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .build(); - - createNewDomain(searchClient, domainName); - System.out.println("Done"); - } - - public static void createNewDomain(OpenSearchClient searchClient, String domainName) { - try { - ClusterConfig clusterConfig = ClusterConfig.builder() - .dedicatedMasterEnabled(true) - .dedicatedMasterCount(3) - .dedicatedMasterType("t2.small.search") - .instanceType("t2.small.search") - .instanceCount(5) - .build(); - - EBSOptions ebsOptions = EBSOptions.builder() - .ebsEnabled(true) - .volumeSize(10) - .volumeType(VolumeType.GP2) - .build(); - - NodeToNodeEncryptionOptions encryptionOptions = NodeToNodeEncryptionOptions.builder() - .enabled(true) - .build(); - - CreateDomainRequest domainRequest = CreateDomainRequest.builder() - .domainName(domainName) - .engineVersion("OpenSearch_1.0") - .clusterConfig(clusterConfig) - .ebsOptions(ebsOptions) - .nodeToNodeEncryptionOptions(encryptionOptions) - .build(); - - System.out.println("Sending domain creation request..."); - CreateDomainResponse createResponse = searchClient.createDomain(domainRequest); - System.out.println("Domain status is " + createResponse.domainStatus().toString()); - System.out.println("Domain Id is " + createResponse.domainStatus().domainId()); - - } catch (OpenSearchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[opensearch.java2.create_domain.main] diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java b/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java deleted file mode 100644 index 8e880175070..00000000000 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.search; - -// snippet-start:[opensearch.java2.delete_domain.main] -// snippet-start:[opensearch.java2.delete_domain.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.opensearch.OpenSearchClient; -import software.amazon.awssdk.services.opensearch.model.OpenSearchException; -import software.amazon.awssdk.services.opensearch.model.DeleteDomainRequest; -// snippet-end:[opensearch.java2.delete_domain.import] - -/** - * 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 - */ -public class DeleteDomain { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - domainName - The name of the domain to delete. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String domainName = args[0]; - Region region = Region.US_EAST_1; - OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .build(); - - deleteSpecificDomain(searchClient, domainName); - System.out.println("Done"); - } - - public static void deleteSpecificDomain(OpenSearchClient searchClient, String domainName) { - try { - DeleteDomainRequest domainRequest = DeleteDomainRequest.builder() - .domainName(domainName) - .build(); - - searchClient.deleteDomain(domainRequest); - System.out.println(domainName + " was successfully deleted."); - - } catch (OpenSearchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[opensearch.java2.delete_domain.main] diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java b/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java deleted file mode 100644 index 14eb6a93e6b..00000000000 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.search; - -// snippet-start:[opensearch.java2.list_domains.main] -// snippet-start:[opensearch.java2.list_domains.import] -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.opensearch.OpenSearchClient; -import software.amazon.awssdk.services.opensearch.model.DomainInfo; -import software.amazon.awssdk.services.opensearch.model.ListDomainNamesRequest; -import software.amazon.awssdk.services.opensearch.model.ListDomainNamesResponse; -import software.amazon.awssdk.services.opensearch.model.OpenSearchException; -// snippet-end:[opensearch.java2.list_domains.import] - -import java.util.List; - -/** - * 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 - */ -public class ListDomainNames { - public static void main(String[] args) { - Region region = Region.US_EAST_1; - OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - listAllDomains(searchClient); - System.out.println("Done"); - } - - public static void listAllDomains(OpenSearchClient searchClient) { - try { - ListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder() - .engineType("OpenSearch") - .build(); - - ListDomainNamesResponse response = searchClient.listDomainNames(namesRequest); - List domainInfoList = response.domainNames(); - for (DomainInfo domain : domainInfoList) - System.out.println("Domain name is " + domain.domainName()); - - } catch (OpenSearchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[opensearch.java2.list_domains.main] diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java b/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java deleted file mode 100644 index 6ad4437f04f..00000000000 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.search; - -// snippet-start:[opensearch.java2.update_domain.main] -// snippet-start:[opensearch.java2.update_domain.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.opensearch.OpenSearchClient; -import software.amazon.awssdk.services.opensearch.model.ClusterConfig; -import software.amazon.awssdk.services.opensearch.model.OpenSearchException; -import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigRequest; -import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigResponse; -// snippet-end:[opensearch.java2.update_domain.import] - -/** - * 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 - */ -public class UpdateDomain { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - domainName - The name of the domain to update. - - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String domainName = args[0]; - Region region = Region.US_EAST_1; - OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .build(); - - updateSpecificDomain(searchClient, domainName); - System.out.println("Done"); - } - - public static void updateSpecificDomain(OpenSearchClient searchClient, String domainName) { - try { - ClusterConfig clusterConfig = ClusterConfig.builder() - .instanceCount(3) - .build(); - - UpdateDomainConfigRequest updateDomainConfigRequest = UpdateDomainConfigRequest.builder() - .domainName(domainName) - .clusterConfig(clusterConfig) - .build(); - - System.out.println("Sending domain update request..."); - UpdateDomainConfigResponse updateResponse = searchClient.updateDomainConfig(updateDomainConfigRequest); - System.out.println("Domain update response from Amazon OpenSearch Service:"); - System.out.println(updateResponse.toString()); - - } catch (OpenSearchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[opensearch.java2.update_domain.main] From fd547ce8e37b64d0846b02e4aa48d078e31704da Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 10:03:28 -0400 Subject: [PATCH 4/9] updated Java files --- javav2/example_code/opensearch/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javav2/example_code/opensearch/README.md b/javav2/example_code/opensearch/README.md index 99176fb8778..8f6fdf72c24 100644 --- a/javav2/example_code/opensearch/README.md +++ b/javav2/example_code/opensearch/README.md @@ -44,10 +44,10 @@ Code excerpts that show you how to call individual service functions. - [ChangeProgress](src/main/java/com/example/search/scenario/OpenSearchActions.java#L215) - [CreateDomain](src/main/java/com/example/search/scenario/OpenSearchActions.java#L69) - [DeleteDomain](src/main/java/com/example/search/scenario/OpenSearchActions.java#L114) -- [DescribeDomain](src/main/java/com/example/search/UpdateDomain.java#L6) +- [DescribeDomain](src/main/java/com/example/search/scenario/OpenSearchActions.java#L189) - [ListDomainNames](src/main/java/com/example/search/scenario/OpenSearchActions.java#L167) - [ListTags](src/main/java/com/example/search/scenario/OpenSearchActions.java#L265) -- [UpdateDomainConfig](src/main/java/com/example/search/UpdateDomain.java#L6) +- [UpdateDomainConfig](src/main/java/com/example/search/scenario/OpenSearchActions.java#L189) From 34fdee90bce8a8d2dad3b10cd1fde435c349a7d6 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 10:16:33 -0400 Subject: [PATCH 5/9] updated Java files --- .doc_gen/metadata/opensearch_metadata.yaml | 17 +++++++++++++++++ .../com/example/search/HelloOpenSearch.java | 18 ++---------------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.doc_gen/metadata/opensearch_metadata.yaml b/.doc_gen/metadata/opensearch_metadata.yaml index 8dffa93f35a..1e2abc6b9fb 100644 --- a/.doc_gen/metadata/opensearch_metadata.yaml +++ b/.doc_gen/metadata/opensearch_metadata.yaml @@ -1,4 +1,21 @@ # zexi 0.4.0 +opensearch_Hello: + title: Hello &ES; + title_abbrev: Hello &ES; + synopsis: get started using &ES;. + category: Hello + languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/opensearch + sdkguide: + excerpts: + - description: + snippet_tags: + - opensearch.java2.hello.main + services: + opensearch: {ListVersions} opensearch_CreateDomain: languages: Kotlin: diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java b/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java index b85a955e2f6..dfb0e060e73 100644 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/HelloOpenSearch.java @@ -3,25 +3,11 @@ package com.example.search; -// snippet-start:[opensearch.java2.create_domain.main] -// snippet-start:[opensearch.java2.create_domain.import] -import software.amazon.awssdk.regions.Region; +// snippet-start:[opensearch.java2.hello.main] import software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient; -import software.amazon.awssdk.services.opensearch.OpenSearchClient; -import software.amazon.awssdk.services.opensearch.model.ClusterConfig; -import software.amazon.awssdk.services.opensearch.model.EBSOptions; import software.amazon.awssdk.services.opensearch.model.ListVersionsRequest; -import software.amazon.awssdk.services.opensearch.model.ListVersionsResponse; -import software.amazon.awssdk.services.opensearch.model.VersionStatus; -import software.amazon.awssdk.services.opensearch.model.VolumeType; -import software.amazon.awssdk.services.opensearch.model.NodeToNodeEncryptionOptions; -import software.amazon.awssdk.services.opensearch.model.CreateDomainRequest; -import software.amazon.awssdk.services.opensearch.model.CreateDomainResponse; -import software.amazon.awssdk.services.opensearch.model.OpenSearchException; - import java.util.List; import java.util.concurrent.CompletableFuture; -// snippet-end:[opensearch.java2.create_domain.import] /** * Before running this Java V2 code example, set up your development @@ -62,4 +48,4 @@ public static CompletableFuture listVersionsAsync() { }); } } -// snippet-end:[opensearch.java2.create_domain.main] +// snippet-end:[opensearch.java2.hello.main] From 076ed4f6fc21b963a2ac23959272a54ff08f9618 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 10:22:07 -0400 Subject: [PATCH 6/9] updated Readme --- javav2/example_code/opensearch/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/javav2/example_code/opensearch/README.md b/javav2/example_code/opensearch/README.md index 8f6fdf72c24..17c9da4dbac 100644 --- a/javav2/example_code/opensearch/README.md +++ b/javav2/example_code/opensearch/README.md @@ -29,6 +29,11 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav +### Get started + +- [Hello OpenSearch](src/main/java/com/example/search/HelloOpenSearch.java#L6) (`ListVersions`) + + ### Basics Code examples that show you how to perform the essential operations within a service. @@ -61,6 +66,10 @@ Code excerpts that show you how to call individual service functions. +#### Hello OpenSearch + +This example shows you how to get started using OpenSearch. + #### Learn OpenSearch core operations From 9c74854fbbcce0fda7167f638c2a51f656eb60e8 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 11:11:46 -0400 Subject: [PATCH 7/9] updated Spec --- .../opensearch_scenario/SPECIFICATION.md | 29 ------------------- 1 file changed, 29 deletions(-) diff --git a/basics_scenarios/opensearch_scenario/SPECIFICATION.md b/basics_scenarios/opensearch_scenario/SPECIFICATION.md index 4fc400f8d36..776c95a0203 100644 --- a/basics_scenarios/opensearch_scenario/SPECIFICATION.md +++ b/basics_scenarios/opensearch_scenario/SPECIFICATION.md @@ -14,80 +14,51 @@ This program is intended for users not familiar with the Amazon OpenSearch SDK t The Amazon OpenSearch Basics scenario executes the following operations. 1. **Create an Amazon OpenSearch Domain**: -<<<<<<< HEAD - Description: This operation creates a new Amazon OpenSearch domain, which is a managed instance of the OpenSearch engine. Invoke the `createDomain` method. - Exception Handling: Check to see if a `OpenSearchException` is thrown. We tested as group and `ResourceExistsException` is not thrown. Display the message and end the program. -======= - - Description: This operation creates a new Amazon OpenSearch domain, which is a managed instance of the OpenSearch engine. ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 2. **Describe the Amazon OpenSearch Domain**: - Description: This operation retrieves information about the specified Amazon OpenSearch domain. - The method `describeDomain(domainName)` is called to obtain the Amazon Resource Name (ARN) of the specified OpenSearch domain. -<<<<<<< HEAD - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 3. **List the Domains in Your Account**: - Description: This operation lists all the Amazon OpenSearch domains in the current AWS account. - The method `listAllDomains()` is called to retrieve a list of all the OpenSearch domains available in the account. -<<<<<<< HEAD - Exception Handling: Check to see if a `OpenSearchException` is thrown. There are not many other useful exceptions for this specific call. If so, display the message and end the program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 4. **Wait until the Domain's Change Status Reaches a Completed State**: - Description: This operation waits until the change status of the specified Amazon OpenSearch domain reaches a completed state. - When making changes to an OpenSearch domain, such as scaling the number of data nodes or updating the OpenSearch version, the domain goes through a change process. This method, `domainChangeProgress(domainName)`, waits until the change status of the specified domain reaches a completed state, which can take several minutes to several hours, depending on the complexity of the change and the current load on the OpenSearch service. -<<<<<<< HEAD - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. Note this operation may take up to 20 minutes (I am observering that uses the Java SDK). -======= - Note this operation may take up to 20 minutes. ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 5. **Modify the Domain**: - Description: This operation modifies the cluster configuration of the specified Amazon OpenSearch domain, such as the instance count. - The flexibility to modify the OpenSearch domain's configuration is particularly useful when the data or usage patterns change over time, as you can easily scale the domain to meet the new requirements without having to recreate the entire domain. - The method `updateSpecificDomain(domainName)` is called to update the configuration of the specified OpenSearch domain. -<<<<<<< HEAD - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 6. **Wait until the Domain's Change Status Reaches a Completed State (Again)**: - Description: This operation is similar to the previous "Wait until the Domain's Change Status Reaches a Completed State" operation, but it is called after the domain modification to ensure the changes have been fully applied. - The method `domainChangeProgress(domainName)` is called again to wait until the change status of the specified domain reaches a completed state. -<<<<<<< HEAD - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 7. **Tag the Domain**: - Description: This operation adds tags to the specified Amazon OpenSearch domain. - Tags are key-value pairs that can be used to categorize and filter OpenSearch domains. They can be useful for tracking costs by grouping expenses for similarly tagged resources. - The method `addDomainTags(arn)` is called to add tags to the OpenSearch domain identified by the provided ARN. -<<<<<<< HEAD - Exception Handling: Check to see if a `OpenSearchException` is thrown. There are not many other useful exceptions for this specific call. If so, display the message and end the program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 8. **List Domain Tags**: - Description: This operation lists the tags associated with the specified Amazon OpenSearch domain. - The method `listDomainTags(arn)` is called to retrieve the tags for the OpenSearch domain identified by the provided ARN. -<<<<<<< HEAD - Exception Handling: Check to see if a `OpenSearchException` is thrown. There are not many other useful exceptions for this specific call. If so, display the message and end the program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) 9. **Delete the Amazon OpenSearch Domain**: - Description: This operation deletes the specified Amazon OpenSearch domain. - The method `deleteSpecificDomain(domainName)` is called to delete the OpenSearch domain with the specified name." -<<<<<<< HEAD - Exception Handling: Check to see if a `ResourceNotFoundException` is thrown. If so, display the message and end program. -======= ->>>>>>> 150c02cfd (added OpenSearch Basics Scenario) ### Program execution From e3a8dd2db50bad64d313cd0c50420eafa3ca1686 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 11:28:17 -0400 Subject: [PATCH 8/9] updated Readme --- basics_scenarios/opensearch_scenario/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/basics_scenarios/opensearch_scenario/README.md b/basics_scenarios/opensearch_scenario/README.md index 8308cb63ba0..7d9fa147d63 100644 --- a/basics_scenarios/opensearch_scenario/README.md +++ b/basics_scenarios/opensearch_scenario/README.md @@ -44,7 +44,7 @@ This scenario example will be implemented in the following languages: ## Additional reading -- [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) +- [Amazon OpenSearch](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) --- From 359f10822366dd08ff87605ade7da750b19313a7 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Mon, 16 Sep 2024 11:30:37 -0400 Subject: [PATCH 9/9] updated Readme --- basics_scenarios/opensearch_scenario/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/basics_scenarios/opensearch_scenario/README.md b/basics_scenarios/opensearch_scenario/README.md index 7d9fa147d63..3bbfb8b9233 100644 --- a/basics_scenarios/opensearch_scenario/README.md +++ b/basics_scenarios/opensearch_scenario/README.md @@ -2,7 +2,7 @@ ## Overview - This Amazon OpenSearch Service (Amazon ECR) basic scenario demonstrates how to interact with the Amazon OpenSearch service using an AWS SDK. The scenario covers various operations such as creating an OpenSearch domain, modifying a domain, waiting for changes to the domain to enter a complete state, and so on. + This Amazon OpenSearch Service basic scenario demonstrates how to interact with the Amazon OpenSearch service using an AWS SDK. The scenario covers various operations such as creating an OpenSearch domain, modifying a domain, waiting for changes to the domain to enter a complete state, and so on. Here are the top five service operations this scenario covers.