001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2014 ForgeRock AS. 015 */ 016 017package org.forgerock.openig.filter.oauth2.cache; 018 019import java.util.concurrent.Callable; 020import java.util.concurrent.ExecutionException; 021 022import org.forgerock.openig.filter.oauth2.AccessToken; 023import org.forgerock.openig.filter.oauth2.AccessTokenResolver; 024import org.forgerock.openig.filter.oauth2.OAuth2TokenException; 025 026/** 027 * A {@link CachingAccessTokenResolver} is a delegating {@link AccessTokenResolver} that uses a write-through cache 028 * to enable fast {@link AccessToken} resolution. 029 */ 030public class CachingAccessTokenResolver implements AccessTokenResolver { 031 032 private final AccessTokenResolver resolver; 033 private final ThreadSafeCache<String, AccessToken> cache; 034 035 /** 036 * Builds a {@link CachingAccessTokenResolver} delegating to the given {@link AccessTokenResolver} using the given 037 * (pre-configured) cache. 038 * 039 * @param resolver 040 * resolver to delegates to 041 * @param cache 042 * access token cache 043 */ 044 public CachingAccessTokenResolver(final AccessTokenResolver resolver, 045 final ThreadSafeCache<String, AccessToken> cache) { 046 this.resolver = resolver; 047 this.cache = cache; 048 } 049 050 @Override 051 public AccessToken resolve(final String token) throws OAuth2TokenException { 052 try { 053 return cache.getValue(token, new Callable<AccessToken>() { 054 @Override 055 public AccessToken call() throws Exception { 056 return resolver.resolve(token); 057 } 058 }); 059 } catch (InterruptedException e) { 060 throw new OAuth2TokenException("Timed out retrieving OAuth2 access token information", e); 061 } catch (ExecutionException e) { 062 throw new OAuth2TokenException("Initial token resolution has failed", e); 063 } 064 } 065}