@@ -145,6 +145,7 @@ public static void main(String[] args) throws Exception {
145
145
146
146
// Create the corresponding JWT depending on the selected algorithm.
147
147
String token ;
148
+ DateTime iat = new DateTime ();
148
149
if (options .algorithm .equals ("RS256" )) {
149
150
token = createJwtRsa (options .projectId , options .privateKeyFile );
150
151
} else if (options .algorithm .equals ("ES256" )) {
@@ -154,15 +155,28 @@ public static void main(String[] args) throws Exception {
154
155
"Invalid algorithm " + options .algorithm + ". Should be one of 'RS256' or 'ES256'." );
155
156
}
156
157
158
+ String urlPath = String .format ("%s/%s/" , options .httpBridgeAddress , options .apiVersion );
159
+ System .out .format ("Using URL: '%s'\n " , urlPath );
160
+
157
161
// Publish numMessages messages to the HTTP bridge.
158
162
for (int i = 1 ; i <= options .numMessages ; ++i ) {
159
163
String payload = String .format ("%s/%s-payload-%d" , options .registryId , options .deviceId , i );
160
164
System .out .format (
161
165
"Publishing %s message %d/%d: '%s'\n " ,
162
166
options .messageType , i , options .numMessages , payload );
163
167
164
- String urlPath = String .format ("%s/%s/" , options .httpBridgeAddress , options .apiVersion );
165
- System .out .format ("Using URL: '%s'\n " , urlPath );
168
+ // Refresh the authentication token if the token has expired.
169
+ long secsSinceRefresh = ((new DateTime ()).getMillis () - iat .getMillis ()) / 1000 ;
170
+ if (secsSinceRefresh > (options .tokenExpMins * 60 )) {
171
+ System .out .format ("\t Refreshing token after: %d seconds\n " , secsSinceRefresh );
172
+ iat = new DateTime ();
173
+
174
+ if (options .algorithm .equals ("RS256" )) {
175
+ token = createJwtRsa (options .projectId , options .privateKeyFile );
176
+ } else if (options .algorithm .equals ("ES256" )) {
177
+ token = createJwtEs (options .projectId , options .privateKeyFile );
178
+ }
179
+ }
166
180
167
181
publishMessage (payload , urlPath , options .messageType , token , options .projectId ,
168
182
options .cloudRegion , options .registryId , options .deviceId );
0 commit comments