Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2009 eXo Platform SAS. This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF site:
 import java.util.List;
 import  org.picocontainer.Startable;

Created by The eXo Platform SAS Author : liem.nguyen Jun 5, 2009 todo julien : - make delay configuration from init param and

<T> the token type
<K> the token key type
setter - start/stop expiration daemon - manually invoke the daemon via @Managed
 @ManagedDescription("Token Store Service")
 @NameTemplate({ @Property(key = "service", value = "TokenStore"), @Property(key = "name", value = "{Name}") })
 public abstract class AbstractTokenService<T extends Token, K> implements Startable, TokenStore {
     protected final Logger log = LoggerFactory.getLogger(getClass());
     protected static final String SERVICE_CONFIG = "service.configuration";
     protected static final String CLEANUP_PERIOD_TIME = "cleanup.period.time";

See tokenByteLength. 8 bytes (64 bits) would be enough, but we want to get padding-less Byte64 representation, so we take the next greater number divisible by 3 which is 9. 9 bytes is equal to 72 bits.
     public static final int DEFAULT_TOKEN_BYTE_LENGTH = 9;

The number of random bits generared by nextRandom(). Use values divisible by 3 to produce random strings consisting only of 0-9, a-z, A-Z, - and _, i.e. URL safe Byte64 without padding. If a value not divisible by 3 is used the random strings will contain * in addition to the named characters.
     protected final int tokenByteLength;
     protected String name;
     protected long validityMillis;
     protected int delay_time = 600;
     public AbstractTokenService(InitParams initParamsthrows TokenServiceInitializationException {
         List<Stringparams = initParams.getValuesParam().getValues();
         this. = params.get(0);
         long configValue = new Long(params.get(1));
         this. = TimeoutEnum.valueOf(params.get(2)).toMilisecond(configValue);
         this. = ;
         ValueParam delayParam = initParams.getValueParam();
         if(delayParam != null) {
              = Integer.parseInt(delayParam.getValue());
    public void start() {
        if( > 0) {
         // start a thread, garbage expired cookie token every [DELAY_TIME]
             = Executors.newSingleThreadScheduledExecutor();
            .scheduleWithFixedDelay(new Runnable() {
                public void run() {
                    try {
                    } catch (Throwable t) {
                        .warn("Failed to clean expired tokens"t);
            }, 0, .);
    public void stop() {
        if( != null) {
    public static <T extends AbstractTokenService<?, ?>> T getInstance(Class<T> classType) {
        PortalContainer container = PortalContainer.getInstance();
        return classType.cast(container.getComponentInstanceOfType(classType));
    public Credentials validateToken(String stringKeyboolean remove) {
        if (stringKey == null) {
            throw new NullPointerException();
        K tokenKey = decodeKey(stringKey);
        T token;
        try {
            if (remove) {
                token = this.deleteToken(tokenKey);
            } else {
                token = this.getToken(tokenKey);
            if (token != null) {
                boolean valid = token.getExpirationTimeMillis() > System.currentTimeMillis();
                if (valid) {
                    return token.getPayload();
                } else if (!remove) {
        } catch (Exception e) {
        return null;
    @ManagedDescription("Clean all tokens are expired")
    public abstract void cleanExpiredTokens();
    @ManagedDescription("Get time for token expiration in seconds")
    public long getValidityTime() {
        return  / 1000;
    @ManagedDescription("The expiration daemon period time in seconds")
    public long getPeriodTime() {
        return ;
    @ManagedDescription("The token service name")
    public String getName() {
        return ;
    public abstract T getToken(K id);
    public abstract T deleteToken(K id);

Decode a key from its string representation.

stringKey the key a s a string
the typed key
    protected abstract K decodeKey(String stringKey);
    // We don't make it a property as retrieving the value can be an expensive operation
    @ManagedDescription("The number of tokens")
    public abstract long size();
    private enum TimeoutEnum {
        SECOND(1000), MINUTE(1000 * 60), HOUR(1000 * 60 * 60), DAY(1000 * 60 * 60 * 24);
        private long multiply;
        private TimeoutEnum(long multiply) {
            this. = multiply;
        public long toMilisecond(long configValue) {
            return configValue * ;
    protected String nextTokenId() {
        return . + nextRandom();
    protected String nextRandom() {
        byte[] randomBytes = new byte[];
        PortalContainer container = PortalContainer.getInstance();
        return Base64.encodeBytes(randomBytes.);
New to GrepCode? Check out our FAQ X