1414
1515package com .google .cloud .iot .examples ;
1616
17+ // [START cloudiotcore_mqtt_imports]
1718import io .jsonwebtoken .JwtBuilder ;
1819import io .jsonwebtoken .Jwts ;
1920import io .jsonwebtoken .SignatureAlgorithm ;
2627import org .eclipse .paho .client .mqttv3 .MqttMessage ;
2728import org .eclipse .paho .client .mqttv3 .persist .MemoryPersistence ;
2829import org .joda .time .DateTime ;
30+ // [END cloudiotcore_mqtt_imports]
2931
3032/**
3133 * Java sample of connecting to Google Cloud IoT Core vice via MQTT, using JWT.
5254 * </pre>
5355 */
5456public class MqttExample {
55- /** Create a Cloud IoT Core JWT for the given project id, signed with the given private key. */
57+ // [START cloudiotcore_mqtt_createjwt]
58+ /** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
5659 private static String createJwtRsa (String projectId , String privateKeyFile ) throws Exception {
5760 DateTime now = new DateTime ();
5861 // Create a JWT to authenticate this device. The device will be disconnected after the token
@@ -71,6 +74,7 @@ private static String createJwtRsa(String projectId, String privateKeyFile) thro
7174 return jwtBuilder .signWith (SignatureAlgorithm .RS256 , kf .generatePrivate (spec )).compact ();
7275 }
7376
77+ /** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */
7478 private static String createJwtEs (String projectId , String privateKeyFile ) throws Exception {
7579 DateTime now = new DateTime ();
7680 // Create a JWT to authenticate this device. The device will be disconnected after the token
@@ -88,8 +92,11 @@ private static String createJwtEs(String projectId, String privateKeyFile) throw
8892
8993 return jwtBuilder .signWith (SignatureAlgorithm .ES256 , kf .generatePrivate (spec )).compact ();
9094 }
95+ // [END cloudiotcore_mqtt_createjwt]
9196
97+ /** Parse arguments, configure MQTT, and publish messages. */
9298 public static void main (String [] args ) throws Exception {
99+ // [START cloudiotcore_mqtt_configuremqtt]
93100 MqttExampleOptions options = MqttExampleOptions .fromFlags (args );
94101 if (options == null ) {
95102 // Could not parse.
@@ -131,7 +138,9 @@ public static void main(String[] args) throws Exception {
131138 throw new IllegalArgumentException (
132139 "Invalid algorithm " + options .algorithm + ". Should be one of 'RS256' or 'ES256'." );
133140 }
141+ // [END cloudiotcore_mqtt_configuremqtt]
134142
143+ // [START cloudiotcore_mqtt_publish]
135144 // Create a client, and connect to the Google MQTT bridge.
136145 MqttClient client = new MqttClient (mqttServerAddress , mqttClientId , new MemoryPersistence ());
137146 try {
@@ -171,5 +180,6 @@ public static void main(String[] args) throws Exception {
171180 client .disconnect ();
172181 }
173182 System .out .println ("Finished loop successfully. Goodbye!" );
183+ // [END cloudiotcore_mqtt_publish]
174184 }
175185}
0 commit comments