[]todo - handle token expiration more gracefully  - eg handle renewing
964859
def setup_security_token(security_url)
      reset_cookies
      begin
        json_response = send_request(security_url, { :method => :get })
        @security_token = json_response[json_response.keys[0]]["SecurityToken"]
      rescue StandardError => ex
        raise unless (ex.message.include?("HTTP-404") || ex.message.include?("HTTP-500")) #for on-prem not on wsapi 2.x
      end
      true
    end
837066
private void handleToken(String token) throws ParseException
    {
        currentToken = token;

        if (skipParsing)
        {
            cmd.addArg(token);
        }
        else if ("--".equals(token))
        {
            skipParsing = true;
        }
        else if (currentOption != null && currentOption.acceptsArg() && isArgument(token))
        {
            currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token));
        }
        else if (token.startsWith("--"))
        {
            handleLongOption(token);
        }
        else if (token.startsWith("-") && !"-".equals(token))
        {
            handleShortAndLongOption(token);
        }
        else
        {
            handleUnknownToken(token);
        }

        if (currentOption != null && !currentOption.acceptsArg())
        {
            currentOption = null;
        }
    }
1371077
public static <T> Expiring<T> of(T... elements) {
		return of(Arrays.asList(checkNotNull(elements)));
	}
452005
void expireAfterWrite(String key, @Nullable String value) {
    requireArgument(expireAfterWriteDuration == UNSET_INT, "expireAfterWrite was already set");
    expireAfterWriteDuration = parseDuration(key, value);
    expireAfterWriteTimeUnit = parseTimeUnit(key, value);
  }
102146
@Override
    public String getToken() throws TokenManagerException {
        if (hasTokenExpired()) {
            synchronized (this) {
                if (hasTokenExpired()) {
                    try {
                        final IAMToken iamToken = invokeTokenApi();
                        expiresAt = (long) (TimeUnit.SECONDS.toNanos(
                                iamToken.expires_in) * tokenExpiryThreshold)
                                + System.nanoTime();
                        token = iamToken.access_token;
                    } catch (final IAMTokenException e) {
                        throw new TokenManagerException("Failed getting Token.",
                                e);
                    }

                }
            }
        }
        return token;
    }
1143453
function timerExpired() {
    let time = new Date()
      .getTime();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    // 重启定时器
    timerId = setTimeout(timerExpired, remainingWait(time));
  }
39368
def handle_generic(tokens, options)
      t = Chronic.time_class.parse(options[:text])
      Span.new(t, t + 1)
    end
258418
private void expireSession(long index, long timestamp, ServerSessionContext session, CompletableFuture<Void> future, ThreadContext context) {
    if (!log.isOpen()) {
      context.executor().execute(() -> future.completeExceptionally(new IllegalStateException("log closed")));
      return;
    }

    // If the session is already in an inactive state, complete the future exceptionally.
    if (!session.state().active()) {
      context.executor().execute(() -> future.completeExceptionally(new UnknownSessionException("inactive session: " + session.id())));
      return;
    }

    // Trigger scheduled callbacks in the state machine.
    executor.tick(index, timestamp);

    // Update the state machine context with the unregister entry's index. This ensures that events published
    // within the expire or close methods will be properly associated with the unregister entry's index.
    // All events published during expiration or closing of a session are linearizable to ensure that clients
    // receive related events before the expiration is completed.
    executor.init(index, Instant.ofEpochMilli(timestamp), ServerStateMachineContext.Type.COMMAND);

    // Expire the session and call state machine callbacks.
    session.expire(index);
    for (SessionListener listener : executor.context().sessions().listeners) {
      listener.expire(session);
      listener.close(session);
    }

    // Calculate the last completed index.
    long lastCompleted = calculateLastCompleted(index);

    // Once expiration callbacks have been completed, ensure that events published during the callbacks
    // are published in batch. The state machine context will generate an event future for all published events
    // to all sessions. If the event future is non-null, that indicates events are pending which were published
    // during the call to expire(). Wait for the events to be received by the client before completing the future.
    executor.commit();
    context.executor().execute(() -> {
      setLastCompleted(lastCompleted);
      future.complete(null);
    });
  }
1166726
synchronized long tryReserveTokens(long tokens, long maxWaitMillis) {
    long now = System.currentTimeMillis();
    long waitUntilNextTokenAvailable = Math.max(0, this.nextTokenAvailableMillis - now);

    updateTokensStored(now);
    if (tokens <= this.tokensStored) {
      this.tokensStored -= tokens;
      return waitUntilNextTokenAvailable;
    }

    double additionalNeededTokens = tokens - this.tokensStored;
    // casting to long will round towards 0
    long additionalWaitForEnoughTokens = (long) (additionalNeededTokens / this.tokensPerMilli) + 1;
    long totalWait = waitUntilNextTokenAvailable + additionalWaitForEnoughTokens;
    if (totalWait > maxWaitMillis) {
      return -1;
    }
    this.tokensStored = this.tokensPerMilli * additionalWaitForEnoughTokens - additionalNeededTokens;
    this.nextTokenAvailableMillis = this.nextTokenAvailableMillis + additionalWaitForEnoughTokens;
    return totalWait;
  }
975006
public int getRealExpire(int expire, String expireExpression, Object[] arguments, Object result) throws Exception {
        Integer tmpExpire = null;
        if (null != expireExpression && expireExpression.length() > 0) {
            tmpExpire = this.getElValue(expireExpression, null, arguments, result, true, Integer.class);
            if (null != tmpExpire && tmpExpire.intValue() >= 0) {
                // 返回缓存时间表达式计算的时间
                return tmpExpire.intValue();
            }
        }
        return expire;
    }
1168795
def expires_on(self):
    """"""
    timestamp = self._info.get('expirationTime', None)
    if timestamp is None:
      return None
    return _parser.Parser.parse_timestamp(timestamp)
544676
function (token, match, lastState) {
    var self = this;

    match = match.split('.');

    if (_reserved.indexOf(match[0]) !== -1) {
      utils.throwError('Reserved keyword "' + match[0] + '" attempted to be used as a variable', self.line, self.filename);
    }

    self.filterApplyIdx.push(self.out.length);
    if (lastState === _t.CURLYOPEN) {
      if (match.length > 1) {
        utils.throwError('Unexpected dot', self.line, self.filename);
      }
      self.out.push(match[0]);
      return;
    }

    self.out.push(self.checkMatch(match));
  }
688159
function(req, res, user) {
    var jsonWebTokens = waterlock.config.jsonWebTokens || {};
    var expiryUnit = (jsonWebTokens.expiry && jsonWebTokens.expiry.unit) || 'days';
    var expiryLength = (jsonWebTokens.expiry && jsonWebTokens.expiry.length) || 7;
    var expires = moment().add(expiryLength, expiryUnit).valueOf();
    var issued = Date.now();
    user = user || req.session.user;

    var token = jwt.encode({
      iss: user.id + '|' + req.remoteAddress,
      sub: jsonWebTokens.subject,
      aud: jsonWebTokens.audience,
      exp: expires,
      nbf: issued,
      iat: issued,
      jti: uuid.v1()
    }, jsonWebTokens.secret);

    return {
      token: token,
      expires: expires
    };
  }
353856
private String getTokenOrBlank(final List<String> tokens, final int reverseIndex) {

		final int length = tokens.size();
		final int index  = length - reverseIndex - 1;

		if (index >= 0 && length > 0 && index < length) {
			return tokens.get(index);
		}

		return "";
	}
774346
public int getExpiresIn(String tokenGrantType, String scope) {
        int expiresIn = Integer.MAX_VALUE;
        List<Scope> scopes = loadScopes(scope);
        boolean ccGrantType = TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType);
        if (TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getCcExpiresIn() < expiresIn) {
                    expiresIn = s.getCcExpiresIn();
                }
            }
        } else if (TokenRequest.PASSWORD.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getPassExpiresIn() < expiresIn) {
                    expiresIn = s.getPassExpiresIn();
                }
            }
        } else {
            // refresh_token
            for (Scope s : scopes) {
                if (s.getRefreshExpiresIn() < expiresIn) {
                    expiresIn = s.getRefreshExpiresIn();
                }
            }
        }
        if (scopes.size() == 0 || expiresIn == Integer.MAX_VALUE) {
            expiresIn = (ccGrantType) ? OAuthConfig.DEFAULT_CC_EXPIRES_IN : OAuthConfig.DEFAULT_PASSWORD_EXPIRES_IN;
        }
        return expiresIn;
    }
1256907
function processToken(token, done) {
    var user = _.find(users, function (item) {
        return item.username === token[claims.username];
    });
    if (!user) {
        user = {
            id          : token[claims.id] || currId++,
            username    : token[claims.username],
            email       : token[claims.email],
            firstName   : token[claims.firstName],
            lastName    : token[claims.lastName]
        };
        var roles = token[claims.role];
        if (!roles) {
            roles = ["guest"];
        } else if (!(roles instanceof Array)) {
            roles = [roles];
        }
        user.roles = roles;
        users.push(user);
    }
    done(null, user);
}
1153072
public static <T> Expiring<T> of(Iterator<T> iterator) {
		return of(Lists.newArrayList(checkNotNull(iterator)));
	}