diff --git a/.doc_gen/metadata/glue_metadata.yaml b/.doc_gen/metadata/glue_metadata.yaml index ed2c3ca45c9..f899a2f74a8 100644 --- a/.doc_gen/metadata/glue_metadata.yaml +++ b/.doc_gen/metadata/glue_metadata.yaml @@ -437,7 +437,7 @@ glue_GetTables: excerpts: - description: snippet_tags: - - glue.java2.get_table.main + - glue.java2.get_tables.main PHP: versions: - sdk_version: 3 diff --git a/.doc_gen/metadata/iam_metadata.yaml b/.doc_gen/metadata/iam_metadata.yaml index 78193fbb656..ab8896365a3 100644 --- a/.doc_gen/metadata/iam_metadata.yaml +++ b/.doc_gen/metadata/iam_metadata.yaml @@ -3355,7 +3355,7 @@ iam_Scenario_GroupBasics: iam: {AddUserToGroup, CreateGroup, CreateUser, CreateAccessKey, CreateRole, CreatePolicy, AttachRolePolicy, PutGroupPolicy, DeleteGroup, DeleteGroupPolicy, DeleteAccessKey, DeleteUser, RemoveUserFromGroup} iam_Scenario_CreateUserAssumeRole: - title: Create an &IAM-user; and assume a role with &STS; using an &AWS; SDK + title: Learn core operations for &IAM; using an &AWS; SDK. title_abbrev: Create a user and assume a role synopsis: create a user and assume a role. &aws_sec_sdk_use-federation-warning; synopsis_list: @@ -3363,7 +3363,7 @@ iam_Scenario_CreateUserAssumeRole: - Create a role that grants permission to list &S3; buckets for the account. - Add a policy to let the user assume the role. - Assume the role and list S3 buckets using temporary credentials, then clean up resources. - category: Scenarios + category: Basics languages: .NET: versions: diff --git a/.doc_gen/metadata/lambda_metadata.yaml b/.doc_gen/metadata/lambda_metadata.yaml index a30db5f5bf4..098e244849b 100644 --- a/.doc_gen/metadata/lambda_metadata.yaml +++ b/.doc_gen/metadata/lambda_metadata.yaml @@ -13,7 +13,7 @@ lambda_Hello: excerpts: - description: snippet_tags: - - lambda.java2.ListLambdaFunctions.complete + - lambda.java2.list.main .NET: versions: - sdk_version: 3 @@ -384,6 +384,15 @@ lambda_Invoke: lambda: {Invoke} lambda_GetFunction: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/lambda + sdkguide: + excerpts: + - description: + snippet_tags: + - lambda.java2.get.function.main .NET: versions: - sdk_version: 3 @@ -469,6 +478,15 @@ lambda_GetFunction: lambda: {GetFunction} lambda_UpdateFunctionCode: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/lambda + sdkguide: + excerpts: + - description: + snippet_tags: + - lambda.java2.get.function.main .NET: versions: - sdk_version: 3 @@ -555,6 +573,15 @@ lambda_UpdateFunctionCode: lambda: {UpdateFunctionCode} lambda_UpdateFunctionConfiguration: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/lambda + sdkguide: + excerpts: + - description: + snippet_tags: + - lambda.java2.update.config.main .NET: versions: - sdk_version: 3 @@ -724,7 +751,7 @@ lambda_ListFunctions: services: lambda: {ListFunctions} lambda_Scenario_GettingStartedFunctions: - title: Get started creating and invoking &LAM; functions using an &AWS; SDK + title: Learn core operations for &LAM; functions using an &AWS; SDK title_abbrev: Get started with functions synopsis_list: - Create an &IAM; role and &LAM; function, then upload handler code. @@ -732,7 +759,7 @@ lambda_Scenario_GettingStartedFunctions: - Update the function code and configure with an environment variable. - Invoke the function with new parameters and get results. Display the returned execution log. - List the functions for your account, then clean up resources. - category: Scenarios + category: Basics guide_topic: title: Create a &LAM; function with the console url: lambda/latest/dg/getting-started-create-function.html diff --git a/javav2/example_code/glue/README.md b/javav2/example_code/glue/README.md index 38e998832b9..79d12544eb1 100644 --- a/javav2/example_code/glue/README.md +++ b/javav2/example_code/glue/README.md @@ -38,18 +38,18 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav Code examples that show you how to perform the essential operations within a service. -- [Learn the basics](src/main/java/com/example/glue/GlueScenario.java) +- [Learn the basics](src/main/java/com/example/glue/scenario/GlueScenario.java) ### Single actions Code excerpts that show you how to call individual service functions. -- [CreateCrawler](src/main/java/com/example/glue/CreateCrawler.java#L6) -- [GetCrawler](src/main/java/com/example/glue/GetCrawler.java#L6) -- [GetDatabase](src/main/java/com/example/glue/GetDatabase.java#L6) -- [GetTables](src/main/java/com/example/glue/GetTable.java#L6) -- [StartCrawler](src/main/java/com/example/glue/StartCrawler.java#L6) +- [CreateCrawler](src/main/java/com/example/glue/scenario/GlueScenario.java#L335) +- [GetCrawler](src/main/java/com/example/glue/scenario/GlueScenario.java#L383) +- [GetDatabase](src/main/java/com/example/glue/scenario/GlueScenario.java#L438) +- [GetTables](src/main/java/com/example/glue/scenario/GlueScenario.java#L470) +- [StartCrawler](src/main/java/com/example/glue/scenario/GlueScenario.java#L415) diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/CreateCrawler.java b/javav2/example_code/glue/src/main/java/com/example/glue/CreateCrawler.java deleted file mode 100644 index 478f79137db..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/CreateCrawler.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.create_crawler.main] -// snippet-start:[glue.java2.create_crawler.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.CreateCrawlerRequest; -import software.amazon.awssdk.services.glue.model.CrawlerTargets; -import software.amazon.awssdk.services.glue.model.GlueException; -import software.amazon.awssdk.services.glue.model.S3Target; -import java.util.ArrayList; -import java.util.List; -// snippet-end:[glue.java2.create_crawler.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 CreateCrawler { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - IAM - The ARN of the IAM role that has AWS Glue and S3 permissions.\s - s3Path - The Amazon Simple Storage Service (Amazon S3) target that contains data (for example, CSV data). - cron - A cron expression used to specify the schedule (i.e., cron(15 12 * * ? *). - dbName - The database name.\s - crawlerName - The name of the crawler.\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String iam = args[0]; - String s3Path = args[1]; - String cron = args[2]; - String dbName = args[3]; - String crawlerName = args[4]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - createGlueCrawler(glueClient, iam, s3Path, cron, dbName, crawlerName); - glueClient.close(); - } - - public static void createGlueCrawler(GlueClient glueClient, - String iam, - String s3Path, - String cron, - String dbName, - String crawlerName) { - - try { - S3Target s3Target = S3Target.builder() - .path(s3Path) - .build(); - - // Add the S3Target to a list. - List targetList = new ArrayList<>(); - targetList.add(s3Target); - - CrawlerTargets targets = CrawlerTargets.builder() - .s3Targets(targetList) - .build(); - - CreateCrawlerRequest crawlerRequest = CreateCrawlerRequest.builder() - .databaseName(dbName) - .name(crawlerName) - .description("Created by the AWS Glue Java API") - .targets(targets) - .role(iam) - .schedule(cron) - .build(); - - glueClient.createCrawler(crawlerRequest); - System.out.println(crawlerName + " was successfully created"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.create_crawler.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/DeleteCrawler.java b/javav2/example_code/glue/src/main/java/com/example/glue/DeleteCrawler.java deleted file mode 100644 index c6c475dd76e..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/DeleteCrawler.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.glue; - -// snippet-start:[glue.java2.delete_crawler.main] -// snippet-start:[glue.java2.delete_crawler.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.DeleteCrawlerRequest; -import software.amazon.awssdk.services.glue.model.GlueException; -// snippet-end:[glue.java2.delete_crawler.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 DeleteCrawler { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - crawlerName - The name of the crawler.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String crawlerName = args[0]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - deleteSpecificCrawler(glueClient, crawlerName); - glueClient.close(); - } - - public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerName) { - try { - DeleteCrawlerRequest deleteCrawlerRequest = DeleteCrawlerRequest.builder() - .name(crawlerName) - .build(); - - glueClient.deleteCrawler(deleteCrawlerRequest); - System.out.println(crawlerName + " was deleted"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.delete_crawler.main] \ No newline at end of file diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/GetCrawler.java b/javav2/example_code/glue/src/main/java/com/example/glue/GetCrawler.java deleted file mode 100644 index 422e92c4608..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/GetCrawler.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.get_crawler.main] -// snippet-start:[glue.java2.get_crawler.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.GetCrawlerRequest; -import software.amazon.awssdk.services.glue.model.GetCrawlerResponse; -import software.amazon.awssdk.services.glue.model.GlueException; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Locale; -// snippet-end:[glue.java2.get_crawler.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 GetCrawler { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - crawlerName - The name of the crawler.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String crawlerName = args[0]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - getSpecificCrawler(glueClient, crawlerName); - glueClient.close(); - } - - public static void getSpecificCrawler(GlueClient glueClient, String crawlerName) { - try { - GetCrawlerRequest crawlerRequest = GetCrawlerRequest.builder() - .name(crawlerName) - .build(); - - GetCrawlerResponse response = glueClient.getCrawler(crawlerRequest); - Instant createDate = response.crawler().creationTime(); - - // Convert the Instant to readable date - DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - .withLocale(Locale.US) - .withZone(ZoneId.systemDefault()); - - formatter.format(createDate); - System.out.println("The create date of the Crawler is " + createDate); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.get_crawler.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/GetDatabase.java b/javav2/example_code/glue/src/main/java/com/example/glue/GetDatabase.java deleted file mode 100644 index d8b39f289ed..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/GetDatabase.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.get_database.main] -// snippet-start:[glue.java2.get_database.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.GetDatabaseRequest; -import software.amazon.awssdk.services.glue.model.GetDatabaseResponse; -import software.amazon.awssdk.services.glue.model.GlueException; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Locale; -// snippet-end:[glue.java2.get_database.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 GetDatabase { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - databaseName - The name of the database.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String databaseName = args[0]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - getSpecificDatabase(glueClient, databaseName); - glueClient.close(); - } - - public static void getSpecificDatabase(GlueClient glueClient, String databaseName) { - try { - GetDatabaseRequest databasesRequest = GetDatabaseRequest.builder() - .name(databaseName) - .build(); - - GetDatabaseResponse response = glueClient.getDatabase(databasesRequest); - Instant createDate = response.database().createTime(); - - // Convert the Instant to readable date. - DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - .withLocale(Locale.US) - .withZone(ZoneId.systemDefault()); - - formatter.format(createDate); - System.out.println("The create date of the database is " + createDate); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.get_database.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/GetJobRun.java b/javav2/example_code/glue/src/main/java/com/example/glue/GetJobRun.java deleted file mode 100644 index 677263f89c1..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/GetJobRun.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.get_job.main] -// snippet-start:[glue.java2.get_job.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.GetJobRunRequest; -import software.amazon.awssdk.services.glue.model.GetJobRunResponse; -import software.amazon.awssdk.services.glue.model.GlueException; -// snippet-end:[glue.java2.get_job.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 GetJobRun { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - jobName - The name of the job.\s - runId - The run id value.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String jobName = args[0]; - String runId = args[1]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - getGlueJobRun(glueClient, jobName, runId); - glueClient.close(); - } - - public static void getGlueJobRun(GlueClient glueClient, String jobName, String runId) { - try { - GetJobRunRequest jobRunRequest = GetJobRunRequest.builder() - .jobName(jobName) - .runId(runId) - .build(); - - GetJobRunResponse runResponse = glueClient.getJobRun(jobRunRequest); - System.out.println("Job status is : " + runResponse.jobRun().jobRunStateAsString()); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.get_job.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/GetTable.java b/javav2/example_code/glue/src/main/java/com/example/glue/GetTable.java deleted file mode 100644 index cf231c4dd59..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/GetTable.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.get_table.main] -// snippet-start:[glue.java2.get_table.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.GetTableRequest; -import software.amazon.awssdk.services.glue.model.GetTableResponse; -import software.amazon.awssdk.services.glue.model.GlueException; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Locale; -// snippet-end:[glue.java2.get_table.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 GetTable { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - dbName - The database name.\s - tableName - The name of the table.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String dbName = args[0]; - String tableName = args[1]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - getGlueTable(glueClient, dbName, tableName); - glueClient.close(); - } - - public static void getGlueTable(GlueClient glueClient, String dbName, String tableName) { - try { - GetTableRequest tableRequest = GetTableRequest.builder() - .databaseName(dbName) - .name(tableName) - .build(); - - GetTableResponse tableResponse = glueClient.getTable(tableRequest); - Instant createDate = tableResponse.table().createTime(); - - // Convert the Instant to readable date. - DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - .withLocale(Locale.US) - .withZone(ZoneId.systemDefault()); - - formatter.format(createDate); - System.out.println("The create date of the table is " + createDate); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.get_table.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java b/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java deleted file mode 100644 index 4a175272f19..00000000000 --- a/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.start_crawler.main] -// snippet-start:[glue.java2.start_crawler.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import software.amazon.awssdk.services.glue.model.GlueException; -import software.amazon.awssdk.services.glue.model.StartCrawlerRequest; -// snippet-end:[glue.java2.start_crawler.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 StartCrawler { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - crawlerName - The name of the crawler.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String crawlerName = args[0]; - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - - startSpecificCrawler(glueClient, crawlerName); - glueClient.close(); - } - - public static void startSpecificCrawler(GlueClient glueClient, String crawlerName) { - try { - StartCrawlerRequest crawlerRequest = StartCrawlerRequest.builder() - .name(crawlerName) - .build(); - - glueClient.startCrawler(crawlerRequest); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[glue.java2.start_crawler.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/GlueScenario.java b/javav2/example_code/glue/src/main/java/com/example/glue/scenario/GlueScenario.java similarity index 51% rename from javav2/example_code/glue/src/main/java/com/example/glue/GlueScenario.java rename to javav2/example_code/glue/src/main/java/com/example/glue/scenario/GlueScenario.java index e69f8972467..96e00f3cf35 100644 --- a/javav2/example_code/glue/src/main/java/com/example/glue/GlueScenario.java +++ b/javav2/example_code/glue/src/main/java/com/example/glue/scenario/GlueScenario.java @@ -1,501 +1,747 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.glue; - -// snippet-start:[glue.java2.scenario.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.glue.GlueClient; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import software.amazon.awssdk.services.glue.model.DatabaseInput; -import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest; -import software.amazon.awssdk.services.glue.model.GlueException; -import software.amazon.awssdk.services.glue.model.GetCrawlerResponse; -import software.amazon.awssdk.services.glue.model.GetCrawlerRequest; -import software.amazon.awssdk.services.glue.model.CreateCrawlerRequest; -import software.amazon.awssdk.services.glue.model.GetTablesResponse; -import software.amazon.awssdk.services.glue.model.GetTablesRequest; -import software.amazon.awssdk.services.glue.model.StartCrawlerRequest; -import software.amazon.awssdk.services.glue.model.GetDatabaseRequest; -import software.amazon.awssdk.services.glue.model.CrawlerTargets; -import software.amazon.awssdk.services.glue.model.GetDatabaseResponse; -import software.amazon.awssdk.services.glue.model.Table; -import software.amazon.awssdk.services.glue.model.StartJobRunResponse; -import software.amazon.awssdk.services.glue.model.StartJobRunRequest; -import software.amazon.awssdk.services.glue.model.GetJobsRequest; -import software.amazon.awssdk.services.glue.model.CreateJobRequest; -import software.amazon.awssdk.services.glue.model.GetJobRunsResponse; -import software.amazon.awssdk.services.glue.model.GetJobsResponse; -import software.amazon.awssdk.services.glue.model.Job; -import software.amazon.awssdk.services.glue.model.WorkerType; -import software.amazon.awssdk.services.glue.model.JobCommand; -import software.amazon.awssdk.services.glue.model.GetJobRunsRequest; -import software.amazon.awssdk.services.glue.model.JobRun; -import software.amazon.awssdk.services.glue.model.S3Target; -import software.amazon.awssdk.services.glue.model.DeleteJobRequest; -import software.amazon.awssdk.services.glue.model.DeleteDatabaseRequest; -import software.amazon.awssdk.services.glue.model.DeleteCrawlerRequest; -// snippet-end:[glue.java2.scenario.import] - -// snippet-start:[glue.java2.scenario.main] -/** - * - * 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 - * - * To set up the resources, see this documentation topic: - * - * https://docs.aws.amazon.com/glue/latest/ug/tutorial-add-crawler.html - * - * This example performs the following tasks: - * - * 1. Create a database. - * 2. Create a crawler. - * 3. Get a crawler. - * 4. Start a crawler. - * 5. Get a database. - * 6. Get tables. - * 7. Create a job. - * 8. Start a job run. - * 9. List all jobs. - * 10. Get job runs. - * 11. Delete a job. - * 12. Delete a database. - * 13. Delete a crawler. - */ - -public class GlueScenario { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); - - public static void main(String[] args) throws InterruptedException { - final String usage = """ - - Usage: - \s - - Where: - iam - The ARN of the IAM role that has AWS Glue and S3 permissions.\s - s3Path - The Amazon Simple Storage Service (Amazon S3) target that contains data (for example, CSV data). - cron - A cron expression used to specify the schedule (i.e., cron(15 12 * * ? *). - dbName - The database name.\s - crawlerName - The name of the crawler.\s - jobName - The name you assign to this job definition. - scriptLocation - The Amazon S3 path to a script that runs a job. - locationUri - The location of the database - bucketNameSc - The Amazon S3 bucket name used when creating a job - """; - - if (args.length != 9) { - System.out.println(usage); - System.exit(1); - } - - String iam = args[0]; - String s3Path = args[1]; - String cron = args[2]; - String dbName = args[3]; - String crawlerName = args[4]; - String jobName = args[5]; - String scriptLocation = args[6]; - String locationUri = args[7]; - String bucketNameSc = args[8]; - - Region region = Region.US_EAST_1; - GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); - System.out.println(DASHES); - System.out.println("Welcome to the AWS Glue scenario."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("1. Create a database."); - createDatabase(glueClient, dbName, locationUri); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("2. Create a crawler."); - createGlueCrawler(glueClient, iam, s3Path, cron, dbName, crawlerName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("3. Get a crawler."); - getSpecificCrawler(glueClient, crawlerName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("4. Start a crawler."); - startSpecificCrawler(glueClient, crawlerName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("5. Get a database."); - getSpecificDatabase(glueClient, dbName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("*** Wait 5 min for the tables to become available"); - TimeUnit.MINUTES.sleep(5); - System.out.println("6. Get tables."); - String myTableName = getGlueTables(glueClient, dbName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("7. Create a job."); - createJob(glueClient, jobName, iam, scriptLocation); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("8. Start a Job run."); - startJob(glueClient, jobName, dbName, myTableName, bucketNameSc); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("9. List all jobs."); - getAllJobs(glueClient); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("10. Get job runs."); - getJobRuns(glueClient, jobName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("11. Delete a job."); - deleteJob(glueClient, jobName); - System.out.println("*** Wait 5 MIN for the " + crawlerName + " to stop"); - TimeUnit.MINUTES.sleep(5); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("12. Delete a database."); - deleteDatabase(glueClient, dbName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("Delete a crawler."); - deleteSpecificCrawler(glueClient, crawlerName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("Successfully completed the AWS Glue Scenario"); - System.out.println(DASHES); - } - - public static void createDatabase(GlueClient glueClient, String dbName, String locationUri) { - try { - DatabaseInput input = DatabaseInput.builder() - .description("Built with the AWS SDK for Java V2") - .name(dbName) - .locationUri(locationUri) - .build(); - - CreateDatabaseRequest request = CreateDatabaseRequest.builder() - .databaseInput(input) - .build(); - - glueClient.createDatabase(request); - System.out.println(dbName + " was successfully created"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void createGlueCrawler(GlueClient glueClient, - String iam, - String s3Path, - String cron, - String dbName, - String crawlerName) { - - try { - S3Target s3Target = S3Target.builder() - .path(s3Path) - .build(); - - List targetList = new ArrayList<>(); - targetList.add(s3Target); - CrawlerTargets targets = CrawlerTargets.builder() - .s3Targets(targetList) - .build(); - - CreateCrawlerRequest crawlerRequest = CreateCrawlerRequest.builder() - .databaseName(dbName) - .name(crawlerName) - .description("Created by the AWS Glue Java API") - .targets(targets) - .role(iam) - .schedule(cron) - .build(); - - glueClient.createCrawler(crawlerRequest); - System.out.println(crawlerName + " was successfully created"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void getSpecificCrawler(GlueClient glueClient, String crawlerName) { - try { - GetCrawlerRequest crawlerRequest = GetCrawlerRequest.builder() - .name(crawlerName) - .build(); - - boolean ready = false; - while (!ready) { - GetCrawlerResponse response = glueClient.getCrawler(crawlerRequest); - String status = response.crawler().stateAsString(); - if (status.compareTo("READY") == 0) { - ready = true; - } - Thread.sleep(3000); - } - - System.out.println("The crawler is now ready"); - - } catch (GlueException | InterruptedException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void startSpecificCrawler(GlueClient glueClient, String crawlerName) { - try { - StartCrawlerRequest crawlerRequest = StartCrawlerRequest.builder() - .name(crawlerName) - .build(); - - glueClient.startCrawler(crawlerRequest); - System.out.println(crawlerName + " was successfully started!"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void getSpecificDatabase(GlueClient glueClient, String databaseName) { - try { - GetDatabaseRequest databasesRequest = GetDatabaseRequest.builder() - .name(databaseName) - .build(); - - GetDatabaseResponse response = glueClient.getDatabase(databasesRequest); - Instant createDate = response.database().createTime(); - - // Convert the Instant to readable date. - DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - .withLocale(Locale.US) - .withZone(ZoneId.systemDefault()); - - formatter.format(createDate); - System.out.println("The create date of the database is " + createDate); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static String getGlueTables(GlueClient glueClient, String dbName) { - String myTableName = ""; - try { - GetTablesRequest tableRequest = GetTablesRequest.builder() - .databaseName(dbName) - .build(); - - GetTablesResponse response = glueClient.getTables(tableRequest); - List tables = response.tableList(); - if (tables.isEmpty()) { - System.out.println("No tables were returned"); - } else { - for (Table table : tables) { - myTableName = table.name(); - System.out.println("Table name is: " + myTableName); - } - } - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return myTableName; - } - - public static void startJob(GlueClient glueClient, String jobName, String inputDatabase, String inputTable, - String outBucket) { - try { - Map myMap = new HashMap<>(); - myMap.put("--input_database", inputDatabase); - myMap.put("--input_table", inputTable); - myMap.put("--output_bucket_url", outBucket); - - StartJobRunRequest runRequest = StartJobRunRequest.builder() - .workerType(WorkerType.G_1_X) - .numberOfWorkers(10) - .arguments(myMap) - .jobName(jobName) - .build(); - - StartJobRunResponse response = glueClient.startJobRun(runRequest); - System.out.println("The request Id of the job is " + response.responseMetadata().requestId()); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void createJob(GlueClient glueClient, String jobName, String iam, String scriptLocation) { - try { - JobCommand command = JobCommand.builder() - .pythonVersion("3") - .name("glueetl") - .scriptLocation(scriptLocation) - .build(); - - CreateJobRequest jobRequest = CreateJobRequest.builder() - .description("A Job created by using the AWS SDK for Java V2") - .glueVersion("2.0") - .workerType(WorkerType.G_1_X) - .numberOfWorkers(10) - .name(jobName) - .role(iam) - .command(command) - .build(); - - glueClient.createJob(jobRequest); - System.out.println(jobName + " was successfully created."); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void getAllJobs(GlueClient glueClient) { - try { - GetJobsRequest jobsRequest = GetJobsRequest.builder() - .maxResults(10) - .build(); - - GetJobsResponse jobsResponse = glueClient.getJobs(jobsRequest); - List jobs = jobsResponse.jobs(); - for (Job job : jobs) { - System.out.println("Job name is : " + job.name()); - System.out.println("The job worker type is : " + job.workerType().name()); - } - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void getJobRuns(GlueClient glueClient, String jobName) { - try { - GetJobRunsRequest runsRequest = GetJobRunsRequest.builder() - .jobName(jobName) - .maxResults(20) - .build(); - - boolean jobDone = false; - while (!jobDone) { - GetJobRunsResponse response = glueClient.getJobRuns(runsRequest); - List jobRuns = response.jobRuns(); - for (JobRun jobRun : jobRuns) { - String jobState = jobRun.jobRunState().name(); - if (jobState.compareTo("SUCCEEDED") == 0) { - System.out.println(jobName + " has succeeded"); - jobDone = true; - - } else if (jobState.compareTo("STOPPED") == 0) { - System.out.println("Job run has stopped"); - jobDone = true; - - } else if (jobState.compareTo("FAILED") == 0) { - System.out.println("Job run has failed"); - jobDone = true; - - } else if (jobState.compareTo("TIMEOUT") == 0) { - System.out.println("Job run has timed out"); - jobDone = true; - - } else { - System.out.println("*** Job run state is " + jobRun.jobRunState().name()); - System.out.println("Job run Id is " + jobRun.id()); - System.out.println("The Glue version is " + jobRun.glueVersion()); - } - TimeUnit.SECONDS.sleep(5); - } - } - - } catch (GlueException | InterruptedException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void deleteJob(GlueClient glueClient, String jobName) { - try { - DeleteJobRequest jobRequest = DeleteJobRequest.builder() - .jobName(jobName) - .build(); - - glueClient.deleteJob(jobRequest); - System.out.println(jobName + " was successfully deleted"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteDatabase(GlueClient glueClient, String databaseName) { - try { - DeleteDatabaseRequest request = DeleteDatabaseRequest.builder() - .name(databaseName) - .build(); - - glueClient.deleteDatabase(request); - System.out.println(databaseName + " was successfully deleted"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerName) { - try { - DeleteCrawlerRequest deleteCrawlerRequest = DeleteCrawlerRequest.builder() - .name(crawlerName) - .build(); - - glueClient.deleteCrawler(deleteCrawlerRequest); - System.out.println(crawlerName + " was deleted"); - - } catch (GlueException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.glue.scenario; + +// snippet-start:[glue.java2.scenario.import] + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.glue.GlueClient; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Scanner; +import java.util.concurrent.TimeUnit; + +import software.amazon.awssdk.services.glue.model.DatabaseInput; +import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest; +import software.amazon.awssdk.services.glue.model.GlueException; +import software.amazon.awssdk.services.glue.model.GetCrawlerResponse; +import software.amazon.awssdk.services.glue.model.GetCrawlerRequest; +import software.amazon.awssdk.services.glue.model.CreateCrawlerRequest; +import software.amazon.awssdk.services.glue.model.GetTablesResponse; +import software.amazon.awssdk.services.glue.model.GetTablesRequest; +import software.amazon.awssdk.services.glue.model.StartCrawlerRequest; +import software.amazon.awssdk.services.glue.model.GetDatabaseRequest; +import software.amazon.awssdk.services.glue.model.CrawlerTargets; +import software.amazon.awssdk.services.glue.model.GetDatabaseResponse; +import software.amazon.awssdk.services.glue.model.Table; +import software.amazon.awssdk.services.glue.model.StartJobRunResponse; +import software.amazon.awssdk.services.glue.model.StartJobRunRequest; +import software.amazon.awssdk.services.glue.model.GetJobsRequest; +import software.amazon.awssdk.services.glue.model.CreateJobRequest; +import software.amazon.awssdk.services.glue.model.GetJobRunsResponse; +import software.amazon.awssdk.services.glue.model.GetJobsResponse; +import software.amazon.awssdk.services.glue.model.Job; +import software.amazon.awssdk.services.glue.model.WorkerType; +import software.amazon.awssdk.services.glue.model.JobCommand; +import software.amazon.awssdk.services.glue.model.GetJobRunsRequest; +import software.amazon.awssdk.services.glue.model.JobRun; +import software.amazon.awssdk.services.glue.model.S3Target; +import software.amazon.awssdk.services.glue.model.DeleteJobRequest; +import software.amazon.awssdk.services.glue.model.DeleteDatabaseRequest; +import software.amazon.awssdk.services.glue.model.DeleteCrawlerRequest; +// snippet-end:[glue.java2.scenario.import] + +// snippet-start:[glue.java2.scenario.main] + +/** + * 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 + *

+ * To set up the resources, see this documentation topic: + *

+ * https://docs.aws.amazon.com/glue/latest/ug/tutorial-add-crawler.html + *

+ * This example performs the following tasks: + *

+ * 1. Create a database. + * 2. Create a crawler. + * 3. Get a crawler. + * 4. Start a crawler. + * 5. Get a database. + * 6. Get tables. + * 7. Create a job. + * 8. Start a job run. + * 9. List all jobs. + * 10. Get job runs. + * 11. Delete a job. + * 12. Delete a database. + * 13. Delete a crawler. + */ + +public class GlueScenario { + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + + public static void main(String[] args) throws InterruptedException { + final String usage = """ + + Usage: + \s + + Where: + iam - The ARN of the IAM role that has AWS Glue and S3 permissions.\s + s3Path - The Amazon Simple Storage Service (Amazon S3) target that contains data (for example, CSV data). + cron - A cron expression used to specify the schedule (i.e., cron(15 12 * * ? *). + dbName - The database name.\s + crawlerName - The name of the crawler.\s + jobName - The name you assign to this job definition. + scriptLocation - The Amazon S3 path to a script that runs a job. + locationUri - The location of the database + bucketNameSc - The Amazon S3 bucket name used when creating a job + """; + + if (args.length != 9) { + System.out.println(usage); + return; + } + Scanner scanner = new Scanner(System.in); + String iam = args[0]; + String s3Path = args[1]; + String cron = args[2]; + String dbName = args[3]; + String crawlerName = args[4]; + String jobName = args[5]; + String scriptLocation = args[6]; + String locationUri = args[7]; + String bucketNameSc = args[8]; + + Region region = Region.US_EAST_1; + GlueClient glueClient = GlueClient.builder() + .region(region) + .build(); + System.out.println(DASHES); + System.out.println("Welcome to the AWS Glue scenario."); + System.out.println(""" + AWS Glue is a fully managed extract, transform, and load (ETL) service provided by Amazon + Web Services (AWS). It is designed to simplify the process of building, running, and maintaining + ETL pipelines, which are essential for data integration and data warehousing tasks. + + One of the key features of AWS Glue is its ability to automatically discover and catalog data + stored in various sources, such as Amazon S3, Amazon RDS, Amazon Redshift, and other databases. + This cataloging process creates a central metadata repository, known as the AWS Glue Data Catalog, + which provides a unified view of an organization's data assets. This metadata can then be used to + create ETL jobs, which can be scheduled and run on-demand or on a regular basis. + + Lets get started. + + """); + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("1. Create a database."); + try { + createDatabase(glueClient, dbName, locationUri); + } catch (GlueException e) { + if (e.awsErrorDetails().errorMessage().equals("Database already exists.")) { + System.out.println("Database " + dbName + " already exists. Skipping creation."); + } else { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + } + + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("2. Create a crawler."); + try { + createGlueCrawler(glueClient, iam, s3Path, cron, dbName, crawlerName); + } catch (GlueException e) { + if (e.awsErrorDetails().errorMessage().contains("already exists")) { + System.out.println("Crawler " + crawlerName + " already exists. Skipping creation."); + } else { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("3. Get a crawler."); + try { + getSpecificCrawler(glueClient, crawlerName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("4. Start a crawler."); + try { + startSpecificCrawler(glueClient, crawlerName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("5. Get a database."); + try { + getSpecificDatabase(glueClient, dbName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("*** Wait 5 min for the tables to become available"); + TimeUnit.MINUTES.sleep(5); + System.out.println("6. Get tables."); + String myTableName; + try { + myTableName = getGlueTables(glueClient, dbName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("7. Create a job."); + try { + createJob(glueClient, jobName, iam, scriptLocation); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("8. Start a Job run."); + try { + startJob(glueClient, jobName, dbName, myTableName, bucketNameSc); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("9. List all jobs."); + try { + getAllJobs(glueClient); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("10. Get job runs."); + try { + getJobRuns(glueClient, jobName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("11. Delete a job."); + try { + deleteJob(glueClient, jobName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + System.out.println("*** Wait 5 MIN for the " + crawlerName + " to stop"); + TimeUnit.MINUTES.sleep(5); + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("12. Delete a database."); + try { + deleteDatabase(glueClient, dbName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("Delete a crawler."); + try { + deleteSpecificCrawler(glueClient, crawlerName); + } catch (GlueException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return; + } + waitForInputToContinue(scanner); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("Successfully completed the AWS Glue Scenario"); + System.out.println(DASHES); + } + + // snippet-start:[glue.java2.create_database.main] + + /** + * Creates a Glue database with the specified name and location URI. + * + * @param glueClient The Glue client to use for the database creation. + * @param dbName The name of the database to create. + * @param locationUri The location URI for the database. + */ + public static void createDatabase(GlueClient glueClient, String dbName, String locationUri) { + try { + DatabaseInput input = DatabaseInput.builder() + .description("Built with the AWS SDK for Java V2") + .name(dbName) + .locationUri(locationUri) + .build(); + + CreateDatabaseRequest request = CreateDatabaseRequest.builder() + .databaseInput(input) + .build(); + + glueClient.createDatabase(request); + System.out.println(dbName + " was successfully created"); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.create_database.main] + + // snippet-start:[glue.java2.create_crawler.main] + + /** + * Creates a new AWS Glue crawler using the AWS Glue Java API. + * + * @param glueClient the AWS Glue client used to interact with the AWS Glue service + * @param iam the IAM role that the crawler will use to access the data source + * @param s3Path the S3 path that the crawler will scan for data + * @param cron the cron expression that defines the crawler's schedule + * @param dbName the name of the AWS Glue database where the crawler will store the metadata + * @param crawlerName the name of the crawler to be created + */ + public static void createGlueCrawler(GlueClient glueClient, + String iam, + String s3Path, + String cron, + String dbName, + String crawlerName) { + + try { + S3Target s3Target = S3Target.builder() + .path(s3Path) + .build(); + + List targetList = new ArrayList<>(); + targetList.add(s3Target); + CrawlerTargets targets = CrawlerTargets.builder() + .s3Targets(targetList) + .build(); + + CreateCrawlerRequest crawlerRequest = CreateCrawlerRequest.builder() + .databaseName(dbName) + .name(crawlerName) + .description("Created by the AWS Glue Java API") + .targets(targets) + .role(iam) + .schedule(cron) + .build(); + + glueClient.createCrawler(crawlerRequest); + System.out.println(crawlerName + " was successfully created"); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.create_crawler.main] + + // snippet-start:[glue.java2.get_crawler.main] + + /** + * Retrieves a specific crawler from the AWS Glue service and waits for it to be in the "READY" state. + * + * @param glueClient the AWS Glue client used to interact with the Glue service + * @param crawlerName the name of the crawler to be retrieved + */ + public static void getSpecificCrawler(GlueClient glueClient, String crawlerName) throws InterruptedException { + try { + GetCrawlerRequest crawlerRequest = GetCrawlerRequest.builder() + .name(crawlerName) + .build(); + + boolean ready = false; + while (!ready) { + GetCrawlerResponse response = glueClient.getCrawler(crawlerRequest); + String status = response.crawler().stateAsString(); + if (status.compareTo("READY") == 0) { + ready = true; + } + Thread.sleep(3000); + } + + System.out.println("The crawler is now ready"); + + } catch (GlueException | InterruptedException e) { + throw e; + } + } + // snippet-end:[glue.java2.get_crawler.main] + + // snippet-start:[glue.java2.start_crawler.main] + /** + * Starts a specific AWS Glue crawler. + * + * @param glueClient the AWS Glue client to use for the crawler operation + * @param crawlerName the name of the crawler to start + * @throws GlueException if there is an error starting the crawler + */ + public static void startSpecificCrawler(GlueClient glueClient, String crawlerName) { + try { + StartCrawlerRequest crawlerRequest = StartCrawlerRequest.builder() + .name(crawlerName) + .build(); + + glueClient.startCrawler(crawlerRequest); + System.out.println(crawlerName + " was successfully started!"); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.start_crawler.main] + + // snippet-start:[glue.java2.get_database.main] + + /** + * Retrieves the specific database from the AWS Glue service. + * + * @param glueClient an instance of the AWS Glue client used to interact with the service + * @param databaseName the name of the database to retrieve + * @throws GlueException if there is an error retrieving the database from the AWS Glue service + */ + public static void getSpecificDatabase(GlueClient glueClient, String databaseName) { + try { + GetDatabaseRequest databasesRequest = GetDatabaseRequest.builder() + .name(databaseName) + .build(); + + GetDatabaseResponse response = glueClient.getDatabase(databasesRequest); + Instant createDate = response.database().createTime(); + + // Convert the Instant to readable date. + DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + .withLocale(Locale.US) + .withZone(ZoneId.systemDefault()); + + formatter.format(createDate); + System.out.println("The create date of the database is " + createDate); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.get_database.main] + + // snippet-start:[glue.java2.get_tables.main] + + /** + * Retrieves the names of the tables in the specified Glue database. + * + * @param glueClient the Glue client to use for the operation + * @param dbName the name of the Glue database to retrieve the table names from + * @return the name of the first table retrieved, or an empty string if no tables were found + */ + public static String getGlueTables(GlueClient glueClient, String dbName) { + String myTableName = ""; + try { + GetTablesRequest tableRequest = GetTablesRequest.builder() + .databaseName(dbName) + .build(); + + GetTablesResponse response = glueClient.getTables(tableRequest); + List

tables = response.tableList(); + if (tables.isEmpty()) { + System.out.println("No tables were returned"); + } else { + for (Table table : tables) { + myTableName = table.name(); + System.out.println("Table name is: " + myTableName); + } + } + + } catch (GlueException e) { + throw e; + } + return myTableName; + } + // snippet-end:[glue.java2.get_tables.main] + + // snippet-start:[glue.java2.start.job.main] + + /** + * Starts a job run in AWS Glue. + * + * @param glueClient the AWS Glue client to use for the job run + * @param jobName the name of the Glue job to run + * @param inputDatabase the name of the input database + * @param inputTable the name of the input table + * @param outBucket the URL of the output S3 bucket + * @throws GlueException if there is an error starting the job run + */ + public static void startJob(GlueClient glueClient, String jobName, String inputDatabase, String inputTable, + String outBucket) { + try { + Map myMap = new HashMap<>(); + myMap.put("--input_database", inputDatabase); + myMap.put("--input_table", inputTable); + myMap.put("--output_bucket_url", outBucket); + + StartJobRunRequest runRequest = StartJobRunRequest.builder() + .workerType(WorkerType.G_1_X) + .numberOfWorkers(10) + .arguments(myMap) + .jobName(jobName) + .build(); + + StartJobRunResponse response = glueClient.startJobRun(runRequest); + System.out.println("The request Id of the job is " + response.responseMetadata().requestId()); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.start.job.main] + + // snippet-start:[glue.java2.create_job.main] + + /** + * Creates a new AWS Glue job. + * + * @param glueClient the AWS Glue client to use for the operation + * @param jobName the name of the job to create + * @param iam the IAM role to associate with the job + * @param scriptLocation the location of the script to be used by the job + * @throws GlueException if there is an error creating the job + */ + public static void createJob(GlueClient glueClient, String jobName, String iam, String scriptLocation) { + try { + JobCommand command = JobCommand.builder() + .pythonVersion("3") + .name("glueetl") + .scriptLocation(scriptLocation) + .build(); + + CreateJobRequest jobRequest = CreateJobRequest.builder() + .description("A Job created by using the AWS SDK for Java V2") + .glueVersion("2.0") + .workerType(WorkerType.G_1_X) + .numberOfWorkers(10) + .name(jobName) + .role(iam) + .command(command) + .build(); + + glueClient.createJob(jobRequest); + System.out.println(jobName + " was successfully created."); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.create_job.main] + + // snippet-start:[glue.java2.get_jobs.main] + + /** + * Retrieves and prints information about all the jobs in the Glue data catalog. + * + * @param glueClient the Glue client used to interact with the AWS Glue service + */ + public static void getAllJobs(GlueClient glueClient) { + try { + GetJobsRequest jobsRequest = GetJobsRequest.builder() + .maxResults(10) + .build(); + + GetJobsResponse jobsResponse = glueClient.getJobs(jobsRequest); + List jobs = jobsResponse.jobs(); + for (Job job : jobs) { + System.out.println("Job name is : " + job.name()); + System.out.println("The job worker type is : " + job.workerType().name()); + } + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.get_jobs.main] + + // snippet-start:[glue.java2.get_job.main] + + /** + * Retrieves the job runs for a given Glue job and prints the status of the job runs. + * + * @param glueClient the Glue client used to make API calls + * @param jobName the name of the Glue job to retrieve the job runs for + */ + public static void getJobRuns(GlueClient glueClient, String jobName) { + try { + GetJobRunsRequest runsRequest = GetJobRunsRequest.builder() + .jobName(jobName) + .maxResults(20) + .build(); + + boolean jobDone = false; + while (!jobDone) { + GetJobRunsResponse response = glueClient.getJobRuns(runsRequest); + List jobRuns = response.jobRuns(); + for (JobRun jobRun : jobRuns) { + String jobState = jobRun.jobRunState().name(); + if (jobState.compareTo("SUCCEEDED") == 0) { + System.out.println(jobName + " has succeeded"); + jobDone = true; + + } else if (jobState.compareTo("STOPPED") == 0) { + System.out.println("Job run has stopped"); + jobDone = true; + + } else if (jobState.compareTo("FAILED") == 0) { + System.out.println("Job run has failed"); + jobDone = true; + + } else if (jobState.compareTo("TIMEOUT") == 0) { + System.out.println("Job run has timed out"); + jobDone = true; + + } else { + System.out.println("*** Job run state is " + jobRun.jobRunState().name()); + System.out.println("Job run Id is " + jobRun.id()); + System.out.println("The Glue version is " + jobRun.glueVersion()); + } + TimeUnit.SECONDS.sleep(5); + } + } + + } catch (GlueException e) { + throw e; + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + // snippet-end:[glue.java2.get_job.main] + + // snippet-start:[glue.java2.delete_job.main] + + /** + * Deletes a Glue job. + * + * @param glueClient the Glue client to use for the operation + * @param jobName the name of the job to be deleted + * @throws GlueException if there is an error deleting the job + */ + public static void deleteJob(GlueClient glueClient, String jobName) { + try { + DeleteJobRequest jobRequest = DeleteJobRequest.builder() + .jobName(jobName) + .build(); + + glueClient.deleteJob(jobRequest); + System.out.println(jobName + " was successfully deleted"); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.delete_job.main] + + // snippet-start:[glue.java2.delete_database.main] + + /** + * Deletes a AWS Glue Database. + * + * @param glueClient An instance of the AWS Glue client used to interact with the AWS Glue service. + * @param databaseName The name of the database to be deleted. + * @throws GlueException If an error occurs while deleting the database. + */ + public static void deleteDatabase(GlueClient glueClient, String databaseName) { + try { + DeleteDatabaseRequest request = DeleteDatabaseRequest.builder() + .name(databaseName) + .build(); + + glueClient.deleteDatabase(request); + System.out.println(databaseName + " was successfully deleted"); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.delete_database.main] + + // snippet-start:[glue.java2.delete_crawler.main] + + /** + * Deletes a specific AWS Glue crawler. + * + * @param glueClient the AWS Glue client object + * @param crawlerName the name of the crawler to be deleted + * @throws GlueException if an error occurs during the deletion process + */ + public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerName) { + try { + DeleteCrawlerRequest deleteCrawlerRequest = DeleteCrawlerRequest.builder() + .name(crawlerName) + .build(); + + glueClient.deleteCrawler(deleteCrawlerRequest); + System.out.println(crawlerName + " was deleted"); + + } catch (GlueException e) { + throw e; + } + } + // snippet-end:[glue.java2.delete_crawler.main] + + private static void waitForInputToContinue(Scanner scanner) { + while (true) { + System.out.println(""); + System.out.println("Enter 'c' followed by to continue:"); + String input = scanner.nextLine(); + + if (input.trim().equalsIgnoreCase("c")) { + System.out.println("Continuing with the program..."); + System.out.println(""); + break; + } else { + // Handle invalid input. + System.out.println("Invalid input. Please try again."); + } + } + } +} // snippet-end:[glue.java2.scenario.main] \ No newline at end of file diff --git a/javav2/example_code/glue/src/test/java/GlueTest.java b/javav2/example_code/glue/src/test/java/GlueTest.java index 7aacd8f95bc..bb26061c38c 100644 --- a/javav2/example_code/glue/src/test/java/GlueTest.java +++ b/javav2/example_code/glue/src/test/java/GlueTest.java @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import com.example.glue.*; +import com.example.glue.scenario.GlueScenario; import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.glue.GlueClient; @@ -10,10 +10,13 @@ import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; + import java.io.*; import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + /** * To run these integration tests, you must set the required values * in the config.properties file or AWS Secrets Manager. @@ -41,11 +44,11 @@ public class GlueTest { private static String bucketNameSc = ""; @BeforeAll - public static void setUp() throws IOException, URISyntaxException { + public static void setUp() { glueClient = GlueClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -61,86 +64,148 @@ public static void setUp() throws IOException, URISyntaxException { existingDatabaseName = values.getExistingDatabaseName(); existingCrawlerName = values.getExistingCrawlerName(); jobNameSc = values.getJobNameSc() + java.util.UUID.randomUUID(); - ; s3PathSc = values.getS3PathSc() + java.util.UUID.randomUUID(); - ; dbNameSc = values.getDbNameSc() + java.util.UUID.randomUUID(); crawlerNameSc = values.getCrawlerNameSc() + java.util.UUID.randomUUID(); scriptLocationSc = values.getScriptLocationSc(); locationUri = values.getLocationUri(); bucketNameSc = values.getBucketNameSc(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * GlueTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * crawlerName = prop.getProperty("crawlerName"); - * s3Path = prop.getProperty("s3Path"); - * cron = prop.getProperty("cron"); - * IAM = prop.getProperty("IAM"); - * databaseName = prop.getProperty("databaseName"); - * tableName = prop.getProperty("tableName"); - * text = prop.getProperty("text"); - * existingDatabaseName = prop.getProperty("existingDatabaseName"); - * existingCrawlerName = prop.getProperty("existingCrawlerName"); - * jobNameSc = prop.getProperty("jobNameSc")+ java.util.UUID.randomUUID();; - * s3PathSc = prop.getProperty("s3PathSc")+ java.util.UUID.randomUUID();; - * dbNameSc = prop.getProperty("dbNameSc")+ java.util.UUID.randomUUID(); - * crawlerNameSc = prop.getProperty("crawlerNameSc")+ - * java.util.UUID.randomUUID(); - * scriptLocationSc = prop.getProperty("scriptLocationSc"); - * locationUri = prop.getProperty("locationUri"); - * bucketNameSc = prop.getProperty("bucketNameSc"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test @Tag("IntegrationTest") @Order(1) - public void ScenarioTest() throws InterruptedException { - GlueScenario.createDatabase(glueClient, dbNameSc, locationUri); - GlueScenario.createGlueCrawler(glueClient, IAM, s3PathSc, cron, dbNameSc, crawlerNameSc); - GlueScenario.getSpecificCrawler(glueClient, crawlerNameSc); - GlueScenario.startSpecificCrawler(glueClient, crawlerNameSc); - GlueScenario.getSpecificDatabase(glueClient, dbNameSc); - - System.out.println("Wait 5 min for the tables to become available"); - TimeUnit.MINUTES.sleep(5);// Sleep for 5 minute to get tables ready - String myTableName = GlueScenario.getGlueTables(glueClient, dbNameSc); - GlueScenario.createJob(glueClient, jobNameSc, IAM, scriptLocationSc); - GlueScenario.startJob(glueClient, jobNameSc, dbNameSc, myTableName, bucketNameSc); - GlueScenario.getAllJobs(glueClient); - GlueScenario.getJobRuns(glueClient, jobNameSc); - GlueScenario.deleteJob(glueClient, jobNameSc); - System.out.println("*** Wait 5 MIN for the " + crawlerNameSc + " to stop"); - TimeUnit.MINUTES.sleep(5); - GlueScenario.deleteDatabase(glueClient, dbNameSc); - GlueScenario.deleteSpecificCrawler(glueClient, crawlerNameSc); + void testCreateDatabase() { + assertDoesNotThrow(() -> { + GlueScenario.createDatabase(glueClient, dbNameSc, locationUri); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(2) + void testCreateGlueCrawler() { + assertDoesNotThrow(() -> { + GlueScenario.createGlueCrawler(glueClient, IAM, s3PathSc, cron, dbNameSc, crawlerNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(3) + void testGetSpecificCrawler() { + assertDoesNotThrow(() -> { + GlueScenario.getSpecificCrawler(glueClient, crawlerNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(4) + void testStartSpecificCrawler() { + assertDoesNotThrow(() -> { + GlueScenario.startSpecificCrawler(glueClient, crawlerNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(5) + void testGetSpecificDatabase() { + assertDoesNotThrow(() -> { + GlueScenario.getSpecificDatabase(glueClient, dbNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(6) + void testGetTable() { + assertDoesNotThrow(() -> { + System.out.println("*** Wait 5 min for the tables to become available"); + TimeUnit.MINUTES.sleep(5); + System.out.println("6. Get tables."); + GlueScenario.getGlueTables(glueClient, dbNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(7) + void testCreateJob() { + assertDoesNotThrow(() -> { + GlueScenario.createJob(glueClient, jobNameSc, IAM, scriptLocationSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(8) + void testStartJob() { + assertDoesNotThrow(() -> { + GlueScenario.startJob(glueClient, jobNameSc, dbNameSc, tableName, bucketNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(9) + void testGetJobs() { + assertDoesNotThrow(() -> { + GlueScenario.getAllJobs(glueClient); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(10) + void testRunJobs() { + assertDoesNotThrow(() -> { + GlueScenario.getJobRuns(glueClient, jobNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(11) + void testDeleteJob() { + assertDoesNotThrow(() -> { + GlueScenario.deleteJob(glueClient, jobNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(12) + void testDeleteDB() { + assertDoesNotThrow(() -> { + System.out.println("*** Wait 5 MIN for the " + crawlerNameSc + " to stop"); + TimeUnit.MINUTES.sleep(5); + GlueScenario.deleteDatabase(glueClient, dbNameSc); + }); + } + + @Test + @Tag("IntegrationTest") + @Order(13) + void testDelCrawler() { + assertDoesNotThrow(() -> { + System.out.println("*** Wait 5 MIN for the " + crawlerNameSc + " to stop"); + TimeUnit.MINUTES.sleep(5); + GlueScenario.deleteSpecificCrawler(glueClient, crawlerNameSc); + }); } private static String getSecretValues() { - // Get the Amazon RDS creds from Secrets Manager. SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/glue"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/iam/README.md b/javav2/example_code/iam/README.md index a7a147ed0fc..0edb192f960 100644 --- a/javav2/example_code/iam/README.md +++ b/javav2/example_code/iam/README.md @@ -34,6 +34,13 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav - [Hello IAM](src/main/java/com/example/iam/HelloIAM.java#L6) (`ListPolicies`) +### Basics + +Code examples that show you how to perform the essential operations within a service. + +- [Create a user and assume a role](src/main/java/com/example/iam/scenario/IAMScenario.java) + + ### Single actions Code excerpts that show you how to call individual service functions. @@ -61,7 +68,6 @@ Code examples that show you how to accomplish a specific task by calling multipl functions within the same service. - [Build and manage a resilient service](../../usecases/resilient_service/src/main/java/com/example/resilient/Main.java) -- [Create a user and assume a role](src/main/java/com/example/iam/IAMScenario.java) - [Work with the IAM Policy Builder API](src/main/java/com/example/iam/IamPolicyBuilderExamples.java) @@ -81,6 +87,22 @@ functions within the same service. This example shows you how to get started using IAM. +#### Create a user and assume a role + +This example shows you how to create a user and assume a role. + +- Create a user with no permissions. +- Create a role that grants permission to list Amazon S3 buckets for the account. +- Add a policy to let the user assume the role. +- Assume the role and list S3 buckets using temporary credentials, then clean up resources. + + + + + + + + #### Build and manage a resilient service @@ -100,22 +122,6 @@ This example shows you how to create a load-balanced web service that returns bo -#### Create a user and assume a role - -This example shows you how to create a user and assume a role. - -- Create a user with no permissions. -- Create a role that grants permission to list Amazon S3 buckets for the account. -- Add a policy to let the user assume the role. -- Assume the role and list S3 buckets using temporary credentials, then clean up resources. - - - - - - - - #### Work with the IAM Policy Builder API This example shows you how to do the following: diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java b/javav2/example_code/iam/src/main/java/com/example/iam/scenario/IAMScenario.java similarity index 68% rename from javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java rename to javav2/example_code/iam/src/main/java/com/example/iam/scenario/IAMScenario.java index 11d575331c5..d625b9046c0 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/scenario/IAMScenario.java @@ -1,416 +1,484 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.iam; - -// snippet-start:[iam.java2.scenario.import] -import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; -import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; -import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.iam.IamClient; -import software.amazon.awssdk.services.iam.model.AccessKey; -import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest; -import software.amazon.awssdk.services.iam.model.AttachedPolicy; -import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest; -import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse; -import software.amazon.awssdk.services.iam.model.CreatePolicyRequest; -import software.amazon.awssdk.services.iam.model.CreatePolicyResponse; -import software.amazon.awssdk.services.iam.model.CreateRoleRequest; -import software.amazon.awssdk.services.iam.model.CreateRoleResponse; -import software.amazon.awssdk.services.iam.model.CreateUserRequest; -import software.amazon.awssdk.services.iam.model.CreateUserResponse; -import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest; -import software.amazon.awssdk.services.iam.model.DeletePolicyRequest; -import software.amazon.awssdk.services.iam.model.DeleteRoleRequest; -import software.amazon.awssdk.services.iam.model.DeleteUserRequest; -import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest; -import software.amazon.awssdk.services.iam.model.GetPolicyRequest; -import software.amazon.awssdk.services.iam.model.GetPolicyResponse; -import software.amazon.awssdk.services.iam.model.GetUserRequest; -import software.amazon.awssdk.services.iam.model.GetUserResponse; -import software.amazon.awssdk.services.iam.model.IamException; -import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest; -import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse; -import software.amazon.awssdk.services.iam.model.User; -import software.amazon.awssdk.services.iam.waiters.IamWaiter; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListObjectsRequest; -import software.amazon.awssdk.services.s3.model.ListObjectsResponse; -import software.amazon.awssdk.services.s3.model.S3Object; -import software.amazon.awssdk.services.sts.StsClient; -import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; -import software.amazon.awssdk.services.sts.model.AssumeRoleResponse; -import software.amazon.awssdk.services.sts.model.Credentials; -import software.amazon.awssdk.services.sts.model.StsException; -import java.util.List; -import java.util.concurrent.TimeUnit; -// snippet-end:[iam.java2.scenario.import] - -// snippet-start:[iam.java2.scenario.main] -/* - To run this Java V2 code example, set up your development environment, including your credentials. - - For information, see this documentation topic: - - https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - - This example performs these operations: - - 1. Creates a user that has no permissions. - 2. Creates a role and policy that grants Amazon S3 permissions. - 3. Creates a role. - 4. Grants the user permissions. - 5. Gets temporary credentials by assuming the role. Creates an Amazon S3 Service client object with the temporary credentials. - 6. Deletes the resources. - */ - -public class IAMScenario { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); - public static final String PolicyDocument = "{" + - " \"Version\": \"2012-10-17\"," + - " \"Statement\": [" + - " {" + - " \"Effect\": \"Allow\"," + - " \"Action\": [" + - " \"s3:*\"" + - " ]," + - " \"Resource\": \"*\"" + - " }" + - " ]" + - "}"; - - public static String userArn; - - public static void main(String[] args) throws Exception { - - final String usage = """ - - Usage: - \s - - Where: - username - The name of the IAM user to create.\s - policyName - The name of the policy to create.\s - roleName - The name of the role to create.\s - roleSessionName - The name of the session required for the assumeRole operation.\s - bucketName - The name of the Amazon S3 bucket from which objects are read.\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String userName = args[0]; - String policyName = args[1]; - String roleName = args[2]; - String roleSessionName = args[3]; - String bucketName = args[4]; - - Region region = Region.AWS_GLOBAL; - IamClient iam = IamClient.builder() - .region(region) - .build(); - - System.out.println(DASHES); - System.out.println("Welcome to the AWS IAM example scenario."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println(" 1. Create the IAM user."); - User createUser = createIAMUser(iam, userName); - - System.out.println(DASHES); - userArn = createUser.arn(); - - AccessKey myKey = createIAMAccessKey(iam, userName); - String accessKey = myKey.accessKeyId(); - String secretKey = myKey.secretAccessKey(); - String assumeRolePolicyDocument = "{" + - "\"Version\": \"2012-10-17\"," + - "\"Statement\": [{" + - "\"Effect\": \"Allow\"," + - "\"Principal\": {" + - " \"AWS\": \"" + userArn + "\"" + - "}," + - "\"Action\": \"sts:AssumeRole\"" + - "}]" + - "}"; - - System.out.println(assumeRolePolicyDocument); - System.out.println(userName + " was successfully created."); - System.out.println(DASHES); - System.out.println("2. Creates a policy."); - String polArn = createIAMPolicy(iam, policyName); - System.out.println("The policy " + polArn + " was successfully created."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("3. Creates a role."); - TimeUnit.SECONDS.sleep(30); - String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument); - System.out.println(roleArn + " was successfully created."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("4. Grants the user permissions."); - attachIAMRolePolicy(iam, roleName, polArn); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("*** Wait for 30 secs so the resource is available"); - TimeUnit.SECONDS.sleep(30); - System.out.println("5. Gets temporary credentials by assuming the role."); - System.out.println("Perform an Amazon S3 Service operation using the temporary credentials."); - assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("6 Getting ready to delete the AWS resources"); - deleteKey(iam, userName, accessKey); - deleteRole(iam, roleName, polArn); - deleteIAMUser(iam, userName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("This IAM Scenario has successfully completed"); - System.out.println(DASHES); - } - - public static AccessKey createIAMAccessKey(IamClient iam, String user) { - try { - CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() - .userName(user) - .build(); - - CreateAccessKeyResponse response = iam.createAccessKey(request); - return response.accessKey(); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return null; - } - - public static User createIAMUser(IamClient iam, String username) { - try { - // Create an IamWaiter object - IamWaiter iamWaiter = iam.waiter(); - CreateUserRequest request = CreateUserRequest.builder() - .userName(username) - .build(); - - // Wait until the user is created. - CreateUserResponse response = iam.createUser(request); - GetUserRequest userRequest = GetUserRequest.builder() - .userName(response.user().userName()) - .build(); - - WaiterResponse waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); - waitUntilUserExists.matched().response().ifPresent(System.out::println); - return response.user(); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return null; - } - - public static String createIAMRole(IamClient iam, String rolename, String json) { - - try { - CreateRoleRequest request = CreateRoleRequest.builder() - .roleName(rolename) - .assumeRolePolicyDocument(json) - .description("Created using the AWS SDK for Java") - .build(); - - CreateRoleResponse response = iam.createRole(request); - System.out.println("The ARN of the role is " + response.role().arn()); - return response.role().arn(); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return ""; - } - - public static String createIAMPolicy(IamClient iam, String policyName) { - try { - // Create an IamWaiter object. - IamWaiter iamWaiter = iam.waiter(); - CreatePolicyRequest request = CreatePolicyRequest.builder() - .policyName(policyName) - .policyDocument(PolicyDocument).build(); - - CreatePolicyResponse response = iam.createPolicy(request); - GetPolicyRequest polRequest = GetPolicyRequest.builder() - .policyArn(response.policy().arn()) - .build(); - - WaiterResponse waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); - waitUntilPolicyExists.matched().response().ifPresent(System.out::println); - return response.policy().arn(); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return ""; - } - - public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) { - try { - ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() - .roleName(roleName) - .build(); - - ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); - List attachedPolicies = response.attachedPolicies(); - String polArn; - for (AttachedPolicy policy : attachedPolicies) { - polArn = policy.policyArn(); - if (polArn.compareTo(policyArn) == 0) { - System.out.println(roleName + " policy is already attached to this role."); - return; - } - } - - AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() - .roleName(roleName) - .policyArn(policyArn) - .build(); - - iam.attachRolePolicy(attachRequest); - System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // Invoke an Amazon S3 operation using the Assumed Role. - // snippet-start:[iam.java2.scenario.assumeRole] - public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal, - String keySecret) { - - // Use the creds of the new IAM user that was created in this code example. - AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret); - StsClient stsClient = StsClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(StaticCredentialsProvider.create(credentials)) - .build(); - - try { - AssumeRoleRequest roleRequest = AssumeRoleRequest.builder() - .roleArn(roleArn) - .roleSessionName(roleSessionName) - .build(); - - AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest); - Credentials myCreds = roleResponse.credentials(); - String key = myCreds.accessKeyId(); - String secKey = myCreds.secretAccessKey(); - String secToken = myCreds.sessionToken(); - - // List all objects in an Amazon S3 bucket using the temp creds retrieved by - // invoking assumeRole. - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .credentialsProvider( - StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken))) - .region(region) - .build(); - - System.out.println("Created a S3Client using temp credentials."); - System.out.println("Listing objects in " + bucketName); - ListObjectsRequest listObjects = ListObjectsRequest.builder() - .bucket(bucketName) - .build(); - - ListObjectsResponse res = s3.listObjects(listObjects); - List objects = res.contents(); - for (S3Object myValue : objects) { - System.out.println("The name of the key is " + myValue.key()); - System.out.println("The owner is " + myValue.owner()); - } - - } catch (StsException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - // snippet-end:[iam.java2.scenario.assumeRole] - public static void deleteRole(IamClient iam, String roleName, String polArn) { - - try { - // First the policy needs to be detached. - DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder() - .policyArn(polArn) - .roleName(roleName) - .build(); - - iam.detachRolePolicy(rolePolicyRequest); - - // Delete the policy. - DeletePolicyRequest request = DeletePolicyRequest.builder() - .policyArn(polArn) - .build(); - - iam.deletePolicy(request); - System.out.println("*** Successfully deleted " + polArn); - - // Delete the role. - DeleteRoleRequest roleRequest = DeleteRoleRequest.builder() - .roleName(roleName) - .build(); - - iam.deleteRole(roleRequest); - System.out.println("*** Successfully deleted " + roleName); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteKey(IamClient iam, String username, String accessKey) { - try { - DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() - .accessKeyId(accessKey) - .userName(username) - .build(); - - iam.deleteAccessKey(request); - System.out.println("Successfully deleted access key " + accessKey + - " from user " + username); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteIAMUser(IamClient iam, String userName) { - try { - DeleteUserRequest request = DeleteUserRequest.builder() - .userName(userName) - .build(); - - iam.deleteUser(request); - System.out.println("*** Successfully deleted " + userName); - - } catch (IamException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.iam.scenario; + +// snippet-start:[iam.java2.scenario.import] + +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.AccessKey; +import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest; +import software.amazon.awssdk.services.iam.model.AttachedPolicy; +import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest; +import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse; +import software.amazon.awssdk.services.iam.model.CreatePolicyRequest; +import software.amazon.awssdk.services.iam.model.CreatePolicyResponse; +import software.amazon.awssdk.services.iam.model.CreateRoleRequest; +import software.amazon.awssdk.services.iam.model.CreateRoleResponse; +import software.amazon.awssdk.services.iam.model.CreateUserRequest; +import software.amazon.awssdk.services.iam.model.CreateUserResponse; +import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest; +import software.amazon.awssdk.services.iam.model.DeletePolicyRequest; +import software.amazon.awssdk.services.iam.model.DeleteRoleRequest; +import software.amazon.awssdk.services.iam.model.DeleteUserRequest; +import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest; +import software.amazon.awssdk.services.iam.model.GetPolicyRequest; +import software.amazon.awssdk.services.iam.model.GetPolicyResponse; +import software.amazon.awssdk.services.iam.model.GetUserRequest; +import software.amazon.awssdk.services.iam.model.GetUserResponse; +import software.amazon.awssdk.services.iam.model.IamException; +import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest; +import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse; +import software.amazon.awssdk.services.iam.model.User; +import software.amazon.awssdk.services.iam.waiters.IamWaiter; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListObjectsRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsResponse; +import software.amazon.awssdk.services.s3.model.S3Object; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; +import software.amazon.awssdk.services.sts.model.AssumeRoleResponse; +import software.amazon.awssdk.services.sts.model.Credentials; +import software.amazon.awssdk.services.sts.model.StsException; + +import java.util.List; +import java.util.concurrent.TimeUnit; +// snippet-end:[iam.java2.scenario.import] + +// snippet-start:[iam.java2.scenario.main] +/* + To run this Java V2 code example, set up your development environment, including your credentials. + + For information, see this documentation topic: + + https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + + This example performs these operations: + + 1. Creates a user that has no permissions. + 2. Creates a role and policy that grants Amazon S3 permissions. + 3. Creates a role. + 4. Grants the user permissions. + 5. Gets temporary credentials by assuming the role. Creates an Amazon S3 Service client object with the temporary credentials. + 6. Deletes the resources. + */ + +public class IAMScenario { + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static final String PolicyDocument = "{" + + " \"Version\": \"2012-10-17\"," + + " \"Statement\": [" + + " {" + + " \"Effect\": \"Allow\"," + + " \"Action\": [" + + " \"s3:*\"" + + " ]," + + " \"Resource\": \"*\"" + + " }" + + " ]" + + "}"; + + public static String userArn; + + public static void main(String[] args) throws Exception { + + final String usage = """ + + Usage: + \s + + Where: + username - The name of the IAM user to create.\s + policyName - The name of the policy to create.\s + roleName - The name of the role to create.\s + roleSessionName - The name of the session required for the assumeRole operation.\s + bucketName - The name of the Amazon S3 bucket from which objects are read.\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String userName = args[0]; + String policyName = args[1]; + String roleName = args[2]; + String roleSessionName = args[3]; + String bucketName = args[4]; + + Region region = Region.AWS_GLOBAL; + IamClient iam = IamClient.builder() + .region(region) + .build(); + + System.out.println(DASHES); + System.out.println("Welcome to the AWS IAM example scenario."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println(" 1. Create the IAM user."); + User createUser = createIAMUser(iam, userName); + + System.out.println(DASHES); + userArn = createUser.arn(); + + AccessKey myKey = createIAMAccessKey(iam, userName); + String accessKey = myKey.accessKeyId(); + String secretKey = myKey.secretAccessKey(); + String assumeRolePolicyDocument = "{" + + "\"Version\": \"2012-10-17\"," + + "\"Statement\": [{" + + "\"Effect\": \"Allow\"," + + "\"Principal\": {" + + " \"AWS\": \"" + userArn + "\"" + + "}," + + "\"Action\": \"sts:AssumeRole\"" + + "}]" + + "}"; + + System.out.println(assumeRolePolicyDocument); + System.out.println(userName + " was successfully created."); + System.out.println(DASHES); + System.out.println("2. Creates a policy."); + String polArn = createIAMPolicy(iam, policyName); + System.out.println("The policy " + polArn + " was successfully created."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("3. Creates a role."); + TimeUnit.SECONDS.sleep(30); + String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument); + System.out.println(roleArn + " was successfully created."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("4. Grants the user permissions."); + attachIAMRolePolicy(iam, roleName, polArn); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("*** Wait for 30 secs so the resource is available"); + TimeUnit.SECONDS.sleep(30); + System.out.println("5. Gets temporary credentials by assuming the role."); + System.out.println("Perform an Amazon S3 Service operation using the temporary credentials."); + assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("6 Getting ready to delete the AWS resources"); + deleteKey(iam, userName, accessKey); + deleteRole(iam, roleName, polArn); + deleteIAMUser(iam, userName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("This IAM Scenario has successfully completed"); + System.out.println(DASHES); + } + + /** + * Creates an IAM access key for the specified user. + * + * @param iam the IAM client to use for the operation + * @param user the name of the IAM user for whom to create the access key + * @return the created access key, or null if an error occurred + */ + public static AccessKey createIAMAccessKey(IamClient iam, String user) { + try { + CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() + .userName(user) + .build(); + + CreateAccessKeyResponse response = iam.createAccessKey(request); + return response.accessKey(); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return null; + } + + /** + * Creates an IAM user with the specified username. + * + * @param iam the IAM client used to interact with the AWS IAM service + * @param username the username for the new IAM user + * @return the newly created IAM user + */ + public static User createIAMUser(IamClient iam, String username) { + try { + IamWaiter iamWaiter = iam.waiter(); + CreateUserRequest request = CreateUserRequest.builder() + .userName(username) + .build(); + + CreateUserResponse response = iam.createUser(request); + GetUserRequest userRequest = GetUserRequest.builder() + .userName(response.user().userName()) + .build(); + + WaiterResponse waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); + waitUntilUserExists.matched().response().ifPresent(System.out::println); + return response.user(); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return null; + } + + /** + * Creates an IAM role with the specified role name and assume role policy document. + * + * @param iam the IAM client to use for creating the role + * @param rolename the name of the role to create + * @param json the JSON-formatted assume role policy document + * @return the Amazon Resource Name (ARN) of the created role + * @throws IamException if an error occurs while creating the role + */ + public static String createIAMRole(IamClient iam, String rolename, String json) { + try { + CreateRoleRequest request = CreateRoleRequest.builder() + .roleName(rolename) + .assumeRolePolicyDocument(json) + .description("Created using the AWS SDK for Java") + .build(); + + CreateRoleResponse response = iam.createRole(request); + System.out.println("The ARN of the role is " + response.role().arn()); + return response.role().arn(); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; + } + + /** + * Creates an IAM policy with the given policy name. + * + * @param iam the IAM client used to interact with the AWS IAM service + * @param policyName the name of the policy to be created + * @return the ARN (Amazon Resource Name) of the created policy + * @throws IamException if there is an error creating the policy + */ + public static String createIAMPolicy(IamClient iam, String policyName) { + try { + IamWaiter iamWaiter = iam.waiter(); + CreatePolicyRequest request = CreatePolicyRequest.builder() + .policyName(policyName) + .policyDocument(PolicyDocument).build(); + + CreatePolicyResponse response = iam.createPolicy(request); + GetPolicyRequest polRequest = GetPolicyRequest.builder() + .policyArn(response.policy().arn()) + .build(); + + WaiterResponse waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); + waitUntilPolicyExists.matched().response().ifPresent(System.out::println); + return response.policy().arn(); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; + } + + /** + * Attaches an IAM policy to an IAM role. + * + * @param iam An initialized {@link IamClient} object used to interact with the AWS Identity and Access Management (IAM) service. + * @param roleName The name of the IAM role to which the policy should be attached. + * @param policyArn The Amazon Resource Name (ARN) of the IAM policy to be attached. + */ + public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) { + try { + ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() + .roleName(roleName) + .build(); + + ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); + List attachedPolicies = response.attachedPolicies(); + String polArn; + for (AttachedPolicy policy : attachedPolicies) { + polArn = policy.policyArn(); + if (polArn.compareTo(policyArn) == 0) { + System.out.println(roleName + " policy is already attached to this role."); + return; + } + } + + AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() + .roleName(roleName) + .policyArn(policyArn) + .build(); + + iam.attachRolePolicy(attachRequest); + System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + // snippet-start:[iam.java2.scenario.assumeRole] + + /** + * Assumes a specific IAM role and uses the temporary credentials to list objects in an Amazon S3 bucket. + * + * @param roleArn The Amazon Resource Name (ARN) of the IAM role to assume. + * @param roleSessionName A name that identifies the session. + * @param bucketName The name of the Amazon S3 bucket. + * @param keyVal The access key ID of the IAM user that has permissions to assume the role. + * @param keySecret The secret access key of the IAM user that has permissions to assume the role. + */ + public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal, + String keySecret) { + + AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret); + StsClient stsClient = StsClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(credentials)) + .build(); + + try { + AssumeRoleRequest roleRequest = AssumeRoleRequest.builder() + .roleArn(roleArn) + .roleSessionName(roleSessionName) + .build(); + + AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest); + Credentials myCreds = roleResponse.credentials(); + String key = myCreds.accessKeyId(); + String secKey = myCreds.secretAccessKey(); + String secToken = myCreds.sessionToken(); + + // List all objects in an Amazon S3 bucket using the temp creds retrieved by + // invoking assumeRole. + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .credentialsProvider( + StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken))) + .region(region) + .build(); + + System.out.println("Created a S3Client using temp credentials."); + System.out.println("Listing objects in " + bucketName); + ListObjectsRequest listObjects = ListObjectsRequest.builder() + .bucket(bucketName) + .build(); + + ListObjectsResponse res = s3.listObjects(listObjects); + List objects = res.contents(); + for (S3Object myValue : objects) { + System.out.println("The name of the key is " + myValue.key()); + System.out.println("The owner is " + myValue.owner()); + } + + } catch (StsException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + // snippet-end:[iam.java2.scenario.assumeRole] + + /** + * Deletes an IAM role and its associated IAM policy. + * + * @param iam The IAM client to use for the operations. + * @param roleName The name of the IAM role to delete. + * @param polArn The Amazon Resource Name (ARN) of the IAM policy to delete. + * @throws IamException If an error occurs while performing the IAM operations. + */ + public static void deleteRole(IamClient iam, String roleName, String polArn) { + + try { + // First the policy needs to be detached. + DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder() + .policyArn(polArn) + .roleName(roleName) + .build(); + + iam.detachRolePolicy(rolePolicyRequest); + + // Delete the policy. + DeletePolicyRequest request = DeletePolicyRequest.builder() + .policyArn(polArn) + .build(); + + iam.deletePolicy(request); + System.out.println("*** Successfully deleted " + polArn); + + // Delete the role. + DeleteRoleRequest roleRequest = DeleteRoleRequest.builder() + .roleName(roleName) + .build(); + + iam.deleteRole(roleRequest); + System.out.println("*** Successfully deleted " + roleName); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + /** + * Deletes an IAM access key for the specified user. + * + * @param iam The {@link IamClient} object used to interact with the AWS IAM service. + * @param username The username of the IAM user whose access key should be deleted. + * @param accessKey The ID of the access key to be deleted. + * @throws IamException If an error occurs while deleting the access key. + */ + public static void deleteKey(IamClient iam, String username, String accessKey) { + try { + DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() + .accessKeyId(accessKey) + .userName(username) + .build(); + + iam.deleteAccessKey(request); + System.out.println("Successfully deleted access key " + accessKey + + " from user " + username); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + /** + * Deletes an IAM user. + * + * @param iam An {@link IamClient} object, which represents the AWS Identity and Access Management (IAM) client. + * @param userName The name of the IAM user to be deleted. + * @throws IamException If an error occurs while deleting the IAM user. + */ + public static void deleteIAMUser(IamClient iam, String userName) { + try { + DeleteUserRequest request = DeleteUserRequest.builder() + .userName(userName) + .build(); + + iam.deleteUser(request); + System.out.println("*** Successfully deleted " + userName); + + } catch (IamException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} // snippet-end:[iam.java2.scenario.main] \ No newline at end of file diff --git a/javav2/example_code/iam/src/test/java/IAMServiceTest.java b/javav2/example_code/iam/src/test/java/IAMServiceTest.java index eec835bd976..b7096de3b19 100644 --- a/javav2/example_code/iam/src/test/java/IAMServiceTest.java +++ b/javav2/example_code/iam/src/test/java/IAMServiceTest.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import com.example.iam.*; +import com.example.iam.scenario.IAMScenario; import com.google.gson.Gson; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -14,6 +15,8 @@ import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; + +import java.util.UUID; import java.util.concurrent.TimeUnit; /** @@ -50,8 +53,8 @@ public static void setUp() { Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - userName = values.getUserName(); - policyName = values.getPolicyName(); + userName = values.getUserName()+ UUID.randomUUID(); + policyName = values.getPolicyName()+ UUID.randomUUID(); roleName = values.getRoleName(); accountAlias = values.getAccountAlias(); usernameSc = values.getUsernameSc(); @@ -60,37 +63,6 @@ public static void setUp() { roleSessionName = values.getRoleName(); fileLocationSc = values.getFileLocationSc(); bucketNameSc = values.getBucketNameSc(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * IAMServiceTest.class.getClassLoader().getResourceAsStream("config.properties" - * )) { - * Properties prop = new Properties(); - * prop.load(input); - * userName = prop.getProperty("userName"); - * policyName= prop.getProperty("policyName"); - * policyARN= prop.getProperty("policyARN"); - * roleName=prop.getProperty("roleName"); - * accountAlias=prop.getProperty("accountAlias"); - * usernameSc=prop.getProperty("usernameSc"); - * policyNameSc=prop.getProperty("policyNameSc"); - * roleNameSc=prop.getProperty("roleNameSc"); - * roleSessionName=prop.getProperty("roleSessionName"); - * fileLocationSc=prop.getProperty("fileLocationSc"); - * bucketNameSc=prop.getProperty("bucketNameSc"); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } @Test diff --git a/javav2/example_code/lambda/README.md b/javav2/example_code/lambda/README.md index d8818d1ade2..2a6315f305f 100644 --- a/javav2/example_code/lambda/README.md +++ b/javav2/example_code/lambda/README.md @@ -31,23 +31,26 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav ### Get started -- [Hello Lambda](src/main/java/com/example/lambda/ListLambdaFunctions.java#L4) (`ListFunctions`) +- [Hello Lambda](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L220) (`ListFunctions`) -### Single actions +### Basics -Code excerpts that show you how to call individual service functions. +Code examples that show you how to perform the essential operations within a service. -- [CreateFunction](src/main/java/com/example/lambda/CreateFunction.java#L6) -- [DeleteFunction](src/main/java/com/example/lambda/DeleteFunction.java#L7) -- [Invoke](src/main/java/com/example/lambda/LambdaInvoke.java#L7) +- [Get started with functions](src/main/java/com/example/lambda/scenario/LambdaScenario.java) -### Scenarios -Code examples that show you how to accomplish a specific task by calling multiple -functions within the same service. +### Single actions -- [Get started with functions](src/main/java/com/example/lambda/LambdaScenario.java) +Code excerpts that show you how to call individual service functions. + +- [CreateFunction](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L144) +- [DeleteFunction](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L339) +- [GetFunction](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L197) +- [Invoke](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L243) +- [UpdateFunctionCode](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L197) +- [UpdateFunctionConfiguration](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L312) @@ -66,7 +69,6 @@ functions within the same service. This example shows you how to get started using Lambda. - #### Get started with functions This example shows you how to do the following: @@ -77,12 +79,13 @@ This example shows you how to do the following: - Invoke the function with new parameters and get results. Display the returned execution log. - List the functions for your account, then clean up resources. - - + + + + + - - ### Tests diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java deleted file mode 100644 index b6e3b4eda2f..00000000000 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.lambda; - -// snippet-start:[lambda.java2.create.main] -// snippet-start:[lambda.java2.create.import] -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.lambda.LambdaClient; -import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; -import software.amazon.awssdk.services.lambda.model.FunctionCode; -import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse; -import software.amazon.awssdk.services.lambda.model.GetFunctionRequest; -import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; -import software.amazon.awssdk.services.lambda.model.LambdaException; -import software.amazon.awssdk.services.lambda.model.Runtime; -import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -// snippet-end:[lambda.java2.create.import] - -/** - * This code example requires a ZIP or JAR that represents the code of the - * Lambda function. - * If you do not have a ZIP or JAR, please refer to the following document: - * - * https://github.com/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_workflows_stepfunctions - * - * Also, set up your development environment, including your credentials. - * - * For information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CreateFunction { - public static void main(String[] args) { - - final String usage = """ - - Usage: - \s - - Where: - functionName - The name of the Lambda function.\s - filePath - The path to the ZIP or JAR where the code is located.\s - role - The role ARN that has Lambda permissions.\s - handler - The fully qualified method name (for example, example.Handler::handleRequest). \s - """; - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); - } - - String functionName = args[0]; - String filePath = args[1]; - String role = args[2]; - String handler = args[3]; - Region region = Region.US_WEST_2; - LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); - - createLambdaFunction(awsLambda, functionName, filePath, role, handler); - awsLambda.close(); - } - - public static void createLambdaFunction(LambdaClient awsLambda, - String functionName, - String filePath, - String role, - String handler) { - - try { - LambdaWaiter waiter = awsLambda.waiter(); - InputStream is = new FileInputStream(filePath); - SdkBytes fileToUpload = SdkBytes.fromInputStream(is); - - FunctionCode code = FunctionCode.builder() - .zipFile(fileToUpload) - .build(); - - CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() - .functionName(functionName) - .description("Created by the Lambda Java API") - .code(code) - .handler(handler) - .runtime(Runtime.JAVA8) - .role(role) - .build(); - - // Create a Lambda function using a waiter. - CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); - GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() - .functionName(functionName) - .build(); - WaiterResponse waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("The function ARN is " + functionResponse.functionArn()); - - } catch (LambdaException | FileNotFoundException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[lambda.java2.create.main] diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java deleted file mode 100644 index 8e7686ee2e1..00000000000 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[lambda.java2.DeleteFunction.complete] -package com.example.lambda; - -// snippet-start:[lambda.java2.delete.main] -// snippet-start:[lambda.java2.delete.import] -import software.amazon.awssdk.services.lambda.LambdaClient; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; -import software.amazon.awssdk.services.lambda.model.LambdaException; -// snippet-end:[lambda.java2.delete.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 DeleteFunction { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - functionName - The name of the Lambda function.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String functionName = args[0]; - Region region = Region.US_EAST_1; - LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); - - deleteLambdaFunction(awsLambda, functionName); - awsLambda.close(); - } - - public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { - try { - DeleteFunctionRequest request = DeleteFunctionRequest.builder() - .functionName(functionName) - .build(); - - awsLambda.deleteFunction(request); - System.out.println("The " + functionName + " function was deleted"); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[lambda.java2.delete.main] -// snippet-end:[lambda.java2.DeleteFunction.complete] diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java deleted file mode 100644 index 691cc952556..00000000000 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[lambda.java2.LambdaInvoke.complete] -package com.example.lambda; - -// snippet-start:[lambda.java2.invoke.main] -// snippet-start:[lambda.java2.invoke.import] -import org.json.JSONObject; -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; -import software.amazon.awssdk.services.lambda.LambdaClient; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.lambda.model.InvokeRequest; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.services.lambda.model.InvokeResponse; -import software.amazon.awssdk.services.lambda.model.LambdaException; -// snippet-end:[lambda.java2.invoke.import] - -public class LambdaInvoke { - - /* - * Function names appear as - * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction - * you can retrieve the value by looking at the function in the AWS Console - * - * Also, set up your development environment, including your credentials. - * - * For information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started. - * html - */ - - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - functionName - The name of the Lambda function\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String functionName = args[0]; - Region region = Region.US_WEST_2; - LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); - - invokeFunction(awsLambda, functionName); - awsLambda.close(); - } - - public static void invokeFunction(LambdaClient awsLambda, String functionName) { - - InvokeResponse res = null; - try { - // Need a SdkBytes instance for the payload. - JSONObject jsonObj = new JSONObject(); - jsonObj.put("inputValue", "2000"); - String json = jsonObj.toString(); - SdkBytes payload = SdkBytes.fromUtf8String(json); - - // Setup an InvokeRequest. - InvokeRequest request = InvokeRequest.builder() - .functionName(functionName) - .payload(payload) - .build(); - - res = awsLambda.invoke(request); - String value = res.payload().asUtf8String(); - System.out.println(value); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[lambda.java2.invoke.main] -// snippet-end:[lambda.java2.LambdaInvoke.complete] \ No newline at end of file diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java deleted file mode 100644 index 9d0ff876cbc..00000000000 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// snippet-start:[lambda.java2.ListLambdaFunctions.complete] -package com.example.lambda; - -// snippet-start:[lambda.java2.list.main] -// snippet-start:[lambda.java2.list.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.lambda.LambdaClient; -import software.amazon.awssdk.services.lambda.model.LambdaException; -import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse; -import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; -import java.util.List; -// snippet-end:[lambda.java2.list.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 ListLambdaFunctions { - public static void main(String[] args) { - Region region = Region.US_WEST_2; - LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); - - listFunctions(awsLambda); - awsLambda.close(); - } - - public static void listFunctions(LambdaClient awsLambda) { - try { - ListFunctionsResponse functionResult = awsLambda.listFunctions(); - List list = functionResult.functions(); - for (FunctionConfiguration config : list) { - System.out.println("The function name is " + config.functionName()); - } - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[lambda.java2.list.main] -// snippet-end:[lambda.java2.ListLambdaFunctions.complete] \ No newline at end of file diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/scenario/LambdaScenario.java similarity index 61% rename from javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java rename to javav2/example_code/lambda/src/main/java/com/example/lambda/scenario/LambdaScenario.java index 3129603e7dd..52408b5612a 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/scenario/LambdaScenario.java @@ -1,298 +1,364 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.lambda; - -// snippet-start:[lambda.javav2.scenario.import] -import org.json.JSONObject; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.lambda.LambdaClient; -import software.amazon.awssdk.services.lambda.model.FunctionCode; -import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse; -import software.amazon.awssdk.services.lambda.model.GetFunctionRequest; -import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; -import software.amazon.awssdk.services.lambda.model.LambdaException; -import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse; -import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; -import software.amazon.awssdk.services.lambda.model.InvokeResponse; -import software.amazon.awssdk.services.lambda.model.InvokeRequest; -import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; -import software.amazon.awssdk.services.lambda.model.UpdateFunctionCodeRequest; -import software.amazon.awssdk.services.lambda.model.UpdateFunctionCodeResponse; -import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationRequest; -import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationResponse; -import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; -import software.amazon.awssdk.services.lambda.model.UpdateFunctionConfigurationRequest; -import software.amazon.awssdk.services.lambda.model.Runtime; -import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.List; -// snippet-end:[lambda.javav2.scenario.import] - -// snippet-start:[lambda.javav2.scenario.main] -/* - * Lambda function names appear as: - * - * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction - * - * To find this value, look at the function in the AWS Management Console. - * - * Before running this Java code example, set up your development environment, including your credentials. - * - * For more information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - * - * This example performs the following tasks: - * - * 1. Creates an AWS Lambda function. - * 2. Gets a specific AWS Lambda function. - * 3. Lists all Lambda functions. - * 4. Invokes a Lambda function. - * 5. Updates the Lambda function code and invokes it again. - * 6. Updates a Lambda function's configuration value. - * 7. Deletes a Lambda function. - */ - -public class LambdaScenario { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); - - public static void main(String[] args) throws InterruptedException { - final String usage = """ - - Usage: - \s - - Where: - functionName - The name of the Lambda function.\s - filePath - The path to the .zip or .jar where the code is located.\s - role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s - handler - The fully qualified method name (for example, example.Handler::handleRequest).\s - bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s - key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar). - """; - - if (args.length != 6) { - System.out.println(usage); - System.exit(1); - } - - String functionName = args[0]; - String filePath = args[1]; - String role = args[2]; - String handler = args[3]; - String bucketName = args[4]; - String key = args[5]; - - Region region = Region.US_WEST_2; - LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); - - System.out.println(DASHES); - System.out.println("Welcome to the AWS Lambda example scenario."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("1. Create an AWS Lambda function."); - String funArn = createLambdaFunction(awsLambda, functionName, filePath, role, handler); - System.out.println("The AWS Lambda ARN is " + funArn); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("2. Get the " + functionName + " AWS Lambda function."); - getFunction(awsLambda, functionName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("3. List all AWS Lambda functions."); - listFunctions(awsLambda); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("4. Invoke the Lambda function."); - System.out.println("*** Sleep for 1 min to get Lambda function ready."); - Thread.sleep(60000); - invokeFunction(awsLambda, functionName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("5. Update the Lambda function code and invoke it again."); - updateFunctionCode(awsLambda, functionName, bucketName, key); - System.out.println("*** Sleep for 1 min to get Lambda function ready."); - Thread.sleep(60000); - invokeFunction(awsLambda, functionName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("6. Update a Lambda function's configuration value."); - updateFunctionConfiguration(awsLambda, functionName, handler); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("7. Delete the AWS Lambda function."); - LambdaScenario.deleteLambdaFunction(awsLambda, functionName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("The AWS Lambda scenario completed successfully"); - System.out.println(DASHES); - awsLambda.close(); - } - - public static String createLambdaFunction(LambdaClient awsLambda, - String functionName, - String filePath, - String role, - String handler) { - - try { - LambdaWaiter waiter = awsLambda.waiter(); - InputStream is = new FileInputStream(filePath); - SdkBytes fileToUpload = SdkBytes.fromInputStream(is); - - FunctionCode code = FunctionCode.builder() - .zipFile(fileToUpload) - .build(); - - CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() - .functionName(functionName) - .description("Created by the Lambda Java API") - .code(code) - .handler(handler) - .runtime(Runtime.JAVA8) - .role(role) - .build(); - - // Create a Lambda function using a waiter - CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); - GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() - .functionName(functionName) - .build(); - WaiterResponse waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - return functionResponse.functionArn(); - - } catch (LambdaException | FileNotFoundException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - return ""; - } - - public static void getFunction(LambdaClient awsLambda, String functionName) { - try { - GetFunctionRequest functionRequest = GetFunctionRequest.builder() - .functionName(functionName) - .build(); - - GetFunctionResponse response = awsLambda.getFunction(functionRequest); - System.out.println("The runtime of this Lambda function is " + response.configuration().runtime()); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void listFunctions(LambdaClient awsLambda) { - try { - ListFunctionsResponse functionResult = awsLambda.listFunctions(); - List list = functionResult.functions(); - for (FunctionConfiguration config : list) { - System.out.println("The function name is " + config.functionName()); - } - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void invokeFunction(LambdaClient awsLambda, String functionName) { - - InvokeResponse res; - try { - // Need a SdkBytes instance for the payload. - JSONObject jsonObj = new JSONObject(); - jsonObj.put("inputValue", "2000"); - String json = jsonObj.toString(); - SdkBytes payload = SdkBytes.fromUtf8String(json); - - InvokeRequest request = InvokeRequest.builder() - .functionName(functionName) - .payload(payload) - .build(); - - res = awsLambda.invoke(request); - String value = res.payload().asUtf8String(); - System.out.println(value); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) { - try { - LambdaWaiter waiter = awsLambda.waiter(); - UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder() - .functionName(functionName) - .publish(true) - .s3Bucket(bucketName) - .s3Key(key) - .build(); - - UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest); - GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder() - .functionName(functionName) - .build(); - - WaiterResponse waiterResponse = waiter - .waitUntilFunctionUpdated(getFunctionConfigRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("The last modified value is " + response.lastModified()); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) { - try { - UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder() - .functionName(functionName) - .handler(handler) - .runtime(Runtime.JAVA11) - .build(); - - awsLambda.updateFunctionConfiguration(configurationRequest); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { - try { - DeleteFunctionRequest request = DeleteFunctionRequest.builder() - .functionName(functionName) - .build(); - - awsLambda.deleteFunction(request); - System.out.println("The " + functionName + " function was deleted"); - - } catch (LambdaException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.lambda.scenario; + +// snippet-start:[lambda.javav2.scenario.import] + +import org.json.JSONObject; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.FunctionCode; +import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse; +import software.amazon.awssdk.services.lambda.model.GetFunctionRequest; +import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; +import software.amazon.awssdk.services.lambda.model.LambdaException; +import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse; +import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; +import software.amazon.awssdk.services.lambda.model.InvokeResponse; +import software.amazon.awssdk.services.lambda.model.InvokeRequest; +import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; +import software.amazon.awssdk.services.lambda.model.UpdateFunctionCodeRequest; +import software.amazon.awssdk.services.lambda.model.UpdateFunctionCodeResponse; +import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationRequest; +import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationResponse; +import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; +import software.amazon.awssdk.services.lambda.model.UpdateFunctionConfigurationRequest; +import software.amazon.awssdk.services.lambda.model.Runtime; +import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.List; +// snippet-end:[lambda.javav2.scenario.import] + +// snippet-start:[lambda.javav2.scenario.main] +/* + * Lambda function names appear as: + * + * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction + * + * To find this value, look at the function in the AWS Management Console. + * + * Before running this Java code example, set up your development environment, including your credentials. + * + * For more information, see this documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + * This example performs the following tasks: + * + * 1. Creates an AWS Lambda function. + * 2. Gets a specific AWS Lambda function. + * 3. Lists all Lambda functions. + * 4. Invokes a Lambda function. + * 5. Updates the Lambda function code and invokes it again. + * 6. Updates a Lambda function's configuration value. + * 7. Deletes a Lambda function. + */ + +public class LambdaScenario { + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + + public static void main(String[] args) throws InterruptedException { + final String usage = """ + + Usage: + \s + + Where: + functionName - The name of the Lambda function.\s + role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s + handler - The fully qualified method name (for example, example.Handler::handleRequest).\s + bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s + key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar). + """; + + if (args.length != 5) { + System.out.println(usage); + return; + } + + String functionName = args[0]; + String role = args[1]; + String handler = args[2]; + String bucketName = args[3]; + String key = args[4]; + LambdaClient awsLambda = LambdaClient.builder() + .build(); + + System.out.println(DASHES); + System.out.println("Welcome to the AWS Lambda Basics scenario."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("1. Create an AWS Lambda function."); + String funArn = createLambdaFunction(awsLambda, functionName, key, bucketName, role, handler); + System.out.println("The AWS Lambda ARN is " + funArn); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("2. Get the " + functionName + " AWS Lambda function."); + getFunction(awsLambda, functionName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("3. List all AWS Lambda functions."); + listFunctions(awsLambda); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("4. Invoke the Lambda function."); + System.out.println("*** Sleep for 1 min to get Lambda function ready."); + Thread.sleep(60000); + invokeFunction(awsLambda, functionName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("5. Update the Lambda function code and invoke it again."); + updateFunctionCode(awsLambda, functionName, bucketName, key); + System.out.println("*** Sleep for 1 min to get Lambda function ready."); + Thread.sleep(60000); + invokeFunction(awsLambda, functionName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("6. Update a Lambda function's configuration value."); + updateFunctionConfiguration(awsLambda, functionName, handler); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("7. Delete the AWS Lambda function."); + LambdaScenario.deleteLambdaFunction(awsLambda, functionName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("The AWS Lambda scenario completed successfully"); + System.out.println(DASHES); + awsLambda.close(); + } + + // snippet-start:[lambda.java2.create.main] + + /** + * Creates a new Lambda function in AWS using the AWS Lambda Java API. + * + * @param awsLambda the AWS Lambda client used to interact with the AWS Lambda service + * @param functionName the name of the Lambda function to create + * @param key the S3 key of the function code + * @param bucketName the name of the S3 bucket containing the function code + * @param role the IAM role to assign to the Lambda function + * @param handler the fully qualified class name of the function handler + * @return the Amazon Resource Name (ARN) of the created Lambda function + */ + public static String createLambdaFunction(LambdaClient awsLambda, + String functionName, + String key, + String bucketName, + String role, + String handler) { + + try { + LambdaWaiter waiter = awsLambda.waiter(); + FunctionCode code = FunctionCode.builder() + .s3Key(key) + .s3Bucket(bucketName) + .build(); + + CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() + .functionName(functionName) + .description("Created by the Lambda Java API") + .code(code) + .handler(handler) + .runtime(Runtime.JAVA17) + .role(role) + .build(); + + // Create a Lambda function using a waiter + CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); + GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() + .functionName(functionName) + .build(); + WaiterResponse waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + return functionResponse.functionArn(); + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + return ""; + } + // snippet-end:[lambda.java2.create.main] + + // snippet-start:[lambda.java2.get.function.main] + /** + * Retrieves information about an AWS Lambda function. + * + * @param awsLambda an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service + * @param functionName the name of the AWS Lambda function to retrieve information about + */ + public static void getFunction(LambdaClient awsLambda, String functionName) { + try { + GetFunctionRequest functionRequest = GetFunctionRequest.builder() + .functionName(functionName) + .build(); + + GetFunctionResponse response = awsLambda.getFunction(functionRequest); + System.out.println("The runtime of this Lambda function is " + response.configuration().runtime()); + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[lambda.java2.get.function.main] + + // snippet-start:[lambda.java2.list.main] + /** + * Lists the AWS Lambda functions associated with the current AWS account. + * + * @param awsLambda an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service + * + * @throws LambdaException if an error occurs while interacting with the AWS Lambda service + */ + public static void listFunctions(LambdaClient awsLambda) { + try { + ListFunctionsResponse functionResult = awsLambda.listFunctions(); + List list = functionResult.functions(); + for (FunctionConfiguration config : list) { + System.out.println("The function name is " + config.functionName()); + } + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[lambda.java2.list.main] + + // snippet-start:[lambda.java2.invoke.main] + /** + * Invokes a specific AWS Lambda function. + * + * @param awsLambda an instance of {@link LambdaClient} to interact with the AWS Lambda service + * @param functionName the name of the AWS Lambda function to be invoked + */ + public static void invokeFunction(LambdaClient awsLambda, String functionName) { + InvokeResponse res; + try { + // Need a SdkBytes instance for the payload. + JSONObject jsonObj = new JSONObject(); + jsonObj.put("inputValue", "2000"); + String json = jsonObj.toString(); + SdkBytes payload = SdkBytes.fromUtf8String(json); + + InvokeRequest request = InvokeRequest.builder() + .functionName(functionName) + .payload(payload) + .build(); + + res = awsLambda.invoke(request); + String value = res.payload().asUtf8String(); + System.out.println(value); + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[lambda.java2.invoke.main] + + // snippet-start:[lambda.java2.update.main] + /** + * Updates the code for an AWS Lambda function. + * + * @param awsLambda the AWS Lambda client + * @param functionName the name of the Lambda function to update + * @param bucketName the name of the S3 bucket where the function code is located + * @param key the key (file name) of the function code in the S3 bucket + * @throws LambdaException if there is an error updating the function code + */ + public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) { + try { + LambdaWaiter waiter = awsLambda.waiter(); + UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder() + .functionName(functionName) + .publish(true) + .s3Bucket(bucketName) + .s3Key(key) + .build(); + + UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest); + GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder() + .functionName(functionName) + .build(); + + WaiterResponse waiterResponse = waiter + .waitUntilFunctionUpdated(getFunctionConfigRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println("The last modified value is " + response.lastModified()); + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[lambda.java2.update.main] + + // snippet-start:[lambda.java2.update.config.main] + /** + * Updates the configuration of an AWS Lambda function. + * + * @param awsLambda the {@link LambdaClient} instance to use for the AWS Lambda operation + * @param functionName the name of the AWS Lambda function to update + * @param handler the new handler for the AWS Lambda function + * + * @throws LambdaException if there is an error while updating the function configuration + */ + public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) { + try { + UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder() + .functionName(functionName) + .handler(handler) + .runtime(Runtime.JAVA17) + .build(); + + awsLambda.updateFunctionConfiguration(configurationRequest); + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[lambda.java2.update.config.main] + + // snippet-start:[lambda.java2.delete.main] + /** + * Deletes an AWS Lambda function. + * + * @param awsLambda an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service + * @param functionName the name of the Lambda function to be deleted + * + * @throws LambdaException if an error occurs while deleting the Lambda function + */ + public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { + try { + DeleteFunctionRequest request = DeleteFunctionRequest.builder() + .functionName(functionName) + .build(); + + awsLambda.deleteFunction(request); + System.out.println("The " + functionName + " function was deleted"); + + } catch (LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[lambda.java2.delete.main] +} // snippet-end:[lambda.javav2.scenario.main] \ No newline at end of file diff --git a/javav2/example_code/lambda/src/test/java/LambdaTest.java b/javav2/example_code/lambda/src/test/java/LambdaTest.java index 4b07221fe9f..32e19324bd5 100644 --- a/javav2/example_code/lambda/src/test/java/LambdaTest.java +++ b/javav2/example_code/lambda/src/test/java/LambdaTest.java @@ -1,12 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import com.example.lambda.CreateFunction; -import com.example.lambda.DeleteFunction; import com.example.lambda.GetAccountSettings; -import com.example.lambda.LambdaScenario; -import com.example.lambda.LambdaInvoke; -import com.example.lambda.ListLambdaFunctions; +import com.example.lambda.scenario.LambdaScenario; import com.google.gson.Gson; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -45,10 +41,8 @@ public class LambdaTest { @BeforeAll public static void setUp() { - Region region = Region.US_WEST_2; awsLambda = LambdaClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); // Get the values to run these tests from AWS Secrets Manager. @@ -62,82 +56,22 @@ public static void setUp() { functionNameSc = values.getFunctionNameSc() + java.util.UUID.randomUUID(); bucketName = values.getBucketName(); key = values.getKey(); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * - * try (InputStream input = - * LambdaTest.class.getClassLoader().getResourceAsStream("config.properties")) { - * Properties prop = new Properties(); - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * functionName = prop.getProperty("functionNameSc")+ - * java.util.UUID.randomUUID(); - * filePath = prop.getProperty("filePath"); - * role = prop.getProperty("role"); - * handler = prop.getProperty("handler"); - * functionNameSc = prop.getProperty("functionNameSc")+ - * java.util.UUID.randomUUID(); - * bucketName = prop.getProperty("bucketName"); - * key = prop.getProperty("key"); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ } - @Test - @Tag("IntegrationTest") - @Order(1) - public void CreateFunction() { - assertDoesNotThrow(() -> CreateFunction.createLambdaFunction(awsLambda, functionName, filePath, role, handler)); - System.out.println("Test 1 passed"); - } @Test @Tag("IntegrationTest") - @Order(2) + @Order(1) public void GetAccountSettings() { assertDoesNotThrow(() -> GetAccountSettings.getSettings(awsLambda)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void ListLambdaFunctions() { - assertDoesNotThrow(() -> ListLambdaFunctions.listFunctions(awsLambda)); - System.out.println("Test 3 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(4) - public void LambdaInvoke() throws InterruptedException { - System.out.println("*** Wait for 5 MIN so the resource is available"); - TimeUnit.MINUTES.sleep(5); - assertDoesNotThrow(() -> LambdaInvoke.invokeFunction(awsLambda, functionName)); - System.out.println("Test 4 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(5) - public void DeleteFunction() { - assertDoesNotThrow(() -> DeleteFunction.deleteLambdaFunction(awsLambda, functionName)); - System.out.println("Test 5 passed"); + System.out.println("Test 1 passed"); } @Test @Tag("IntegrationTest") - @Order(6) + @Order(2) public void LambdaScenario() throws InterruptedException { - String funArn = LambdaScenario.createLambdaFunction(awsLambda, functionNameSc, filePath, role, handler); + String funArn = LambdaScenario.createLambdaFunction(awsLambda, functionNameSc, key, bucketName, role, handler); assertFalse(funArn.isEmpty()); System.out.println("The function ARN is " + funArn); @@ -222,7 +156,5 @@ public String getBucketName() { public String getFunctionName() { return functionName; } - } - }