|
22 | 22 | import com.google.api.gax.rpc.TransportChannelProvider; |
23 | 23 | import com.google.auth.Credentials; |
24 | 24 | import com.google.auth.oauth2.GoogleCredentials; |
| 25 | +import com.google.auth.oauth2.OAuth2Credentials; |
25 | 26 | import com.google.auth.oauth2.ServiceAccountCredentials; |
26 | 27 | import com.google.auth.oauth2.UserCredentials; |
27 | 28 | import com.google.auto.value.AutoValue; |
@@ -548,6 +549,10 @@ public GoogleAdsClient build() { |
548 | 549 | // action is needed. |
549 | 550 | } |
550 | 551 |
|
| 552 | + // Refreshes the OAuth credentials if necessary. This also ensures that the credentials are |
| 553 | + // valid, avoiding https://github.com/googleads/google-ads-java/issues/169 |
| 554 | + refreshCredentialsIfNecessary(); |
| 555 | + |
551 | 556 | // Provides the credentials to the primer to preemptively get these ready for usage. |
552 | 557 | Primer.getInstance().ifPresent(p -> p.primeCredentialsAsync(getCredentials())); |
553 | 558 | // Proceeds with creating the client library instance. |
@@ -576,6 +581,19 @@ public GoogleAdsClient build() { |
576 | 581 | return provider; |
577 | 582 | } |
578 | 583 |
|
| 584 | + /** Attempts to refresh the OAuth credentials if necessary. */ |
| 585 | + private void refreshCredentialsIfNecessary() { |
| 586 | + Credentials credentials = getCredentials(); |
| 587 | + if (credentials instanceof OAuth2Credentials) { |
| 588 | + OAuth2Credentials oAuth2Credentials = (OAuth2Credentials) credentials; |
| 589 | + try { |
| 590 | + oAuth2Credentials.refreshIfExpired(); |
| 591 | + } catch (IOException e) { |
| 592 | + throw new OAuthException(e); |
| 593 | + } |
| 594 | + } |
| 595 | + } |
| 596 | + |
579 | 597 | @VisibleForTesting |
580 | 598 | Builder setConfigurationFileSupplier(Supplier<File> configurationFileSupplier) { |
581 | 599 | this.configurationFileSupplier = configurationFileSupplier; |
|
0 commit comments