Returns {@code true} if the credential can and should be refreshed.
175349
@VisibleForTesting
  boolean isCredentialRefreshable(Credential credential) {
    return credential.getAccessToken() == null || credential.getExpiresInSeconds() != null
        && credential.getExpiresInSeconds() <= refreshWindowSeconds;
  }
1372678
private function isRefreshNeededByProbability()
    {
        if (is_null($this->refreshProbability)) {
            return false;
        }
        $rand = (float) mt_rand() / (float) mt_getrandmax();
        if ($this->refreshProbability == 1.0 || $rand <= $this->refreshProbability) {
            return true;
        }
        return false; // @codeCoverageIgnore
    }
182752
def refresh_oauth_credential(self):
        """"""
        if self.session.token_type == auth.SERVER_TOKEN_TYPE:
            return

        credential = self.session.oauth2credential
        if credential.is_stale():
            refresh_session = refresh_access_token(credential)
            self.session = refresh_session
407779
public boolean hasValidCredentials() {
        String accessToken = storage.retrieveString(KEY_ACCESS_TOKEN);
        String refreshToken = storage.retrieveString(KEY_REFRESH_TOKEN);
        String idToken = storage.retrieveString(KEY_ID_TOKEN);
        Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT);

        return !(isEmpty(accessToken) && isEmpty(idToken) ||
                expiresAt == null ||
                expiresAt <= getCurrentTimeInMillis() && refreshToken == null);
    }
168358
public boolean isEligibleForContextRefresh() {
        if (this.override) {
            return true;
        }
        if (getFile() != null) {
            return CONFIG_FILE_PATTERN.matcher(getFile().toFile().getName()).find();
        }
        return false;
    }
665279
public Credential setRefreshToken(String refreshToken) {
    lock.lock();
    try {
      if (refreshToken != null) {
        Preconditions.checkArgument(jsonFactory != null && transport != null
            && clientAuthentication != null && tokenServerEncodedUrl != null,
            "Please use the Builder and call setJsonFactory, setTransport, setClientAuthentication"
            + " and setTokenServerUrl/setTokenServerEncodedUrl");
      }
      this.refreshToken = refreshToken;
    } finally {
      lock.unlock();
    }
    return this;
  }
450393
public boolean isFresh(final String filename) {
        final FileSystem fileSystem = vertx.fileSystem();

        try {
            FileProps fileProps = fileSystem.propsBlocking(filename);
            LRUCache.CacheEntry<String, T> cacheEntry = cache.get(filename);
            final long lastModified = fileProps.lastModifiedTime();

            if (cacheEntry == null) {
                return false;
            }
            if (cacheEntry.isFresh(lastModified)) {
                return true;
            }
            // not fresh anymore, purge it
            cache.remove(filename);
            return false;
        } catch (RuntimeException e) {
            return false;
        }
    }
1220097
def request(self, uri, method='GET', body=None, headers=None,
                **kwargs):
        """"""

        _credential_refresh_attempt = kwargs.pop(
            '_credential_refresh_attempt', 0)

        # Make a copy of the headers. They will be modified by the credentials
        # and we want to pass the original headers if we recurse.
        request_headers = headers.copy() if headers is not None else {}

        self.credentials.before_request(
            self._request, method, uri, request_headers)

        # Check if the body is a file-like stream, and if so, save the body
        # stream position so that it can be restored in case of refresh.
        body_stream_position = None
        if all(getattr(body, stream_prop, None) for stream_prop in
               _STREAM_PROPERTIES):
            body_stream_position = body.tell()

        # Make the request.
        response, content = self.http.request(
            uri, method, body=body, headers=request_headers, **kwargs)

        # If the response indicated that the credentials needed to be
        # refreshed, then refresh the credentials and re-attempt the
        # request.
        # A stored token may expire between the time it is retrieved and
        # the time the request is made, so we may need to try twice.
        if (response.status in self._refresh_status_codes
                and _credential_refresh_attempt < self._max_refresh_attempts):

            _LOGGER.info(
                'Refreshing credentials due to a %s response. Attempt %s/%s.',
                response.status, _credential_refresh_attempt + 1,
                self._max_refresh_attempts)

            self.credentials.refresh(self._request)

            # Restore the body's stream position if needed.
            if body_stream_position is not None:
                body.seek(body_stream_position)

            # Recurse. Pass in the original headers, not our modified set.
            return self.request(
                uri, method, body=body, headers=headers,
                _credential_refresh_attempt=_credential_refresh_attempt + 1,
                **kwargs)

        return response, content
1043191
private HeaderCacheElement syncRefresh(long timeout, TimeUnit timeUnit) {
    Span span = TRACER.spanBuilder("Bigtable.CredentialsRefresh").startSpan();
    try (Scope scope = TRACER.withSpan(span)) {
      return asyncRefresh().get(timeout, timeUnit);
    } catch (InterruptedException e) {
      LOG.warn("Interrupted while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("Authentication was interrupted.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      Thread.currentThread().interrupt();
      return new HeaderCacheElement(status);
    } catch (ExecutionException e) {
      LOG.warn("ExecutionException while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("ExecutionException during Authentication.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      return new HeaderCacheElement(status);
    } catch (TimeoutException e) {
      LOG.warn("TimeoutException while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("TimeoutException during Authentication.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      return new HeaderCacheElement(status);
    } catch (Exception e) {
      LOG.warn("Unexpected execption while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("Unexpected execption during Authentication.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      return new HeaderCacheElement(status);
    } finally {
      span.end();
    }
  }
192134
public boolean check(Object credentials)
    {
	if (this == credentials)
	    return true;
	
        if (credentials instanceof Password)
            return credentials.equals(_pw);
        
        if (credentials instanceof String)
            return credentials.equals(_pw);
        
        if (credentials instanceof Credential)
            return ((Credential)credentials).check(_pw);
            
        return false;
    }
1043007
@Override
  public boolean canAuthenticate(String resource) {
    if (resource == null) {
      return false;
    }

    ClientCredential credential = getCredentialForResource(resource);
    return credential != null;
  }
675594
@Override
    public CompletableFuture<Void> refreshAsync(String key, int expireSeconds) {
        return setExpireSecondsAsync(key, expireSeconds);
    }
945461
private static boolean ifExistsAndFresh(Configuration conf, FileSystem fs,
                                          URI cache, long confFileStamp,
                                          CacheStatus lcacheStatus,
                                          FileStatus fileStatus)
  throws IOException {
    // check for existence of the cache
    long dfsFileStamp;
    if (fileStatus != null) {
      dfsFileStamp = fileStatus.getModificationTime();
    } else {
      dfsFileStamp = getTimestamp(conf, cache);
    }

    // ensure that the file on hdfs hasn't been modified since the job started
    if (dfsFileStamp != confFileStamp) {
      LOG.fatal("File: " + cache + " has changed on HDFS since job started");
      throw new IOException("File: " + cache +
          " has changed on HDFS since job started");
    }

    if (dfsFileStamp != lcacheStatus.mtime) {
      // needs refreshing
      return false;
    }

    return true;
  }
820750
protected boolean needsToLoadCredentials() {
        if (credentials == null) return true;

        if (credentialsExpiration != null) {
            if (isWithinExpirationThreshold()) return true;
        }

        if (lastInstanceProfileCheck != null) {
            if (isPastRefreshThreshold()) return true;
        }

        return false;
    }
577592
public boolean refreshSession (String sessionKey, int expireDays)
        throws PersistenceException
    {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, expireDays);
        Date expires = new Date(cal.getTime().getTime());

        // attempt to update an existing session row, returning true if we found and updated it
        return (update("update sessions set expires = '" + expires + "' " +
                       "where authcode = " + JDBCUtil.escape(sessionKey)) == 1);
    }
29861
private Credential newCredential(String userId) {
        Credential.Builder builder = new Credential.Builder(getMethod())
                .setTransport(getTransport())
                .setJsonFactory(getJsonFactory())
                .setTokenServerEncodedUrl(getTokenServerEncodedUrl())
                .setClientAuthentication(getClientAuthentication())
                .setRequestInitializer(getRequestInitializer())
                .setClock(getClock());
        if (getCredentialStore() != null) {
            builder.addRefreshListener(
                    new CredentialStoreRefreshListener(userId, getCredentialStore()));
        }

        builder.getRefreshListeners().addAll(getRefreshListeners());

        return builder.build();
    }
801024
@Api
	public void refresh() {
		if (state == State.INITIALIZED) { // to prevent refresh before the map is drawn
			state = State.REFRESHING;
			clear();
			ClientConfigurationService.clear(); // refresh because configuration changed, clear cache
			refreshFromConfiguration();
		}
	}