001/**
002 * Copyright 2016 Tampere University of Technology, Pori Department
003 * 
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * 
008 *   http://www.apache.org/licenses/LICENSE-2.0
009 * 
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package service.tut.pori.apilta.files;
017
018import java.math.BigInteger;
019import java.security.SecureRandom;
020import java.util.concurrent.TimeUnit;
021
022import com.google.common.cache.Cache;
023import com.google.common.cache.CacheBuilder;
024
025/**
026 * temporary file token handler
027 * 
028 */
029public class TemporaryTokenHandler {
030  /** default cache validity, in seconds */
031  public static final long CACHE_VALIDITY = 900;
032  private Cache<String, String> _cache = null; // key: token, value: GUID
033  private SecureRandom _random = new SecureRandom();
034  
035  /**
036   * 
037   */
038  public TemporaryTokenHandler(){
039    _cache = CacheBuilder.newBuilder().expireAfterAccess(CACHE_VALIDITY, TimeUnit.SECONDS).build();
040  }
041
042  /**
043   * 
044   * @param guid
045   * @return existing or newly generated token for the GUID
046   */
047  public String getToken(String guid) {
048    String token = new BigInteger(130, _random).toString(32); // from http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
049    _cache.put(token, guid);
050    return token;
051  }
052
053  /**
054   * 
055   * @param token
056   * @return guid for the given token or null if not found
057   */
058  public String getGUID(String token) {
059    return _cache.getIfPresent(token);
060  }
061}