All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bimface.sdk.config.authorization.DefaultAccessTokenStorage Maven / Gradle / Ivy

The newest version!
package com.bimface.sdk.config.authorization;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.bimface.sdk.bean.response.AccessTokenBean;

/**
 * 默认情况下,缓存AccessToken的方式
 * 
 * @author bimface, 2016-06-01.
 */
public class DefaultAccessTokenStorage implements AccessTokenStorage {

    private AccessTokenBean accessTokenBean;

    private long lastRefreshTimeMi;

    private int tokenTimeout;

    private static final long MONTH_TO_MILLIS = 30L * 24 * 60 * 60 * 1000;


    public synchronized void put(AccessTokenBean accessTokenBean) {
        this.accessTokenBean = accessTokenBean;
    }

    public AccessTokenBean get() {
        if (accessTokenBean == null) {
            return null;
        }
        if (maybeExpire(accessTokenBean.getExpireTime())) {
            return null;
        }
        return accessTokenBean;
    }

    @Override
    public void setTokenTimeout(int tokenTimeout) {
        this.tokenTimeout = tokenTimeout;
    }

    /**
     * 判断是否过期或即将过期
     *
     * @param expireTime 过期时间
     * @return true:已过期或即将过期, false:未过期
     */
    private boolean maybeExpire(String expireTime) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date expire = dateFormat.parse(accessTokenBean.getExpireTime());
            // 最后一次刷新时间是否在过去设置的时间有效期以内 && token的有效期 > 1秒
            if (System.currentTimeMillis() - lastRefreshTimeMi < tokenTimeout && expire.getTime() - System.currentTimeMillis() >= 1000) {
                return false;
            }
            // token 的有效期是否小于30天(其实此次应该设定为一个比较大的值好一些),若小于其他则认为已经过期,在accessTokenService中会重新触发获取token的操作
            boolean expired = (expire.getTime() - System.currentTimeMillis() - MONTH_TO_MILLIS) <= 1000; // 时间需要大于1秒
            if (expired) {
                // 记录最近一次token过期的时间
                lastRefreshTimeMi = System.currentTimeMillis();
            }
            return expired;
        } catch (ParseException e) {
            return true;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy