Skip to main content

AWS Lambda – Function in Java

Creating JAR file in Eclipse

Before proceeding to work on creating a lambda function in AWS, we need AWS toolkit support for Eclipse. For any guidance on installation of the same, you can refer to the Environment Setup chapter in this tutorial.

Once you are done with installation, follow the steps given here −

Step 1

Open Eclipse IDE and create a new project with AWS Lambda Java Project. Observe the screenshot given below for better understanding −

Select Wizard


Step 2

Once you select Next, it will redirect you the screen shown below −

Lambda Java Project


Step 3

Now, a default code is created for Input Type Custom. Once you click Finish button the project gets created as shown below −

Custom Type


Step 4

Now, right click your project and export it. Select Java / JAR file from the Export wizard and click Next.

Export Wizard


Step 5

Now, if you click Next, you will be prompted save the file in the destination folder which will be asked when you click on next.

Once the file is saved, go back to AWS Console and create the AWS Lambda function for Java.

AWS Console For Java


Step 6

Now, upload the .jar file that we created using the Upload button as shown in the screenshot given below −

Upload Button
Handler Details for Java

Handler is package name and class name. Look at the following example to understand handler in detail −

Example

package com.amazonaws.lambda.demo;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler {
@Override
public String handleRequest(Object input, Context context) {
context
.getLogger().log("Input: " + input);

// TODO: implement your handler
return "Hello from Lambda!";
}
}

Observe that from the above code, the handler will be com.amazonaws.lambda.demo.LambdaFunctionHandler

Now, let us test the changes and see the output −

Lambda Function Handler

Lambda Function Handler Output
Context Object in Java

Interaction with AWS Lambda execution is done using the context. It provides following methods to be used inside Java − 

1. getMemoryLimitInMB()

This will give the memory limit you specified while creating lambda function.

2. getFunctionName()

This will give the name of the lambda function.

3. getFunctionVersion()

This will give the version of the lambda function running.

4. getInvokedFunctionArn()

this will give the ARN used to invoke the function.

5. getAwsRequestId()

This will give the aws request id. This id gets created for the lambda function and it is unique. The id can be used with aws support incase if you face any issues.

6. getLogGroupName()

This will give the aws cloudwatch group name linked with aws lambda function created. It will be null if the iam user is not having permission for cloudwatch logging.

7. getClientContext()

This will give details about the app and device when used with aws mobile sdk. It will give details like version name and code, client id, title, app package name. It can be null.

8. getIdentity()

This will give details about the amazon cognito identity when used with aws mobile sdk. It can be null.

9 . getRemainingTimeInMillis()

This will give the remaining time execution in milliseconds when the function is terminated after the specified timeout.

10. getLogger()

This will give the lambda logger linked with the context object.

Now, let us update the code given above and observe the output for some of the methods listed above. Observe the Example code given below for a better understanding −

package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
context
.getLogger().log("Input: " + input);
System.out.println("AWS Lambda function name: " + context.getFunctionName());
System.out.println("Memory Allocated: " + context.getMemoryLimitInMB());
System.out.println("Time remaining in milliseconds: " + context.getRemainingTimeInMillis());
System.out.println("Cloudwatch group name " + context.getLogGroupName());
System.out.println("AWS Lambda Request Id " + context.getAwsRequestId());

// TODO: implement your handler
return "Hello from Lambda!";
}
}

Once you run the code given above, you can find the output as given below −

Context Object

Logs for context

You can observe the following output when you are viewing your log output −

Logs for Context

The memory allocated for the Lambda function is 512MB. The time allocated is 25 seconds. The time remaining as displayed above is 24961, which is in milliseconds. So 25000 - 24961 which equals to 39 milliseconds is used for the execution of the Lambda function. Note that Cloudwatch group name and request id are also displayed as shown above.

Note that we have used the following command to print logs in Java −

System.out.println (“log message”)

The same is available in CloudWatch. For this, go to AWS services, select CloudWatchservices and click Logs.

Now, if you select the Lambda function, it will display the logs date wise as shown below −

Logs Date Wise

Logging in Java

You can also use Lambdalogger in Java to log the data. Observe the following example that shows the same −

Example

package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
LambdaLogger logger = context.getLogger();
logger
.log("Input: " + input);
logger
.log("AWS Lambda function name: " + context.getFunctionName()+"\n");
logger
.log("Memory Allocated: " + context.getMemoryLimitInMB()+"\n");
logger
.log("Time remaining in milliseconds: " + context.getRemainingTimeInMillis()+"\n");
logger
.log("Cloudwatch group name " + context.getLogGroupName()+"\n");
logger
.log("AWS Lambda Request Id " + context.getAwsRequestId()+"\n");

// TODO: implement your handler
return "Hello from Lambda!";
}
}

The code shown above will give you the following output −

Logging Java

The output in CloudWatch will be as shown below −

Logging Java Output

Error handling in Java for Lambda Function

This section will explain how to handle errors in Java for Lambda function. Observe the following code that shows the same −

package com.amazonaws.lambda.errorhandling;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
throw new RuntimeException("Error from aws lambda");
}
}

Note that the error details are displayed in json format with errorMessage Error from AWS Lambda. Also, the ErrorType and stackTrace gives more details about the error.

The output and the corresponding log output of the code given above will be as shown in the following screenshots given below −

Error handling Java

Error handling Output

Comments

Popular posts from this blog

PERL Some good framework

1. Catalyst is the most popular agile Perl MVC web framework that encourages rapid development and clean design without getting in your way. Catalyst | Perl MVC web application framework 2. Mojolicious is a next generation web framework for the Perl programming language. Back in the early days of the web, many people learned Perl because of a wonderful Perl   ... Mojolicious - Perl real-time web framework 3. Documents for Perl  The Perl Archive Network, the gateway to all things Perl. The canonical location for Perl code and modules. The Comprehensive Perl Archive Network - www. cpan .org

C++ How to use Date and Time

The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t , and tm . The types clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements: struct tm { int tm_sec ; // seconds of minutes from 0 to 61 int tm_min ; // minutes of hour from 0 to 59 int tm_hour ; // hours of day from 0 to 24 int tm_mday ; // day of month from 1 to 31 int tm_mon ; // month of year from 0 to 11 int tm_year ; // year since 1900 int tm_wday ; // days since sunday int tm_yday ; // days since January 1st int tm_isdst ; // hours of daylight savin...

Lambda Function with Amazon DynamoDB

DynamoDB can trigger AWS Lambda when the data in added to the tables, updated or deleted. In this chapter, we will work on a simple example that will add items to the DynamoDB table and AWS Lambda which will read the data and send mail with the data added. Requisites To use Amazon DB and AWS Lambda, we need to follow the steps as shown below − Create a table in DynamoDB with primary key Create a role which will have permission to work with DynamoDBand AWS Lambda. Create function in AWS Lambda AWS Lambda Trigger to send mail Add data in DynamoDB Let us discuss each of this step in detail. Example We are going to work out on following example which shows the basic interaction between DynamoDB and AWS Lambda. This example will help you to understand the following operations − Creating a table called customer in Dynamodb table and how to enter data in that table. Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service. The basic block diagram that ...