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

Final additions in private beta #861

Merged
merged 11 commits into from
Sep 26, 2017
60 changes: 60 additions & 0 deletions iot/api-client/http_example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Cloud IoT Core Java HTTP example

This sample app publishes data to Cloud Pub/Sub using the HTTP bridge provided
as part of Google Cloud IoT Core.

Note that before you can run the sample, you must configure a Google Cloud
PubSub topic for Cloud IoT Core and register a device as described in the
[parent README](../README.md).

## Setup

Run the following command to install the dependencies using Maven:

mvn clean compile

## Running the sample

The following command summarizes the sample usage:

```
mvn exec:java \
-Dexec.mainClass="com.google.cloud.iot.examples.HttpExample" \
-Dexec.args="-project_id=my-iot-project \
-registry_id=my-registry \
-device_id=my-device \
-private_key_file=rsa_private_pkcs8 \
-algorithm=RS256"
```

For example, if your project ID is `blue-jet-123`, your service account
credentials are stored in your home folder in creds.json and you have generated
your credentials using the [`generate_keys.sh`](../generate_keys.sh) script
provided in the parent folder, you can run the sample as:

```
mvn exec:java \
-Dexec.mainClass="com.google.cloud.iot.examples.HttpExample" \
-Dexec.args="-project_id=blue-jet-123 \
-registry_id=my-registry \
-device_id=my-java-device \
-private_key_file=../rsa_private_pkcs8 \
-algorithm=RS256"
```

## Reading the messages written by the sample client

1. Create a subscription to your topic.

```
gcloud beta pubsub subscriptions create \
Copy link
Contributor

Choose a reason for hiding this comment

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

I assume gcloud installation is covered in the parent README ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, the guide, linked in the doc, covers this.

projects/your-project-id/subscriptions/my-subscription \
--topic device-events
```

2. Read messages published to the topic

```
gcloud beta pubsub subscriptions pull --auto-ack \
projects/my-iot-project/subscriptions/my-subscription
```
47 changes: 47 additions & 0 deletions iot/api-client/http_example/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Copy link
Contributor

Choose a reason for hiding this comment

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

missing license header

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added here and elsewhere.

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.cloud.iot.examples</groupId>
<artifactId>cloudiot-http-example</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>cloudiot-http-example</name>
<url>http://maven.apache.org</url>

<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<!-- Parent defines config for testing & linting. -->
<parent>
<artifactId>doc-samples</artifactId>
<groupId>com.google.cloud</groupId>
<version>1.0.0</version>
<relativePath>../../../</relativePath>
</parent>

<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package com.google.cloud.iot.examples;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import org.joda.time.DateTime;
import org.json.JSONObject;

/**
* Java sample of connecting to Google Cloud IoT Core vice via HTTP, using JWT.
*
* <p>This example connects to Google Cloud IoT Core via HTTP Bridge, using a JWT for device
* authentication. After connecting, by default the device publishes 100 messages at a rate of one
* per second, and then exits. You can change The behavior to set state instead of events by using
* flag -message_type to 'state'.
*
* <p>To run this example, follow the instructions in the README located in the sample's parent
* folder.
*/
public class HttpExample {
/** Create a Cloud IoT Core JWT for the given project id, signed with the given private key. */
private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
DateTime now = new DateTime();
// Create a JWT to authenticate this device. The device will be disconnected after the token
// expires, and will have to reconnect with a new token. The audience field should always be set
// to the GCP project id.
JwtBuilder jwtBuilder =
Jwts.builder()
.setIssuedAt(now.toDate())
.setExpiration(now.plusMinutes(20).toDate())
.setAudience(projectId);

byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");

return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}

private static String createJwtEs(String projectId, String privateKeyFile) throws Exception {
DateTime now = new DateTime();
// Create a JWT to authenticate this device. The device will be disconnected after the token
// expires, and will have to reconnect with a new token. The audience field should always be set
// to the GCP project id.
JwtBuilder jwtBuilder =
Jwts.builder()
.setIssuedAt(now.toDate())
.setExpiration(now.plusMinutes(20).toDate())
.setAudience(projectId);

byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("ES256");

return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}

public static void main(String[] args) throws Exception {
HttpExampleOptions options = HttpExampleOptions.fromFlags(args);
if (options == null) {
// Could not parse the flags.
System.exit(1);
}

// Build the resource path of the device that is going to be authenticated.
String devicePath =
String.format(
"projects/%s/locations/%s/registries/%s/devices/%s",
options.projectId, options.cloudRegion, options.registryId, options.deviceId);

// This describes the operation that is going to be perform with the device.
String urlSuffix = options.messageType.equals("event") ? "publishEvent" : "setState";

String urlPath =
String.format(
"%s/%s/%s:%s", options.httpBridgeAddress, options.apiVersion, devicePath, urlSuffix);
URL url = new URL(urlPath);
System.out.format("Using URL: '%s'\n", urlPath);

// Create the corresponding JWT depending on the selected algorithm.
String token;
if (options.algorithm.equals("RS256")) {
token = createJwtRsa(options.projectId, options.privateKeyFile);
} else if (options.algorithm.equals("ES256")) {
token = createJwtEs(options.projectId, options.privateKeyFile);
} else {
throw new IllegalArgumentException(
"Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
}

// Data sent through the wire has to be base64 encoded.
Base64.Encoder encoder = Base64.getEncoder();

// Publish numMessages messages to the HTTP bridge.
for (int i = 1; i <= options.numMessages; ++i) {
String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i);
System.out.format(
"Publishing %s message %d/%d: '%s'\n",
options.messageType, i, options.numMessages, payload);
String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

// Adding headers.
httpCon.setRequestProperty("Authorization", String.format("Bearer %s", token));
httpCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

// Adding the post data. The structure of the data send depends on whether it is event or a
// state message.
JSONObject data = new JSONObject();
if (options.messageType.equals("event")) {
data.put("binary_data", encPayload);
} else {
JSONObject state = new JSONObject();
state.put("binary_data", encPayload);
data.put("state", state);
}
httpCon.getOutputStream().write(data.toString().getBytes("UTF-8"));
httpCon.getOutputStream().close();

// This will perform the connection as well.
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());

// Send events every second; states, every 5.
Thread.sleep(options.messageType.equals("event") ? 1000 : 5000);
Copy link
Contributor

Choose a reason for hiding this comment

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

it might be worth pulling out that param to sleep in a separate statement. so that the sleep statement is clearer.

}
System.out.println("Finished loop successfully. Goodbye!");
}
}
9 changes: 8 additions & 1 deletion iot/api-client/manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,14 @@ Create a device registry:
java -cp target/cloudiot-manager-demo-1.0-jar-with-dependencies.jar \
com.example.cloud.iot.examples.DeviceRegistryExample \
-project_id=blue-jet-123 -pubsub_topic=hello-java \
-registry_name=hello-java -command=create-registry \
-registry_name=hello-java -command=create-registry

Delete a device registry:

java -cp target/cloudiot-manager-demo-1.0-jar-with-dependencies.jar \
com.example.cloud.iot.examples.DeviceRegistryExample \
-project_id=blue-jet-123 -pubsub_topic=hello-java \
-registry_name=hello-java -command=delete-registry

Get a device registry:

Expand Down
7 changes: 7 additions & 0 deletions iot/api-client/manager/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@
</properties>

<dependencies>
<!--
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-cloudiot</artifactId>
<version>v1beta1-rev20170418-1.22.0-SNAPSHOT</version>
</dependency>
-->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
Copy link
Contributor

Choose a reason for hiding this comment

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

update to latest google-cloud-java libs

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done.

Expand All @@ -52,6 +54,11 @@
<artifactId>google-oauth-client</artifactId>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
Copy link
Contributor

Choose a reason for hiding this comment

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

can you confirm this is needed ? given you do include a google-cloud-java library:
https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/pom.xml#L750

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The tests will not work without explicitly including this.

Copy link
Contributor

Choose a reason for hiding this comment

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

@gguuss : I meant google-api-client and not guava. But if that too is the case, that tests don't compile, i'll take a look post-merge.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated, tests work still :)

<artifactId>google-api-client</artifactId>
Expand Down
4 changes: 4 additions & 0 deletions iot/api-client/manager/resources/ec_public.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECfwA4OrF9Pcr1W5mXUa+Dx8hpPYd
+pQ5153zNtSSaeEnA/4hrY2AKxUHmKIPJXYRkZrxTxsFElkkpLcoi/CUNQ==
-----END PUBLIC KEY-----
18 changes: 18 additions & 0 deletions iot/api-client/manager/resources/rsa_cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC+DCCAeCgAwIBAgIJAJW4zZX4mjtpMA0GCSqGSIb3DQEBCwUAMBExDzANBgNV
BAMMBnVudXNlZDAeFw0xNzA5MjUyMjM3MzhaFw0xNzEwMjUyMjM3MzhaMBExDzAN
BgNVBAMMBnVudXNlZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKaB
voBJf6cr+Q+S1l/n5Bp0i7BEYeeCnUta+MIZle38y0E3TzXQvjMr8uk081RcWqFq
wkRjY+OM7hLIMbs3C+Qvg6uxbjaJM0LE+gjwnU8Wg76Y4jjhl+tPYP9njWxRZF0d
7WGRMpaztKpukEpgUszC75YM9XVQCal6m3eegu5BraiXrAjngGOAninBe56jhw/b
HIqF85PXczI9BbUoJeq4VycRsdUa2dJSqMxKoF7T2blYLiLBFTyo72ZF6m8SAIzv
eMw78pgtwJK4ZIzONrSe2PaPtctyRmFQBGnnZaMGi3ToiYgQ/pQ4LkuPN1sCCv7y
n3ljavj+QM+IiM5DvZMCAwEAAaNTMFEwHQYDVR0OBBYEFFK2kAhd7rYZInQxdk8T
MZrXXBCrMB8GA1UdIwQYMBaAFFK2kAhd7rYZInQxdk8TMZrXXBCrMA8GA1UdEwEB
/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAKCB1nQ2rFsnQpRRtvjDqlI03Opc
8sfHQ4GxJ3L7ZuXx6MzH37k0+g5/dgGYhRM+Zm9fDnxD6a1c5fek+0iGGIHOg1Cw
9lwqZN15w7SXxMiwxDVYoMBvx7JQEZSFeMfP3ZcKdwSaFRYXNRtbeC45VS70MwhM
CgqqkGDi2hM/JGYxv+UCvIm5+JrF+4SGOFtZeIT8mayq+ZOiD3+Sqo1++mRNXkSr
C8+QUjxW9y2CObE6d7Y/fryfO0mlWUnJS8Ed5H+12GqFWc7HudV2EIPS4RgthdZs
odK3woxB+18j28C1toSaSzzUtaS6hxo+vNsRqfXeK9hCm3RxU3bWRUuQj1U=
-----END CERTIFICATE-----
Loading