diff --git a/.doc_gen/metadata/lambda_metadata.yaml b/.doc_gen/metadata/lambda_metadata.yaml index a30db5f5bf4..b65eca62c4a 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,15 +751,13 @@ lambda_ListFunctions: services: lambda: {ListFunctions} lambda_Scenario_GettingStartedFunctions: - title: Get started creating and invoking &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. - Invoke the function with a single parameter and get results. - 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/lambda/README.md b/javav2/example_code/lambda/README.md index d8818d1ade2..ead800d352d 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#L219) (`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) +- [Learn the basics](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#L338) +- [GetFunction](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L196) +- [Invoke](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L242) +- [UpdateFunctionCode](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L196) +- [UpdateFunctionConfiguration](src/main/java/com/example/lambda/scenario/LambdaScenario.java#L311) @@ -66,8 +69,7 @@ functions within the same service. This example shows you how to get started using Lambda. - -#### Get started with functions +#### Learn the basics 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..74d8db8ee09 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,363 @@ -// 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; } - } - }