@@ -127,7 +127,7 @@ public static void main(String[] args) throws Exception {
127
127
// to authorize the device.
128
128
connectOptions .setUserName ("unused" );
129
129
130
- System . out . println ( options . algorithm );
130
+ DateTime iat = new DateTime ( );
131
131
if (options .algorithm .equals ("RS256" )) {
132
132
connectOptions .setPassword (
133
133
createJwtRsa (options .projectId , options .privateKeyFile ).toCharArray ());
@@ -161,6 +161,24 @@ public static void main(String[] args) throws Exception {
161
161
"Publishing %s message %d/%d: '%s'\n " ,
162
162
options .messageType , i , options .numMessages , payload );
163
163
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
+
164
182
// Publish "payload" to the MQTT topic. qos=1 means at least once delivery. Cloud IoT Core
165
183
// also supports qos=0 for at most once delivery.
166
184
MqttMessage message = new MqttMessage (payload .getBytes ());
0 commit comments