Introduction
AWS Lambda is a Serverless computing service provided by Amazon, that allows you to build and run applications and services without thinking about servers. With serverless computing, your application still runs on servers, but all the server management is done by AWS. At the core of serverless computing is AWS Lambda, which lets you run your code without provisioning or managing servers. AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. AWS Lambda is a serverless computing service provided by Amazon to reduce the configuration of servers, OS, Scalability, etc. AWS Lambda is capable of executing code on AWS Cloud.
AWS Lambda offers an easy way to accomplish many activities in the cloud. For example, you can use AWS Lambda to build mobile back-ends that retrieve and transform data from Amazon DynamoDB, handlers that compress or transform objects as they are uploaded to Amazon S3, auditing and reporting of API call made to any Amazon Web Service and server-less processing of streaming data using Amazon Kinesis.
Here we explain how to generate the thumbnail of an image when uploaded to the s3 bucket.
Dependencies from Maven
com.amazonaws aws-lambda-java-core 1.2.1 com.amazonaws aws-java-sdk-s3 1.11.779 com.amazonaws aws-java-sdk-core 1.11.779 com.google.code.gson gson 2.8.6 com.amazonaws aws-lambda-java-events 2.2.8
Then Create an s3 bucket in AWS, I have created a bucket named dev000001 and created folder images inside it. This is the folder where we upload the images. The thumbnail of the image generated by the AWS lambda function.
MethodHandler for lamda
create a class S3EventHandler.java .inside it creates a function named handleRequest that takes an event object and a context object. This is the handler function that Lambda calls when the function is invoked. The Java function runtime gets invocation events from Lambda and passes them to the handler. In the function configuration, the handler value is com.bala.aws.lamda.example.::handleRequest. S3EventHandler.S3EventHandler.
The function runtime passes a context object to the handler, in addition to the invocation event. The context object contains additional information about the invocation, the function, and the execution environment. More information is available from environment variables.
Your Lambda function comes with a CloudWatch Logs log group. The function runtime sends details about each invocation to CloudWatch Logs. It relays any logs that your function outputs during invocation. If your function returns an error, Lambda formats the error and returns it to the invoker.
import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.event.S3EventNotification.S3EventNotificationRecord; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class S3EventHandler implements RequestHandler
package com.bala.aws.lamda.example;{ Gson gson = new GsonBuilder().setPrettyPrinting().create(); private static final Logger logger = LoggerFactory.getLogger(S3EventHandler.class); private static final float MAX_WIDTH = 100; private static final float MAX_HEIGHT = 100; private final String JPG_TYPE = (String) "jpg"; private final String JPG_MIME = (String) "image/jpeg"; private final String PNG_TYPE = (String) "png"; private final String PNG_MIME = (String) "image/png"; @Override public String handleRequest(S3Event s3event, Context context) { try { logger.info("Event is : " + gson.toJson(s3event)); if(s3event.getRecords().size()!=0) { S3EventNotificationRecord record = s3event.getRecords().get(0); logger.info("getAwsRegion: " + record.getAwsRegion()); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); logger.info("srcBucket: " + srcBucket); String dstBucket = srcBucket; String dstKey = "resized-" + srcKey; Matcher matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey); if (!matcher.matches()) { logger.info("Unable to infer image type for key " + srcKey); return ""; } String imageType = matcher.group(1); if (!(JPG_TYPE.equals(imageType)) && !(PNG_TYPE.equals(imageType))) { logger.info("Skipping non-image " + srcKey); return ""; } // Download the image from S3 into a stream AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient(); S3Object s3Object = s3Client.getObject(new GetObjectRequest( srcBucket, srcKey)); InputStream objectData = s3Object.getObjectContent(); // Read the source image BufferedImage srcImage = ImageIO.read(objectData); int srcHeight = srcImage.getHeight(); int srcWidth = srcImage.getWidth(); // Infer the scaling factor to avoid stretching the image // unnaturally float scalingFactor = Math.min(MAX_WIDTH / srcWidth, MAX_HEIGHT / srcHeight); int width = (int) (scalingFactor * srcWidth); int height = (int) (scalingFactor * srcHeight); BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = resizedImage.createGraphics(); // Fill with white before applying semi-transparent (alpha) images g.setPaint(Color.white); g.fillRect(0, 0, width, height); // Simple bilinear resize g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(srcImage, 0, 0, width, height, null); g.dispose(); // Re-encode image to target format ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(resizedImage, imageType, os); InputStream is = new ByteArrayInputStream(os.toByteArray()); // Set Content-Length and Content-Type ObjectMetadata meta = new ObjectMetadata(); meta.setContentLength(os.size()); if (JPG_TYPE.equals(imageType)) { meta.setContentType(JPG_MIME); } if (PNG_TYPE.equals(imageType)) { meta.setContentType(PNG_MIME); } // Uploading to S3 destination bucket logger.info("Writing to: " + dstBucket + "/" + dstKey); try { s3Client.putObject(dstBucket, dstKey, is, meta); } catch(AmazonServiceException e) { logger.error(e.getErrorMessage()); System.exit(1); } logger.info("Successfully resized " + srcBucket + "/" + srcKey + " and uploaded to " + dstBucket + "/" + dstKey); return "Ok"; }else{ logger.info("no object found in the S3 !!!!!"); } } catch (IOException e) { logger.error("Exception occured during execution of S3EventHandler "); } return "Error"; } }
for deployment, we need to upload jar or zip file.
Generate jar file
mvn clean package shade:shade
Lambda provides runtimes for Java that execute your code to process events. Your code runs in an Amazon Linux environment that includes AWS credentials from an AWS Identity and Access Management (IAM) role that you manage.
Lambda functions use an execution role to get permission to write logs to Amazon CloudWatch Logs and to access other services and resources. If you don't already have an execution role for function development, create one.
To create an execution role
1). Open the roles page in the IAM console.
2). Choose to Create role.
3). Create a role with the following properties.
- Trusted entity – Lambda.
- Permissions – AWSLambdaBasicExecutionRole.
- Role name – lambda-role.
your policy document should like
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write logs to CloudWatch Logs. You can add permissions to the role later, or swap it out for a different role that's specific to a single function.
To create a Java function
1). Open the Lambda console.
2). Choose to Create a function.
3). Configure the following settings:
- Name – CreateThumbnail.
- Runtime – Java 8.
- Role – Choose an existing role.
- Existing role – lambda-role.
Choose to Create a function.
To configure a test event
choose Test. For Event name, enter test.
Choose to Create.
To execute the function, choose Test.
The console creates a Lambda function with a handler class named S3EventHandler.
Since Java is a compiled language, you can't view or edit the source code in the Lambda console, but you can modify its configuration, invoke it, and configure triggers.
image of lamda here
Enable and configure event notifications for an S3 Bucket
1). Go to the dev000001 bucket properties in AWS console
2). Click on Events 3).
Then Click on Add Notification
- Name : lamda-events-for-s3-put
- Events: check All object create events
- Prefix: images/
- Send To: Lamda Function
- Lamda: CreateThumbnail
4). Save.
We added the s3 event to trigger the lambda function CreateThumbnail.
images 2 s3event
1). Click On Lamda Function go Down
2).In Function code Section
- Function package -> selects your java jar file and upload it.
- Function package -> Java 8
- HandlerInfo -> org.wipo.aws.lamda.example.S3EventHandler::handleRequest
3). Save the Changes.
images here
Now our Lamda function is ready to execute.
Upload the Images to bucket dev000001 folder images. you will see parallel to the images folder, resized-images folder generated and you see resized thumbnail generated inside that folder. Also, you can see cloudWatch Logs get generated against log group /aws/lambda/CreateThumbnail in Cloudwtch log section. image cloud watch
That's it. We've created an AWS Lambda function to generate Thumbnail of images uploaded to the s3 bucket, using Java 8 with deployment and testing.
The full code for the aws-lamda-example can be found over on Github
0 Comments
Post a Comment