-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
15f5197
Final additions in private beta
gguuss 2f55341
Merge branch 'master' into iot-snippets
gguuss 2fdad02
Final updates in private beta
gguuss 2f5aafc
Adds tests, state support, and HTTP client
gguuss 7b23b34
Merge branch 'master' into iot-snippets
gguuss 376faff
Merge branch 'master' into iot-snippets
jabubake b2845e3
Feedback from review
gguuss e22a01c
Merge branch 'iot-snippets' of https://github.com/googlecloudplatform…
gguuss bd8c80b
Merge branch 'master' into iot-snippets
gguuss 8a0a005
Updates to snapshot version of sample library dependency
gguuss 99cc747
Merge branch 'iot-snippets' of https://github.com/googlecloudplatform…
gguuss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 \ | ||
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 | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. missing license header There was a problem hiding this comment. Choose a reason for hiding this commentThe 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> |
158 changes: 158 additions & 0 deletions
158
iot/api-client/http_example/src/main/java/com/google/cloud/iot/examples/HttpExample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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.