Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Java Example #149

Merged
merged 17 commits into from
Jun 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/cdk-examples-java/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
!*.t.js
51 changes: 51 additions & 0 deletions examples/cdk-examples-java/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# CDK Java Example

This an example of a CDK program written in Java.

> NOTE: Since this example currently resides inside the CDK repository, it takes
a dependency on the CDK for Java maven package that's built under
`packages/aws-cdk-java`. To enable this, we generate the `pom.xml` file, so we
can plug in the locations of the local maven repositories. This is not
something you will need to do if you are simply using the published CDK maven
package.

## Building

To build this app, run `npm run prepare`. This will:

1. Generate `project/pom.xml` with correct references to jsii and CDK
dependencies.
2. Run `mvn package`, which will compile, test and assemble an executable jar.

## IDE

Once the `pom.xml` file is generated, the [`./project`](./project) directory is
fully functional Maven project, and you should be able to open it from any Java
IDE which supports Maven.

You can use the 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 use `java -jar <executale-jar> app` for the `--app` switch. This means,
you should be able to use the toolkit normally:

```
$ 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>
```

If you make modifications, make sure to rebuild the app, either by callign `mvn
package` from `./project` or `npm run prepare` from the root.
3 changes: 3 additions & 0 deletions examples/cdk-examples-java/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "java -jar project/target/cdk-examples-java-0.7.2-beta-jar-with-dependencies.jar app"
}
3 changes: 3 additions & 0 deletions examples/cdk-examples-java/generate.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/bash
set -euo pipefail
node ./pom.xml.t.js > project/pom.xml
30 changes: 30 additions & 0 deletions examples/cdk-examples-java/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "cdk-examples-java",
"version": "0.7.2-beta",
"description": "CDK examples in Java",
"private": true,
"repository": {
"type": "git",
"url": "git://github.com/awslabs/aws-cdk"
},
"pkglint": {
"ignore": true
},
"scripts": {
"prepare": "/bin/bash generate.sh && cd project && mvn package",
"cdk": "cdk",
"test": "echo ok"
},
"author": {
"name": "Amazon Web Services",
"url": "https://aws.amazon.com"
},
"license": "Apache-2.0",
"dependencies": {
"aws-cdk-java": "^0.7.2-beta"
},
"devDependencies": {
"aws-cdk": "^0.7.2-beta",
"pkgtools": "^0.7.2-beta"
}
}
117 changes: 117 additions & 0 deletions examples/cdk-examples-java/pom.xml.t.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
const path = require('path');
const version = require('./package.json').version;

const mavenFromNpm = name => ({
version: require(`${name}/package.json`).version,
repo: path.join(path.dirname(require.resolve(name)), 'maven-repo'),
});

const cdk = mavenFromNpm('aws-cdk-java');
const jsii = mavenFromNpm('jsii-java-runtime');

process.stdout.write(`
<?xml version="1.0" encoding="UTF-8"?>

<!-- Generated by ${__filename} at ${new Date().toISOString()} -->
<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>

<repositories>
<repository>
<id>cdk</id>
<url>file://${cdk.repo}</url>
</repository>
<repository>
<id>jsii</id>
<url>file://${jsii.repo}</url>
</repository>
</repositories>

<groupId>com.amazonaws.cdk</groupId>
<artifactId>cdk-examples-java</artifactId>
<version>${version}</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>

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would add the necessary things to produce a manifest that mentions the mainClass.

<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.HelloJavaApp</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>com.amazonaws</groupId>
<artifactId>jsii-runtime</artifactId>
<version>${jsii.version}</version>
</dependency>

<dependency>
<groupId>com.amazonaws.cdk</groupId>
<artifactId>aws-cdk</artifactId>
<version>${cdk.version}</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.5</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.5</version>
</dependency>

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

</dependencies>


</project>
`);
9 changes: 9 additions & 0 deletions examples/cdk-examples-java/project/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
target

# generated by pom.xml.t.js
pom.xml

.idea
.classpath
.project
.settings
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.amazonaws.cdk.examples;

import com.amazonaws.cdk.App;

import java.util.Arrays;

public class HelloJavaApp {
public static void main(final String[] args) {
App app = new App(Arrays.asList(args));

new HelloJavaStack(app, "hello-cdk");

System.out.println(app.run());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.amazonaws.cdk.examples;

import com.amazonaws.cdk.App;
import com.amazonaws.cdk.Stack;
import com.amazonaws.cdk.StackProps;
import com.amazonaws.cdk.Construct;
import com.amazonaws.cdk.ec2.Fleet;
import com.amazonaws.cdk.ec2.FleetProps;
import com.amazonaws.cdk.ec2.InstanceType;
import com.amazonaws.cdk.ec2.VpcNetwork;
import com.amazonaws.cdk.ec2.WindowsImage;
import com.amazonaws.cdk.ec2.WindowsVersion;
import com.amazonaws.cdk.resources.s3.BucketResource;
import com.amazonaws.cdk.resources.s3.BucketResourceProps;
import com.amazonaws.cdk.sns.Topic;
import com.amazonaws.cdk.sqs.Queue;
import com.amazonaws.cdk.sqs.QueueProps;

import java.util.Collections;
import java.util.List;

/**
* Hello, CDK for Java!
*/
class HelloJavaStack extends Stack {
public HelloJavaStack(final App parent, final String name) {
super(parent, name);

VpcNetwork vpc = new VpcNetwork(this, "VPC");

MyFleetProps fleetProps = new MyFleetProps();
fleetProps.vpc = vpc;

int topicCount = 5;

SinkQueue sinkQueue = new SinkQueue(this, "MySinkQueue", SinkQueueProps.builder().withRequiredTopicCount(5).build());

for (int i = 0; i < topicCount; ++i) {
sinkQueue.subscribe(new Topic(this, "Topic" + (i+1)));
}

new MyFleet(this, "MyFleet", fleetProps);
}

static class MyFleetProps {
public VpcNetwork vpc;
}

static class MyFleet extends Construct {
MyFleet(final Construct parent, final String name, final MyFleetProps props) {
super(parent, name);

new Fleet(this, "Compute", FleetProps.builder()
.withInstanceType(new InstanceType("t2.micro"))
.withMachineImage(new WindowsImage(WindowsVersion.WindowsServer2016EnglishNanoBase))
.withVpc(props.vpc)
.build());
}

@Override
public List<String> validate() {
System.err.println("Validating MyFleet...");
return Collections.emptyList();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.amazonaws.cdk.examples;

import com.amazonaws.cdk.Construct;
import com.amazonaws.cdk.sns.Topic;
import com.amazonaws.cdk.sqs.Queue;
import com.amazonaws.cdk.sqs.QueueProps;

import java.util.Arrays;
import java.util.List;

/**
* A sink queue is a queue aggregates messages published to any number of SNS topics.
*/
public class SinkQueue extends Construct {
private final Queue queue;
private final int expectedTopicCount;

private int actualTopicCount = 0;

/**
* Defines a SinkQueue.
*
* @param parent Parent construct
* @param name Logical name
* @param props Props
*/
public SinkQueue(final Construct parent, final String name, SinkQueueProps props) {
super(parent, name);

// ensure props is non-null
props = props != null ? props : SinkQueueProps.builder().build();

// defaults
QueueProps queueProps = props.getQueueProps();
this.expectedTopicCount = props.getRequiredTopicCount() != null ? props.getRequiredTopicCount().intValue() : 10;

// WORKAROUND: https://github.com/awslabs/aws-cdk/issues/157
if (queueProps == null) {
queueProps = QueueProps.builder().build();
}

this.queue = new Queue(this, "Resource", queueProps);
}

/**
* Defines a SinkQueue with default props.
* @param parent Parent construct
* @param name Logical name
*/
public SinkQueue(final Construct parent, final String name) {
this(parent, name, null);
}

/**
* Subscribes this queue to receive messages published to the specified topics.
*
* @param topics The topics to subscribe to
*/
public void subscribe(final Topic... topics) {
for (Topic topic: topics) {
if (actualTopicCount == expectedTopicCount) {
throw new RuntimeException("Cannot add more topics to the sink. Maximum topics is configured to " + this.expectedTopicCount);
}
topic.subscribeQueue(this.queue);
actualTopicCount++;
}
}

@Override
public List<String> validate() {
if (actualTopicCount < expectedTopicCount) {
return Arrays.asList(
"There are not enough subscribers to the sink. Expecting " +
this.expectedTopicCount +
", actual is " + this.actualTopicCount);
}

return super.validate();
}
}
Loading