From f6f62ea0f59137c25c79908e4fc426f51fd8b0f8 Mon Sep 17 00:00:00 2001 From: markusgulden Date: Sat, 30 Jun 2018 05:49:16 +0200 Subject: [PATCH] BAEL-1727 (#4575) * Moved Lambda examples to separate module Implementation of API Gateway example * Format fixes * Format fixes * Minor fixes * Minor fixes * Minor fixes * Adding SAM templates for "Introduction to AWS Serverless Application Model" * Fixing formatting with spaces --- .../sam-templates/template-implicit.yaml | 75 ++++++ .../template-inline-swagger.yaml | 127 +++++++++++ .../lambda/apigateway/APIDemoHandler.java | 214 +++++++++--------- .../lambda/apigateway/model/Person.java | 94 ++++---- 4 files changed, 356 insertions(+), 154 deletions(-) create mode 100644 aws-lambda/sam-templates/template-implicit.yaml create mode 100644 aws-lambda/sam-templates/template-inline-swagger.yaml diff --git a/aws-lambda/sam-templates/template-implicit.yaml b/aws-lambda/sam-templates/template-implicit.yaml new file mode 100644 index 0000000000..73289b8bb1 --- /dev/null +++ b/aws-lambda/sam-templates/template-implicit.yaml @@ -0,0 +1,75 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: Baeldung Serverless Application Model Example with Implicit API Definition +Globals: + Api: + EndpointConfiguration: REGIONAL + Name: "TestAPI" +Resources: + PersonTable: + Type: AWS::Serverless::SimpleTable + Properties: + PrimaryKey: + Name: id + Type: Number + TableName: Person + StorePersonFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + StoreApi: + Type: Api + Properties: + Path: /persons + Method: PUT + GetPersonByPathParamFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByPathParam + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBReadPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + GetByPathApi: + Type: Api + Properties: + Path: /persons/{id} + Method: GET + GetPersonByQueryParamFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByQueryParam + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBReadPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + GetByQueryApi: + Type: Api + Properties: + Path: /persons + Method: GET \ No newline at end of file diff --git a/aws-lambda/sam-templates/template-inline-swagger.yaml b/aws-lambda/sam-templates/template-inline-swagger.yaml new file mode 100644 index 0000000000..f704d47c25 --- /dev/null +++ b/aws-lambda/sam-templates/template-inline-swagger.yaml @@ -0,0 +1,127 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: Baeldung Serverless Application Model Example with Inline Swagger API Definition +Resources: + PersonTable: + Type: AWS::Serverless::SimpleTable + Properties: + PrimaryKey: + Name: id + Type: Number + TableName: Person + StorePersonFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + StoreApi: + Type: Api + Properties: + Path: /persons + Method: PUT + RestApiId: + Ref: MyApi + GetPersonByPathParamFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByPathParam + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBReadPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + GetByPathApi: + Type: Api + Properties: + Path: /persons/{id} + Method: GET + RestApiId: + Ref: MyApi + GetPersonByQueryParamFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByQueryParam + Runtime: java8 + Timeout: 15 + MemorySize: 512 + CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar + Policies: + - DynamoDBReadPolicy: + TableName: !Ref PersonTable + Environment: + Variables: + TABLE_NAME: !Ref PersonTable + Events: + GetByQueryApi: + Type: Api + Properties: + Path: /persons + Method: GET + RestApiId: + Ref: MyApi + MyApi: + Type: AWS::Serverless::Api + Properties: + StageName: test + EndpointConfiguration: REGIONAL + DefinitionBody: + swagger: "2.0" + info: + title: "TestAPI" + paths: + /persons: + get: + parameters: + - name: "id" + in: "query" + required: true + type: "string" + x-amazon-apigateway-request-validator: "Validate query string parameters and\ + \ headers" + x-amazon-apigateway-integration: + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByQueryParamFunction.Arn}/invocations + responses: {} + httpMethod: "POST" + type: "aws_proxy" + put: + x-amazon-apigateway-integration: + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StorePersonFunction.Arn}/invocations + responses: {} + httpMethod: "POST" + type: "aws_proxy" + /persons/{id}: + get: + parameters: + - name: "id" + in: "path" + required: true + type: "string" + responses: {} + x-amazon-apigateway-integration: + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByPathParamFunction.Arn}/invocations + responses: {} + httpMethod: "POST" + type: "aws_proxy" + x-amazon-apigateway-request-validators: + Validate query string parameters and headers: + validateRequestParameters: true + validateRequestBody: false \ No newline at end of file diff --git a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java index 328915c028..71889eaf1b 100644 --- a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java +++ b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java @@ -15,152 +15,152 @@ import java.io.*; public class APIDemoHandler implements RequestStreamHandler { - private JSONParser parser = new JSONParser(); - private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME"); + private JSONParser parser = new JSONParser(); + private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME"); - @Override - public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { + @Override + public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - JSONObject responseJson = new JSONObject(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); - AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); - DynamoDB dynamoDb = new DynamoDB(client); + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); - try { - JSONObject event = (JSONObject) parser.parse(reader); + try { + JSONObject event = (JSONObject) parser.parse(reader); - if (event.get("body") != null) { + if (event.get("body") != null) { - Person person = new Person((String) event.get("body")); + Person person = new Person((String) event.get("body")); - dynamoDb.getTable(DYNAMODB_TABLE_NAME) - .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId()) - .withString("firstName", person.getFirstName()) - .withString("lastName", person.getLastName()).withNumber("age", person.getAge()) - .withString("address", person.getAddress()))); - } + dynamoDb.getTable(DYNAMODB_TABLE_NAME) + .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId()) + .withString("firstName", person.getFirstName()) + .withString("lastName", person.getLastName()).withNumber("age", person.getAge()) + .withString("address", person.getAddress()))); + } - JSONObject responseBody = new JSONObject(); - responseBody.put("message", "New item created"); + JSONObject responseBody = new JSONObject(); + responseBody.put("message", "New item created"); - JSONObject headerJson = new JSONObject(); - headerJson.put("x-custom-header", "my custom header value"); + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); - responseJson.put("statusCode", 200); - responseJson.put("headers", headerJson); - responseJson.put("body", responseBody.toString()); + responseJson.put("statusCode", 200); + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); - } catch (ParseException pex) { - responseJson.put("statusCode", 400); - responseJson.put("exception", pex); - } + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } - OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); - writer.write(responseJson.toString()); - writer.close(); - } + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } - public void handleGetByPathParam(InputStream inputStream, OutputStream outputStream, Context context) - throws IOException { + public void handleGetByPathParam(InputStream inputStream, OutputStream outputStream, Context context) + throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - JSONObject responseJson = new JSONObject(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); - AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); - DynamoDB dynamoDb = new DynamoDB(client); + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); - Item result = null; - try { - JSONObject event = (JSONObject) parser.parse(reader); - JSONObject responseBody = new JSONObject(); + Item result = null; + try { + JSONObject event = (JSONObject) parser.parse(reader); + JSONObject responseBody = new JSONObject(); - if (event.get("pathParameters") != null) { + if (event.get("pathParameters") != null) { - JSONObject pps = (JSONObject) event.get("pathParameters"); - if (pps.get("id") != null) { + JSONObject pps = (JSONObject) event.get("pathParameters"); + if (pps.get("id") != null) { - int id = Integer.parseInt((String) pps.get("id")); - result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id); - } + int id = Integer.parseInt((String) pps.get("id")); + result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id); + } - } - if (result != null) { + } + if (result != null) { - Person person = new Person(result.toJSON()); - responseBody.put("Person", person); - responseJson.put("statusCode", 200); - } else { + Person person = new Person(result.toJSON()); + responseBody.put("Person", person); + responseJson.put("statusCode", 200); + } else { - responseBody.put("message", "No item found"); - responseJson.put("statusCode", 404); - } + responseBody.put("message", "No item found"); + responseJson.put("statusCode", 404); + } - JSONObject headerJson = new JSONObject(); - headerJson.put("x-custom-header", "my custom header value"); + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); - responseJson.put("headers", headerJson); - responseJson.put("body", responseBody.toString()); + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); - } catch (ParseException pex) { - responseJson.put("statusCode", 400); - responseJson.put("exception", pex); - } + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } - OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); - writer.write(responseJson.toString()); - writer.close(); - } + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } - public void handleGetByQueryParam(InputStream inputStream, OutputStream outputStream, Context context) - throws IOException { + public void handleGetByQueryParam(InputStream inputStream, OutputStream outputStream, Context context) + throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - JSONObject responseJson = new JSONObject(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); - AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); - DynamoDB dynamoDb = new DynamoDB(client); + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); - Item result = null; - try { - JSONObject event = (JSONObject) parser.parse(reader); - JSONObject responseBody = new JSONObject(); + Item result = null; + try { + JSONObject event = (JSONObject) parser.parse(reader); + JSONObject responseBody = new JSONObject(); - if (event.get("queryStringParameters") != null) { + if (event.get("queryStringParameters") != null) { - JSONObject qps = (JSONObject) event.get("queryStringParameters"); - if (qps.get("id") != null) { + JSONObject qps = (JSONObject) event.get("queryStringParameters"); + if (qps.get("id") != null) { - int id = Integer.parseInt((String) qps.get("id")); - result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id); - } - } + int id = Integer.parseInt((String) qps.get("id")); + result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id); + } + } - if (result != null) { + if (result != null) { - Person person = new Person(result.toJSON()); - responseBody.put("Person", person); - responseJson.put("statusCode", 200); - } else { + Person person = new Person(result.toJSON()); + responseBody.put("Person", person); + responseJson.put("statusCode", 200); + } else { - responseBody.put("message", "No item found"); - responseJson.put("statusCode", 404); - } + responseBody.put("message", "No item found"); + responseJson.put("statusCode", 404); + } - JSONObject headerJson = new JSONObject(); - headerJson.put("x-custom-header", "my custom header value"); + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); - responseJson.put("headers", headerJson); - responseJson.put("body", responseBody.toString()); + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); - } catch (ParseException pex) { - responseJson.put("statusCode", 400); - responseJson.put("exception", pex); - } + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } - OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); - writer.write(responseJson.toString()); - writer.close(); - } + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } } diff --git a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java index 3be7b261cd..df00994651 100644 --- a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java +++ b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java @@ -5,64 +5,64 @@ import com.google.gson.GsonBuilder; public class Person { - private int id; - private String firstName; - private String lastName; - private int age; - private String address; + private int id; + private String firstName; + private String lastName; + private int age; + private String address; - public Person(String json) { - Gson gson = new Gson(); - Person request = gson.fromJson(json, Person.class); - this.id = request.getId(); - this.firstName = request.getFirstName(); - this.lastName = request.getLastName(); - this.age = request.getAge(); - this.address = request.getAddress(); - } + public Person(String json) { + Gson gson = new Gson(); + Person request = gson.fromJson(json, Person.class); + this.id = request.getId(); + this.firstName = request.getFirstName(); + this.lastName = request.getLastName(); + this.age = request.getAge(); + this.address = request.getAddress(); + } - public String toString() { - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - return gson.toJson(this); - } + public String toString() { + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + return gson.toJson(this); + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; + } - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public void setAddress(String address) { - this.address = address; + public void setAddress(String address) { + this.address = address; } }