@@ -127,7 +127,7 @@ public static void main(String[] args) throws Exception {
127127 // to authorize the device.
128128 connectOptions .setUserName ("unused" );
129129
130- System . out . println ( options . algorithm );
130+ DateTime iat = new DateTime ( );
131131 if (options .algorithm .equals ("RS256" )) {
132132 connectOptions .setPassword (
133133 createJwtRsa (options .projectId , options .privateKeyFile ).toCharArray ());
@@ -161,6 +161,24 @@ public static void main(String[] args) throws Exception {
161161 "Publishing %s message %d/%d: '%s'\n " ,
162162 options .messageType , i , options .numMessages , payload );
163163
164+ // Refresh the connection credentials before the JWT expires.
165+ long secsSinceRefresh = ((new DateTime ()).getMillis () - iat .getMillis ()) / 1000 ;
166+ if (secsSinceRefresh > (options .tokenExpMins * 60 )) {
167+ System .out .format ("\t Refreshing token after: %d seconds\n " , secsSinceRefresh );
168+ iat = new DateTime ();
169+ if (options .algorithm .equals ("RS256" )) {
170+ connectOptions .setPassword (
171+ createJwtRsa (options .projectId , options .privateKeyFile ).toCharArray ());
172+ } else if (options .algorithm .equals ("ES256" )) {
173+ connectOptions .setPassword (
174+ createJwtEs (options .projectId , options .privateKeyFile ).toCharArray ());
175+ } else {
176+ throw new IllegalArgumentException (
177+ "Invalid algorithm " + options .algorithm
178+ + ". Should be one of 'RS256' or 'ES256'." );
179+ }
180+ }
181+
164182 // Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
165183 // also supports qos=0 for at most once delivery.
166184 MqttMessage message = new MqttMessage (payload .getBytes ());
0 commit comments