Example usage for org.springframework.vault.authentication LoginToken getLeaseDuration

List of usage examples for org.springframework.vault.authentication LoginToken getLeaseDuration

Introduction

In this page you can find the example usage for org.springframework.vault.authentication LoginToken getLeaseDuration.

Prototype

public Duration getLeaseDuration() 

Source Link

Usage

From source file:org.springframework.vault.authentication.LifecycleAwareSessionManager.java

private boolean isTokenRenewable() {

    if (token instanceof LoginToken) {

        LoginToken loginToken = (LoginToken) token;
        return loginToken.getLeaseDuration() > 0 && loginToken.isRenewable();
    }//from   w w w .  j  av a2 s. co m

    return false;
}

From source file:org.springframework.vault.authentication.LifecycleAwareSessionManager.java

private void scheduleRenewal() {

    logger.info("Scheduling Token renewal");

    LoginToken loginToken = (LoginToken) token;
    long tokenTtl = loginToken.getLeaseDuration();

    VaultResponseEntity<VaultResponse> entity = vaultClient.getForEntity("auth/token/lookup-self", token,
            VaultResponse.class);
    if (entity.isSuccessful() && entity.hasBody()) {
        Map<String, Object> data = entity.getBody().getData();
        tokenTtl = (Integer) data.get("ttl");
    }//ww w  .j  a  va2  s .c  om

    final int seconds = NumberUtils
            .convertNumberToTargetClass(Math.max(1, tokenTtl - REFRESH_PERIOD_BEFORE_EXPIRY), Integer.class);

    final Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                if (LifecycleAwareSessionManager.this.token != null && isTokenRenewable()) {
                    if (renewToken()) {
                        scheduleRenewal();
                    }
                }
            } catch (Exception e) {
                logger.error("Cannot renew VaultToken", e);
            }
        }
    };

    if (taskExecutor instanceof TaskScheduler) {
        scheduleTask((TaskScheduler) taskExecutor, seconds, task);
        return;
    }

    taskExecutor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                // TODO: Revisit this approach since it blocks a thread. Spinning up a
                // managed
                // TaskScheduler just for once-in-a-while token renewal seemed a bit
                // over-sophisticated
                // that's why we emulate a scheduler by blocking a Thread resource
                Thread.sleep(TimeUnit.SECONDS.toMillis(seconds));
                task.run();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    });
}