├── LICENSE
├── README.md
├── images
└── architecture.jpg
├── pom.xml
└── src
└── main
├── java
└── com
│ └── amazonaws
│ └── serverless
│ ├── dao
│ ├── DynamoDBEventDao.java
│ └── EventDao.java
│ ├── domain
│ └── Event.java
│ ├── function
│ └── EventFunctions.java
│ ├── manager
│ └── DynamoDBManager.java
│ ├── pojo
│ ├── City.java
│ └── Team.java
│ └── util
│ └── Consts.java
└── resources
└── log4j.properties
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Serverless Architecture with Java 8, AWS Lambda, and Amazon DynamoDB
2 |
3 | This code base is an example API built with the Java 8 runtime for AWS Lambda, in
4 | the context of a common use case: an API backed by Amazon DynamoDB as its data store. In a production deployment, you would use Amazon API Gateway to proxy RESTful API requests to the Lambda functions, each of which corresponds to a single API call. When API Gateway is added, the architecture is as follows:
5 |
6 | 
7 |
8 | By using Lambda together with DynamoDB and API Gateway, there is no need to deploy or manage servers for either the application tier or database tier. If the front end consists of mobile devices and a web app statically hosted on Amazon S3, the result is a completely serverless architecture with no need to deploy or manage servers anywhere in the system, in either the front end or back end. For further information, see the following blog post series:
9 | - [Serverless Architectures with Java 8, AWS Lambda, and Amazon DynamoDB — Part 1](https://aws.amazon.com/blogs/startups/serverless-architectures-with-java-8-aws-lambda-and-amazon-dynamodb-part-1/).
10 | - [Serverless Architectures with Java 8, AWS Lambda, and Amazon DynamoDB — Part 2](https://aws.amazon.com/blogs/startups/serverless-architectures-with-java-8-aws-lambda-and-amazon-dynamodb-part-2/).
11 |
12 | ### EXAMPLE USE CASE:
13 |
14 | The example use case is a company which maintains a catalog of sports events, and has decided
15 | to build an API for that catalog backed by DynamoDB. For each event, the company needs to
16 | have a record that includes the name of the home team, the event date, the name of the other
17 | (away) team, the sport involved (e.g. basketball, baseball etc.), city, country, etc. The
18 | home page of the company’s application must display all local events for a user’s favorite
19 | home team, as well as all other sports events in the user’s home city. Other queries regarding
20 | events must be supported, but queries to support the home page are the most important.
21 |
22 | To keep this example simple, only a single Event table in DynamoDB is used to model the data,
23 | which essentially is a catalog of available events. Within this table, events are modeled using
24 | a composite key having the home team name as partition key, and event date as sort key, with
25 | the away team name as an ordinary attribute. This allows an event to be modeled as a single item
26 | in the table.
27 |
28 | The primary prerequisite for running the code for this example is to create a table in DynamoDB.
29 | The following attributes are required, with types indicated and whether the attribute functions
30 | as a partition or sort key for the table or a Global Secondary Index (GSI):
31 |
32 | homeTeam: String, Partition Key
33 | eventDate: Number, Sort Key
34 | awayTeam: String, GSI Partition Key
35 | city: String, GSI Partition Key
36 | eventId: Number
37 | sport: String
38 | country: String
39 |
40 |
41 | ### DEPLOYMENT NOTE:
42 |
43 | Follow these steps to deploy the application:
44 |
45 | - Create a DynamoDB table with the keys and attributes mentioned above.
46 |
47 | - Create Lambda functions, one for each handler in the EventFunctions class.
48 |
49 | - Create a API Gateway API. Note that even if you don't do this step, you can still test the Lambda functions via the Lambda console "test function" tab.
50 |
51 | To automate deployment of the Lambda functions and API Gateway, consider using AWS SAM (Serverless Application Model). Using SAM can simplify deploying an API, such as this one, built with a single code base that supports multiple Lambda functions. See http://docs.aws.amazon.com/lambda/latest/dg/deploying-lambda-apps.html.
52 |
53 |
--------------------------------------------------------------------------------
/images/architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/lambda-java8-dynamodb/15a015dda4d63df2b03e30e00057bc7cc432776d/images/architecture.jpg
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.amazonaws
8 | LambdaDynamoDBJava8
9 | 1.0
10 | jar
11 |
12 |
13 |
14 | 1.8
15 | UTF-8
16 |
17 |
18 |
19 |
20 |
21 | com.amazonaws
22 | aws-lambda-java-core
23 | 1.1.0
24 |
25 |
26 |
27 | com.amazonaws
28 | aws-lambda-java-log4j
29 | 1.0.0
30 |
31 |
32 |
33 | com.amazonaws
34 | aws-java-sdk-dynamodb
35 | 1.11.6
36 |
37 |
38 |
39 |
40 |
41 |
42 | ${project.artifactId}
43 |
44 |
45 |
46 |
47 | org.apache.maven.plugins
48 | maven-shade-plugin
49 | 2.3
50 |
51 | false
52 |
53 |
54 |
55 | package
56 |
57 | shade
58 |
59 |
60 |
61 |
62 |
63 |
64 | org.apache.maven.plugins
65 | maven-compiler-plugin
66 | 3.1
67 |
68 | 1.8
69 | 1.8
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/dao/DynamoDBEventDao.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.dao;
16 |
17 |
18 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
19 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
20 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
21 | import com.amazonaws.services.dynamodbv2.model.AttributeValue;
22 | import com.amazonaws.serverless.domain.Event;
23 | import com.amazonaws.serverless.manager.DynamoDBManager;
24 | import org.apache.log4j.Logger;
25 |
26 | import java.util.*;
27 |
28 |
29 | public class DynamoDBEventDao implements EventDao {
30 |
31 | private static final Logger log = Logger.getLogger(DynamoDBEventDao.class);
32 |
33 | private static final DynamoDBMapper mapper = DynamoDBManager.mapper();
34 |
35 | private static volatile DynamoDBEventDao instance;
36 |
37 |
38 | private DynamoDBEventDao() { }
39 |
40 | public static DynamoDBEventDao instance() {
41 |
42 | if (instance == null) {
43 | synchronized(DynamoDBEventDao.class) {
44 | if (instance == null)
45 | instance = new DynamoDBEventDao();
46 | }
47 | }
48 | return instance;
49 | }
50 |
51 | @Override
52 | public List findAllEvents() {
53 | return mapper.scan(Event.class, new DynamoDBScanExpression());
54 | }
55 |
56 | @Override
57 | public List findEventsByCity(String city) {
58 |
59 | Map eav = new HashMap<>();
60 | eav.put(":v1", new AttributeValue().withS(city));
61 |
62 | DynamoDBQueryExpression query = new DynamoDBQueryExpression()
63 | .withIndexName(Event.CITY_INDEX)
64 | .withConsistentRead(false)
65 | .withKeyConditionExpression("city = :v1")
66 | .withExpressionAttributeValues(eav);
67 |
68 | return mapper.query(Event.class, query);
69 |
70 |
71 | // NOTE: without an index, this query would require a full table scan with a filter:
72 | /*
73 | DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
74 | .withFilterExpression("city = :val1")
75 | .withExpressionAttributeValues(eav);
76 |
77 | return mapper.scan(Event.class, scanExpression);
78 | */
79 |
80 | }
81 |
82 | @Override
83 | public List findEventsByTeam(String team) {
84 |
85 | DynamoDBQueryExpression homeQuery = new DynamoDBQueryExpression<>();
86 | Event eventKey = new Event();
87 | eventKey.setHomeTeam(team);
88 | homeQuery.setHashKeyValues(eventKey);
89 | List homeEvents = mapper.query(Event.class, homeQuery);
90 |
91 | Map eav = new HashMap<>();
92 | eav.put(":v1", new AttributeValue().withS(team));
93 | DynamoDBQueryExpression awayQuery = new DynamoDBQueryExpression()
94 | .withIndexName(Event.AWAY_TEAM_INDEX)
95 | .withConsistentRead(false)
96 | .withKeyConditionExpression("awayTeam = :v1")
97 | .withExpressionAttributeValues(eav);
98 |
99 | List awayEvents = mapper.query(Event.class, awayQuery);
100 |
101 | // need to create a new list because PaginatedList from query is immutable
102 | List allEvents = new LinkedList<>();
103 | allEvents.addAll(homeEvents);
104 | allEvents.addAll(awayEvents);
105 | allEvents.sort( (e1, e2) -> e1.getEventDate() <= e2.getEventDate() ? -1 : 1 );
106 |
107 | return allEvents;
108 | }
109 |
110 | @Override
111 | public Optional findEventByTeamAndDate(String team, Long eventDate) {
112 |
113 | Event event = mapper.load(Event.class, team, eventDate);
114 |
115 | return Optional.ofNullable(event);
116 | }
117 |
118 | @Override
119 | public void saveOrUpdateEvent(Event event) {
120 |
121 | mapper.save(event);
122 | }
123 |
124 | @Override
125 | public void deleteEvent(String team, Long eventDate) {
126 |
127 | Optional oEvent = findEventByTeamAndDate(team, eventDate);
128 | if (oEvent.isPresent()) {
129 | mapper.delete(oEvent.get());
130 | }
131 | else {
132 | log.error("Could not delete event, no such team and date combination");
133 | throw new IllegalArgumentException("Delete failed for nonexistent event");
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/dao/EventDao.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.dao;
16 |
17 |
18 | import com.amazonaws.serverless.domain.Event;
19 |
20 | import java.util.List;
21 | import java.util.Optional;
22 |
23 |
24 | public interface EventDao {
25 |
26 | List findAllEvents();
27 |
28 | List findEventsByCity(String city);
29 |
30 | List findEventsByTeam(String team);
31 |
32 | Optional findEventByTeamAndDate(String team, Long eventDate);
33 |
34 | void saveOrUpdateEvent(Event event);
35 |
36 | void deleteEvent(String team, Long eventDate);
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/domain/Event.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.domain;
16 |
17 |
18 | import com.amazonaws.services.dynamodbv2.datamodeling.*;
19 |
20 | import java.io.Serializable;
21 |
22 |
23 | @DynamoDBTable(tableName = "EVENT")
24 | public class Event implements Serializable {
25 |
26 | private static final long serialVersionUID = -8243145429438016232L;
27 | public static final String CITY_INDEX = "City-Index";
28 | public static final String AWAY_TEAM_INDEX = "AwayTeam-Index";
29 |
30 | @DynamoDBAttribute
31 | private Long eventId;
32 |
33 | @DynamoDBRangeKey
34 | private Long eventDate;
35 |
36 | @DynamoDBAttribute
37 | private String sport;
38 |
39 | @DynamoDBHashKey
40 | private String homeTeam;
41 |
42 | @DynamoDBIndexHashKey(globalSecondaryIndexName = AWAY_TEAM_INDEX)
43 | private String awayTeam;
44 |
45 | @DynamoDBIndexHashKey(globalSecondaryIndexName = CITY_INDEX)
46 | private String city;
47 |
48 | @DynamoDBAttribute
49 | private String country;
50 |
51 | public Event() { }
52 |
53 | public Event(String team, Long date) {
54 | this.homeTeam = team;
55 | this.eventDate = date;
56 | }
57 |
58 | public Event(Long eventId, Long eventDate, String sport, String homeTeam, String awayTeam, String city, String country) {
59 | this.eventId = eventId;
60 | this.eventDate = eventDate;
61 | this.sport = sport;
62 | this.homeTeam = homeTeam;
63 | this.awayTeam = awayTeam;
64 | this.city = city;
65 | this.country = country;
66 | }
67 |
68 |
69 | public Long getEventId() {
70 | return eventId;
71 | }
72 |
73 | public void setEventId(Long eventId) {
74 | this.eventId = eventId;
75 | }
76 |
77 | public Long getEventDate() {
78 | return eventDate;
79 | }
80 |
81 | public void setEventDate(Long eventDate) {
82 | this.eventDate = eventDate;
83 | }
84 |
85 | public String getSport() {
86 | return sport;
87 | }
88 |
89 | public void setSport(String sport) {
90 | this.sport = sport;
91 | }
92 |
93 | public String getHomeTeam() {
94 | return homeTeam;
95 | }
96 |
97 | public void setHomeTeam(String homeTeam) {
98 | this.homeTeam = homeTeam;
99 | }
100 |
101 | public String getAwayTeam() {
102 | return awayTeam;
103 | }
104 |
105 | public void setAwayTeam(String awayTeam) {
106 | this.awayTeam = awayTeam;
107 | }
108 |
109 | public String getCity() {
110 | return city;
111 | }
112 |
113 | public void setCity(String city) {
114 | this.city = city;
115 | }
116 |
117 | public String getCountry() {
118 | return country;
119 | }
120 |
121 | public void setCountry(String country) {
122 | this.country = country;
123 | }
124 |
125 | }
126 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/function/EventFunctions.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.function;
16 |
17 |
18 | import java.io.UnsupportedEncodingException;
19 | import java.net.URLDecoder;
20 | import java.util.List;
21 |
22 | import com.amazonaws.serverless.dao.DynamoDBEventDao;
23 | import com.amazonaws.serverless.pojo.Team;
24 | import com.amazonaws.serverless.util.Consts;
25 | import org.apache.log4j.Logger;
26 |
27 | import com.amazonaws.serverless.domain.Event;
28 | import com.amazonaws.serverless.pojo.City;
29 |
30 |
31 | public class EventFunctions {
32 |
33 | private static final Logger log = Logger.getLogger(EventFunctions.class);
34 |
35 | private static final DynamoDBEventDao eventDao = DynamoDBEventDao.instance();
36 |
37 |
38 | public List getAllEventsHandler() {
39 |
40 | log.info("GetAllEvents invoked to scan table for ALL events");
41 | List events = eventDao.findAllEvents();
42 | log.info("Found " + events.size() + " total events.");
43 | return events;
44 | }
45 |
46 | public List getEventsForTeam(Team team) throws UnsupportedEncodingException {
47 |
48 | if (null == team || team.getTeamName().isEmpty() || team.getTeamName().equals(Consts.UNDEFINED)) {
49 | log.error("GetEventsForTeam received null or empty team name");
50 | throw new IllegalArgumentException("Team name cannot be null or empty");
51 | }
52 |
53 | String name = URLDecoder.decode(team.getTeamName(), "UTF-8");
54 | log.info("GetEventsForTeam invoked for team with name = " + name);
55 | List events = eventDao.findEventsByTeam(name);
56 | log.info("Found " + events.size() + " events for team = " + name);
57 |
58 | return events;
59 | }
60 |
61 | public List getEventsForCity(City city) throws UnsupportedEncodingException {
62 |
63 | if (null == city || city.getCityName().isEmpty() || city.getCityName().equals(Consts.UNDEFINED)) {
64 | log.error("GetEventsForCity received null or empty city name");
65 | throw new IllegalArgumentException("City name cannot be null or empty");
66 | }
67 |
68 | String name = URLDecoder.decode(city.getCityName(), "UTF-8");
69 | log.info("GetEventsForCity invoked for city with name = " + name);
70 | List events = eventDao.findEventsByCity(name);
71 | log.info("Found " + events.size() + " events for city = " + name);
72 |
73 | return events;
74 | }
75 |
76 | public void saveOrUpdateEvent(Event event) {
77 |
78 | if (null == event) {
79 | log.error("SaveEvent received null input");
80 | throw new IllegalArgumentException("Cannot save null object");
81 | }
82 |
83 | log.info("Saving or updating event for team = " + event.getHomeTeam() + " , date = " + event.getEventDate());
84 | eventDao.saveOrUpdateEvent(event);
85 | log.info("Successfully saved/updated event");
86 | }
87 |
88 | public void deleteEvent(Event event) {
89 |
90 | if (null == event) {
91 | log.error("DeleteEvent received null input");
92 | throw new IllegalArgumentException("Cannot delete null object");
93 | }
94 |
95 | log.info("Deleting event for team = " + event.getHomeTeam() + " , date = " + event.getEventDate());
96 | eventDao.deleteEvent(event.getHomeTeam(), event.getEventDate());
97 | log.info("Successfully deleted event");
98 | }
99 |
100 | }
101 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/manager/DynamoDBManager.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.manager;
16 |
17 |
18 | import com.amazonaws.regions.Region;
19 | import com.amazonaws.regions.Regions;
20 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
21 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
22 |
23 |
24 | public class DynamoDBManager {
25 |
26 | private static volatile DynamoDBManager instance;
27 |
28 | private static DynamoDBMapper mapper;
29 |
30 | private DynamoDBManager() {
31 |
32 | AmazonDynamoDBClient client = new AmazonDynamoDBClient();
33 | client.setRegion(Region.getRegion(Regions.US_EAST_1));
34 | mapper = new DynamoDBMapper(client);
35 | }
36 |
37 | public static DynamoDBManager instance() {
38 |
39 | if (instance == null) {
40 | synchronized(DynamoDBManager.class) {
41 | if (instance == null)
42 | instance = new DynamoDBManager();
43 | }
44 | }
45 |
46 | return instance;
47 | }
48 |
49 | public static DynamoDBMapper mapper() {
50 |
51 | DynamoDBManager manager = instance();
52 | return manager.mapper;
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/pojo/City.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.pojo;
16 |
17 | /**
18 | *
19 | * This simple POJO is for use with Amazon API Gateway so the
20 | * Lambda functions can receive JSON objects from API Gateway,
21 | * rather than simple Strings.
22 | *
23 | */
24 | public class City {
25 |
26 | private String cityName;
27 |
28 | public String getCityName() {
29 | return cityName;
30 | }
31 |
32 | public void setCityName(String cityName) {
33 | this.cityName = cityName;
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/pojo/Team.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.pojo;
16 |
17 | /**
18 | *
19 | * This simple POJO is for use with Amazon API Gateway so the
20 | * Lambda functions can receive JSON objects from API Gateway,
21 | * rather than simple Strings.
22 | *
23 | */
24 | public class Team {
25 |
26 | private String teamName;
27 |
28 |
29 | public String getTeamName() {
30 | return teamName;
31 | }
32 |
33 | public void setTeamName(String teamName) {
34 | this.teamName = teamName;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/amazonaws/serverless/util/Consts.java:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may
4 | // not use this file except in compliance with the License. A copy of the
5 | // License is located at
6 | //
7 | // http://aws.amazon.com/apache2.0/
8 | //
9 | // or in the "license" file accompanying this file. This file is distributed
10 | // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
11 | // express or implied. See the License for the specific language governing
12 | // permissions and limitations under the License.
13 |
14 |
15 | package com.amazonaws.serverless.util;
16 |
17 | /**
18 | *
19 | * Static constants class
20 | *
21 | */
22 | public class Consts {
23 |
24 | private Consts() {} // callers can't instantiate class itself
25 |
26 | // "undefined" is the string sent by the Amazon API Gateway console when using
27 | // the console's test functionality if an API parameter is left blank
28 | public static final String UNDEFINED = "undefined";
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log = .
2 | log4j.rootLogger = INFO, LAMBDA
3 |
4 | #Define the LAMBDA appender
5 | log4j.appender.LAMBDA=com.amazonaws.services.lambda.runtime.log4j.LambdaAppender
6 | log4j.appender.LAMBDA.layout=org.apache.log4j.PatternLayout
7 | log4j.appender.LAMBDA.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} <%X{AWSRequestId}> %-5p %c{1}:%L - %m%n
--------------------------------------------------------------------------------