Skip to content

Commit

Permalink
Add Java version of the Lambda Cron example (aws-samples#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
emma-burrows authored and rix0rrr committed May 19, 2019
1 parent df216a8 commit d05af6f
Show file tree
Hide file tree
Showing 9 changed files with 404 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ $ cdk destroy
| Example | Description |
|---------|-------------|
| [hello-world](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/hello-world/) | A demo application that uses the CDK in Java |
| [lambda-cron](https://github.com/aws-samples/aws-cdk-examples/tree/master/java/lambda-cron/) | Running a Lambda on a schedule |

## Python examples

Expand Down
32 changes: 32 additions & 0 deletions java/lambda-cron/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# CDK Java Example

This an example of a CDK program written in Java.

## Building

To build this app, run `mvn compile`. This will download the required
dependencies compile the Java code.

You can use your IDE to write code and unit tests, but you will need to use the
CDK toolkit if you wish to synthesize/deploy stacks.

## CDK Toolkit

The [`cdk.json`](./cdk.json) file in the root of this repository includes
instructions for the CDK toolkit on how to execute this program.

Specifically, it will tell the toolkit to use the `mvn exec:java` command as the
entry point of your application. After changing your Java code, you will be able
to run the CDK toolkits commands as usual (Maven will recompile as needed):

$ cdk ls
<list all stacks in this program>

$ cdk synth
<cloudformation template>

$ cdk deploy
<deploy stack to your account>

$ cdk diff
<diff against deployed stack>
3 changes: 3 additions & 0 deletions java/lambda-cron/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "mvn exec:java -Dexec.mainClass=software.amazon.awscdk.examples.LambdaCronApp"
}
109 changes: 109 additions & 0 deletions java/lambda-cron/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>

<groupId>com.amazonaws.cdk</groupId>
<artifactId>lambda-cron</artifactId>
<version>1.0.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.amazonaws.cdk.examples.LambdaCronApp</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>

</plugins>
</build>

<dependencies>
<dependency>
<groupId>software.amazon.jsii</groupId>
<artifactId>jsii-runtime</artifactId>
<version>0.7.14</version>
</dependency>

<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>cdk</artifactId>
<version>0.23.0</version>
</dependency>

<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>lambda</artifactId>
<version>0.23.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>[2.9.8,)</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>[2.9.8,)</version>
</dependency>

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>


</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package software.amazon.awscdk.examples;

import software.amazon.awscdk.App;

public class LambdaCronApp {
public static void main(final String[] args) {
App app = new App();

new LambdaCronStack(app, "cdk-lambda-cron-example");

app.run();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package software.amazon.awscdk.examples;

import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.services.events.EventRule;
import software.amazon.awscdk.services.events.EventRuleProps;
import software.amazon.awscdk.services.lambda.Code;
import software.amazon.awscdk.services.lambda.Runtime;
import software.amazon.awscdk.services.lambda.SingletonFunction;
import software.amazon.awscdk.services.lambda.SingletonFunctionProps;

import java.util.UUID;

/**
* Lambda Cron CDK example for Java!
*/
class LambdaCronStack extends Stack {
public LambdaCronStack(final App parent, final String name) {
super(parent, name);

SingletonFunction lambdaFunction = new SingletonFunction(this, "cdk-lambda-cron",
SingletonFunctionProps.builder()
.withFunctionName("CDK Lambda Cron Example")
.withDescription("Lambda which prints \"I'm running\"")
.withCode(Code.inline(
"def main(event, context):\n" +
" print(\"I'm running!\")\n"))
.withHandler("index.main")
.withTimeout(300)
.withRuntime(Runtime.PYTHON27)
.withUuid(UUID.randomUUID().toString())
.build()
);

EventRule rule = new EventRule(this, "cdk-lambda-cron-rule",
EventRuleProps.builder()
.withDescription("Run every day at 6PM UTC")
.withScheduleExpression("cron(0 18 ? * MON-FRI *)")
.build()
);

rule.addTarget(lambdaFunction);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package software.amazon.awscdk.examples;

import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;

import java.io.IOException;
import java.util.List;

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static software.amazon.awscdk.examples.TestUtils.toCloudFormationJson;

public class LambdaCronStackTest {
private App app;
private Stack stack;
private JsonNode actualStack;
private JsonNode expectedStack;

@Before
public void setUp() throws IOException {
app = new App();
stack = new LambdaCronStack(app, "lambdaResource-cdk-lambda-cron");
actualStack = toCloudFormationJson(stack).path("Resources");
expectedStack = TestUtils.fromFileResource(getClass().getResource("testCronLambdaExpected.json")).path("Resources");
}

@Test()
public void testTypes() {
List<JsonNode> actual = actualStack.findValues("Type");
List<JsonNode> expected = expectedStack.findValues("Type");
containsInAnyOrder(actual, expected);
}

@Test
public void testPermission() {
final String type = "AWS::Lambda::Permission";
JsonNode actual = TestUtils.getJsonNode(actualStack, type);
JsonNode expected = TestUtils.getJsonNode(expectedStack, type);
String[] keys = {"ManagedPolicyArns", "AssumeRolePolicyDocument"};
for (String key : keys) {
assertEquals(actual.get(key), expected.get(key));
}
}

@Test
public void testRole() {
final String type = "AWS::IAM::Role";
JsonNode actual = TestUtils.getJsonNode(actualStack, type);
JsonNode expected = TestUtils.getJsonNode(expectedStack, type);
String[] keys = {"ManagedPolicyArns", "AssumeRolePolicyDocument"};
for (String key : keys) {
assertEquals(actual.get(key), expected.get(key));
}
}

@Test
public void testLambda() {
final String type = "AWS::Lambda::Function";
JsonNode actual = TestUtils.getJsonNode(actualStack, type);
JsonNode expected = TestUtils.getJsonNode(expectedStack, type);
String[] keys = {"Runtime", "Description", "Timeout", "Handler", "Code"};
for (String key : keys) {
assertEquals(actual.get(key), expected.get(key));
}
}

@Test
public void testRule() {
final String type = "AWS::Events::Rule";
JsonNode actual = TestUtils.getJsonNode(actualStack, type);
JsonNode expected = TestUtils.getJsonNode(expectedStack, type);
String[] keys = {"ScheduleExpression", "Description", "State"};
for (String key : keys) {
assertEquals(actual.get(key), expected.get(key));
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package software.amazon.awscdk.examples;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.awscdk.Stack;

import java.io.IOException;
import java.net.URL;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.junit.Assert.assertEquals;

public class TestUtils {
private static ObjectMapper JSON = new ObjectMapper();

static JsonNode fromFileResource(final URL fileResource) throws IOException {
return JSON.readTree(fileResource);
}

static JsonNode toCloudFormationJson(final Stack stack) throws IOException {
JsonNode n = JSON.valueToTree(stack.toCloudFormation());
System.out.println(JSON.writerWithDefaultPrettyPrinter().writeValueAsString(n));
return n;
}

static void assertTemplate(final Stack stack, final URL expectedResource) throws IOException {
assertTemplate(stack, JSON.readTree(expectedResource));
}

static void assertTemplate(final Stack stack, final String expectedTemplate) throws IOException {
assertTemplate(stack, JSON.readTree(expectedTemplate));
}

private static void assertTemplate(final Stack stack, final JsonNode expected) throws IOException {
JsonNode actual = toCloudFormationJson(stack);

// print to stderr if non-equal, so it will be easy to grab
if (expected == null || !expected.equals(actual)) {
String prettyActual = JSON.writerWithDefaultPrettyPrinter().writeValueAsString(actual);
System.err.println(prettyActual);
}

assertEquals(expected, actual);
}

static JsonNode getJsonNode(JsonNode stackJson, String type) {
Iterable<JsonNode> iterable = stackJson::elements;
Optional<JsonNode> maybe = StreamSupport.stream(iterable.spliterator(), false)
.filter(jn -> jn.get("Type").textValue().equals(type)).findFirst();
return maybe.map(jn -> jn.path("Properties")).orElseThrow(NoSuchElementException::new);
}
}
Loading

0 comments on commit d05af6f

Please sign in to comment.