Java 8 Lambda function with Eclipse IDE – chapter 2

Introduction

In the previous chapter I wrote about setting up a Hello World lambda function with the support of aws eclipse plugin. We will now create a more sophisticated lambda function.

1 create an entity

We will create a product entity. Entity class is as follows:

package jtrainer.education.api.serverless.postgresql.function;

import com.google.gson.*;

public class Product {
         
        private int id;
        private Integer product_type_id;
        private String ean;
        private String name;
     
        public Product(String json) {
            Gson gson = new Gson();
            Product product = gson.fromJson(json, Product.class);
            this.id = product.getId();
            this.name = product.getName();
            this.ean=product.getEan();
            this.product_type_id=product.getProduct_type();
        }
     
        public String toString() {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            return gson.toJson(this);
        }
        //insert setters and getters here
}

This entity has 4 properties (id, name, ean and product_type_id). 

2 Create a new Handler

We need also to add 2 dependencies to the pom.xml file:

<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
</dependency>

The previous entity is used by the lambda handler to deserialize the input stream. Let’s say we have got an event like the following:

{“name”: “iphone”,”product_type_id”: “1”,”ean”: “09764748484995”}

The following class CreateProductHandler.java will be able to deserialize the input string and create a product.

package jtrainer.education.api.serverless.postgresql.function;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;

public class CreateProduct {

    public Integer createProduct(Context context, String name, Integer product_type_id, String ean) {
        LambdaLogger logger = context.getLogger();
        Connection conn=PostGresqlConnection.getConnection();
        try {
            Statement stmt = conn.createStatement();
            String query="INSERT INTO public.products(name, product_type_id, ean) VALUES ('"+name+"', '"+product_type_id+"', '"+ean+"');";
            logger.log("["+query+"]");
            ResultSet resultSet = stmt.executeQuery(query);
            int newId = resultSet.getInt(1);
            conn.close();
            return newId;
        } catch (Exception e) {
            e.printStackTrace();
            logger.log("Caught exception: " + e.getMessage());
            try {
                conn.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return 0;
    }
}

Please note that the CreateProduct.createProduct(…) is calling a method which will persist the product object to an amazon rds postgresql database table:

package jtrainer.education.api.serverless.postgresql.function;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;

public class CreateProduct {

    public Integer createProduct(Context context, String name, Integer product_type_id, String ean) {
        LambdaLogger logger = context.getLogger();
        Connection conn=PostGresqlConnection.getConnection();
        try {
            Statement stmt = conn.createStatement();
            String query="INSERT INTO public.products(name, product_type_id, ean) VALUES ('"+name+"', '"+product_type_id+"', '"+ean+"');";
            logger.log("["+query+"]");
            ResultSet resultSet = stmt.executeQuery(query);
            int newId = resultSet.getInt(1);
            conn.close();
            return newId;
        } catch (Exception e) {
            e.printStackTrace();
            logger.log("Caught exception: " + e.getMessage());
            try {
                conn.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return 0;
    }
}

I will not cover the PostgresqlConnection class description here. You can find all classes code on GitHub.

3 Deploy on your aws account

Follow step 4 and 5 of the previous chapter to deploy and test the new handler.

As this event will come from an api gateway you have to use the following test event:

This event will automatically appear when you select the Amazon API gateway AWS Proxy. Just replace the “body” field as follows:

“body”: “{\”name\”: \”iphone\”,\”product_type_id\”: 1,\”ean\”: \”09764748484995\” }”,

See you in the next chapter