Skip to content

Final additions in private beta #861

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

Merged
merged 11 commits into from
Sep 26, 2017
Merged
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
```
62 changes: 62 additions & 0 deletions iot/api-client/http_example/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<!--
Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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,158 @@
/**
* Copyright 2017, Google, Inc.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/

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());

if (options.messageType.equals("event")) {
// Frequently send event payloads (every second)
Thread.sleep(1000);
} else {
// Update state with low frequency (once every 5 seconds)
Thread.sleep(5000);
}
}
System.out.println("Finished loop successfully. Goodbye!");
}
}
Loading