@@ -145,6 +145,7 @@ public static void main(String[] args) throws Exception {
145145
146146 // Create the corresponding JWT depending on the selected algorithm.
147147 String token ;
148+ DateTime iat = new DateTime ();
148149 if (options .algorithm .equals ("RS256" )) {
149150 token = createJwtRsa (options .projectId , options .privateKeyFile );
150151 } else if (options .algorithm .equals ("ES256" )) {
@@ -154,15 +155,28 @@ public static void main(String[] args) throws Exception {
154155 "Invalid algorithm " + options .algorithm + ". Should be one of 'RS256' or 'ES256'." );
155156 }
156157
158+ String urlPath = String .format ("%s/%s/" , options .httpBridgeAddress , options .apiVersion );
159+ System .out .format ("Using URL: '%s'\n " , urlPath );
160+
157161 // Publish numMessages messages to the HTTP bridge.
158162 for (int i = 1 ; i <= options .numMessages ; ++i ) {
159163 String payload = String .format ("%s/%s-payload-%d" , options .registryId , options .deviceId , i );
160164 System .out .format (
161165 "Publishing %s message %d/%d: '%s'\n " ,
162166 options .messageType , i , options .numMessages , payload );
163167
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+ }
166180
167181 publishMessage (payload , urlPath , options .messageType , token , options .projectId ,
168182 options .cloudRegion , options .registryId , options .deviceId );
0 commit comments