001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.security.auth;
016    
017    import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
018    
019    import java.util.Collections;
020    import java.util.Iterator;
021    import java.util.Map;
022    import java.util.Set;
023    import java.util.SortedMap;
024    import java.util.TreeMap;
025    
026    /**
027     * @author Shuyang Zhou
028     */
029    public class TransientTokenUtil {
030    
031            public static boolean checkToken(String token) {
032                    long currentTime = System.currentTimeMillis();
033    
034                    expungeExpiredToken(currentTime);
035    
036                    Set<Map.Entry<Long, String>> tokens = _tokens.entrySet();
037    
038                    Iterator<Map.Entry<Long, String>> itr = tokens.iterator();
039    
040                    while (itr.hasNext()) {
041                            Map.Entry<Long, String> entry = itr.next();
042    
043                            String curToken = entry.getValue();
044    
045                            if (token.equals(curToken)) {
046                                    itr.remove();
047    
048                                    return true;
049                            }
050                    }
051    
052                    return false;
053            }
054    
055            public static void clearAll() {
056                    _tokens.clear();
057            }
058    
059            public static String createToken(long timeTolive) {
060                    long currentTime = System.currentTimeMillis();
061    
062                    long expireTime = currentTime + timeTolive;
063    
064                    expungeExpiredToken(currentTime);
065    
066                    String token = PortalUUIDUtil.generate();
067    
068                    _tokens.put(expireTime, token);
069    
070                    return token;
071            }
072    
073            private static void expungeExpiredToken(long currentTime) {
074                    SortedMap<Long, String> headMap = _tokens.headMap(currentTime);
075    
076                    headMap.clear();
077            }
078    
079            private static final SortedMap<Long, String> _tokens =
080                    Collections.synchronizedSortedMap(new TreeMap<Long, String>());
081    
082    }