Various patterns can be used for Java Lambda input / output types.
In the official documentation, it is written here.
In POJO, I introduced how to handle JSON using POJO classes.
Finally, it is the Stream edition using InputStream / OutputStream.
It is a code that is modified from the previous POJO edition and Parse and Generate by itself using Jackson.
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
public class StreamFunction implements RequestStreamHandler {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
Product product = OBJECT_MAPPER.readValue(inputStream, Product.class);
String name = product.getName();
System.out.println(name); // orange juice
Integer price = product.getPrice();
System.out.println(price); // 1000
Long releaseDate = product.getReleaseDate();
System.out.println(releaseDate); // 1601606387939
Double rate = product.getRate();
System.out.println(rate); // 4.5
List<String> rawMaterial = product.getRawMaterial();
System.out.println(rawMaterial); // [orange, fragrance]
Product.Size size = product.getSize();
Integer height = size.getHeight();
System.out.println(height); // 10
Integer width = size.getWidth();
System.out.println(width); // 20
Integer depth = size.getDepth();
System.out.println(depth); // 30
Product response = new Product();
response.setName("coffee");
response.setPrice(Integer.valueOf(500));
response.setReleaseDate(System.currentTimeMillis());
response.setRate(Double.valueOf(4.2));
response.setRawMaterial(Arrays.asList("coffee", "sugar"));
Product.Size responseSize = new Product.Size();
responseSize.setHeight(Integer.valueOf(100));
responseSize.setWidth(Integer.valueOf(200));
responseSize.setDepth(Integer.valueOf(300));
response.setSize(responseSize);
OBJECT_MAPPER.writeValue(outputStream, response);
}
}
When executed, the result is the same as the POJO edition.
{
"name": "coffee",
"price": 500,
"releaseDate": 1601627790764,
"rate": 4.2,
"rawMaterial": [
"coffee",
"sugar"
],
"size": {
"height": 100,
"width": 200,
"depth": 300
}
}
I don't think I'll use it much, but maybe when I'm dealing with huge JSON or when I want to use the JSON Parser / Generator library.
For product codes, it is recommended to use the POJO method for maintainability. If you just want to move it quickly and try it out, the Map method is easy.
Recommended Posts