|
| 1 | +/** |
| 2 | + * Copyright 2017, Google, Inc. |
| 3 | + * |
| 4 | + * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file |
| 5 | + * except in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * <p>http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * <p>Unless required by applicable law or agreed to in writing, software distributed under the |
| 10 | + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 11 | + * express or implied. See the License for the specific language governing permissions and |
| 12 | + * limitations under the License. |
| 13 | + */ |
| 14 | + |
| 15 | +package com.google.cloud.iot.examples; |
| 16 | + |
| 17 | +import io.jsonwebtoken.JwtBuilder; |
| 18 | +import io.jsonwebtoken.Jwts; |
| 19 | +import io.jsonwebtoken.SignatureAlgorithm; |
| 20 | +import java.net.HttpURLConnection; |
| 21 | +import java.net.URL; |
| 22 | +import java.nio.file.Files; |
| 23 | +import java.nio.file.Paths; |
| 24 | +import java.security.KeyFactory; |
| 25 | +import java.security.spec.PKCS8EncodedKeySpec; |
| 26 | +import java.util.Base64; |
| 27 | +import org.joda.time.DateTime; |
| 28 | +import org.json.JSONObject; |
| 29 | + |
| 30 | +/** |
| 31 | + * Java sample of connecting to Google Cloud IoT Core vice via HTTP, using JWT. |
| 32 | + * |
| 33 | + * <p>This example connects to Google Cloud IoT Core via HTTP Bridge, using a JWT for device |
| 34 | + * authentication. After connecting, by default the device publishes 100 messages at a rate of one |
| 35 | + * per second, and then exits. You can change The behavior to set state instead of events by using |
| 36 | + * flag -message_type to 'state'. |
| 37 | + * |
| 38 | + * <p>To run this example, follow the instructions in the README located in the sample's parent |
| 39 | + * folder. |
| 40 | + */ |
| 41 | +public class HttpExample { |
| 42 | + /** Create a Cloud IoT Core JWT for the given project id, signed with the given private key. */ |
| 43 | + private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception { |
| 44 | + DateTime now = new DateTime(); |
| 45 | + // Create a JWT to authenticate this device. The device will be disconnected after the token |
| 46 | + // expires, and will have to reconnect with a new token. The audience field should always be set |
| 47 | + // to the GCP project id. |
| 48 | + JwtBuilder jwtBuilder = |
| 49 | + Jwts.builder() |
| 50 | + .setIssuedAt(now.toDate()) |
| 51 | + .setExpiration(now.plusMinutes(20).toDate()) |
| 52 | + .setAudience(projectId); |
| 53 | + |
| 54 | + byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); |
| 55 | + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); |
| 56 | + KeyFactory kf = KeyFactory.getInstance("RSA"); |
| 57 | + |
| 58 | + return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact(); |
| 59 | + } |
| 60 | + |
| 61 | + private static String createJwtEs(String projectId, String privateKeyFile) throws Exception { |
| 62 | + DateTime now = new DateTime(); |
| 63 | + // Create a JWT to authenticate this device. The device will be disconnected after the token |
| 64 | + // expires, and will have to reconnect with a new token. The audience field should always be set |
| 65 | + // to the GCP project id. |
| 66 | + JwtBuilder jwtBuilder = |
| 67 | + Jwts.builder() |
| 68 | + .setIssuedAt(now.toDate()) |
| 69 | + .setExpiration(now.plusMinutes(20).toDate()) |
| 70 | + .setAudience(projectId); |
| 71 | + |
| 72 | + byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); |
| 73 | + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); |
| 74 | + KeyFactory kf = KeyFactory.getInstance("ES256"); |
| 75 | + |
| 76 | + return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); |
| 77 | + } |
| 78 | + |
| 79 | + public static void main(String[] args) throws Exception { |
| 80 | + HttpExampleOptions options = HttpExampleOptions.fromFlags(args); |
| 81 | + if (options == null) { |
| 82 | + // Could not parse the flags. |
| 83 | + System.exit(1); |
| 84 | + } |
| 85 | + |
| 86 | + // Build the resource path of the device that is going to be authenticated. |
| 87 | + String devicePath = |
| 88 | + String.format( |
| 89 | + "projects/%s/locations/%s/registries/%s/devices/%s", |
| 90 | + options.projectId, options.cloudRegion, options.registryId, options.deviceId); |
| 91 | + |
| 92 | + // This describes the operation that is going to be perform with the device. |
| 93 | + String urlSuffix = options.messageType.equals("event") ? "publishEvent" : "setState"; |
| 94 | + |
| 95 | + String urlPath = |
| 96 | + String.format( |
| 97 | + "%s/%s/%s:%s", options.httpBridgeAddress, options.apiVersion, devicePath, urlSuffix); |
| 98 | + URL url = new URL(urlPath); |
| 99 | + System.out.format("Using URL: '%s'\n", urlPath); |
| 100 | + |
| 101 | + // Create the corresponding JWT depending on the selected algorithm. |
| 102 | + String token; |
| 103 | + if (options.algorithm.equals("RS256")) { |
| 104 | + token = createJwtRsa(options.projectId, options.privateKeyFile); |
| 105 | + } else if (options.algorithm.equals("ES256")) { |
| 106 | + token = createJwtEs(options.projectId, options.privateKeyFile); |
| 107 | + } else { |
| 108 | + throw new IllegalArgumentException( |
| 109 | + "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'."); |
| 110 | + } |
| 111 | + |
| 112 | + // Data sent through the wire has to be base64 encoded. |
| 113 | + Base64.Encoder encoder = Base64.getEncoder(); |
| 114 | + |
| 115 | + // Publish numMessages messages to the HTTP bridge. |
| 116 | + for (int i = 1; i <= options.numMessages; ++i) { |
| 117 | + String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i); |
| 118 | + System.out.format( |
| 119 | + "Publishing %s message %d/%d: '%s'\n", |
| 120 | + options.messageType, i, options.numMessages, payload); |
| 121 | + String encPayload = encoder.encodeToString(payload.getBytes("UTF-8")); |
| 122 | + |
| 123 | + HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); |
| 124 | + httpCon.setDoOutput(true); |
| 125 | + httpCon.setRequestMethod("POST"); |
| 126 | + |
| 127 | + // Adding headers. |
| 128 | + httpCon.setRequestProperty("Authorization", String.format("Bearer %s", token)); |
| 129 | + httpCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); |
| 130 | + |
| 131 | + // Adding the post data. The structure of the data send depends on whether it is event or a |
| 132 | + // state message. |
| 133 | + JSONObject data = new JSONObject(); |
| 134 | + if (options.messageType.equals("event")) { |
| 135 | + data.put("binary_data", encPayload); |
| 136 | + } else { |
| 137 | + JSONObject state = new JSONObject(); |
| 138 | + state.put("binary_data", encPayload); |
| 139 | + data.put("state", state); |
| 140 | + } |
| 141 | + httpCon.getOutputStream().write(data.toString().getBytes("UTF-8")); |
| 142 | + httpCon.getOutputStream().close(); |
| 143 | + |
| 144 | + // This will perform the connection as well. |
| 145 | + System.out.println(httpCon.getResponseCode()); |
| 146 | + System.out.println(httpCon.getResponseMessage()); |
| 147 | + |
| 148 | + if (options.messageType.equals("event")) { |
| 149 | + // Frequently send event payloads (every second) |
| 150 | + Thread.sleep(1000); |
| 151 | + } else { |
| 152 | + // Update state with low frequency (once every 5 seconds) |
| 153 | + Thread.sleep(5000); |
| 154 | + } |
| 155 | + } |
| 156 | + System.out.println("Finished loop successfully. Goodbye!"); |
| 157 | + } |
| 158 | +} |
0 commit comments