Example usage for com.google.common.cache Cache get

List of usage examples for com.google.common.cache Cache get

Introduction

In this page you can find the example usage for com.google.common.cache Cache get.

Prototype

V get(K key, Callable<? extends V> valueLoader) throws ExecutionException;

Source Link

Document

Returns the value associated with key in this cache, obtaining that value from valueLoader if necessary.

Usage

From source file:com.google.gapid.util.Caches.java

/**
 * Calls and returns the result of {@link Cache#get(Object, Callable)}, where the loader
 * {@link Callable} is guaranteed not to throw a checked exception. Unchecked exceptions are
 * still propagated via the {@link UncheckedExecutionException}.
 *//*from   w ww . jav a2s.  co  m*/
public static <K, V> V getUnchecked(Cache<K, V> cache, K key, Callable<V> loader) {
    try {
        return cache.get(key, loader);
    } catch (ExecutionException e) {
        throw new AssertionError(e);
    }
}

From source file:ec.tstoolkit.utilities.GuavaCaches.java

@Nonnull
public static <K, V> V getOrThrowIOException(@Nonnull Cache<K, V> cache, @Nonnull K key,
        @Nonnull Callable<V> loader) throws IOException {
    try {/*from   w  ww  .  ja v a 2  s  .c  om*/
        return cache.get(key, loader);
    } catch (ExecutionException ex) {
        throw unboxToIOException(ex);
    } catch (UncheckedExecutionException ex) {
        throw new RuntimeException(ex.getCause());
    }
}

From source file:org.ratpackframework.http.internal.DefaultMediaType.java

private static MediaType fromCache(final Cache<String, MediaType> cache, String contentType,
        final String defaultCharset) {
    if (contentType == null) {
        contentType = "";
    } else {//w  ww  .ja v a 2s .c  om
        contentType = contentType.trim();
    }

    final String finalContentType = contentType;
    try {
        return cache.get(contentType, new Callable<MediaType>() {
            public MediaType call() throws Exception {
                return new DefaultMediaType(finalContentType, defaultCharset);
            }
        });
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.newlandframework.rpc.serialize.protostuff.SchemaCache.java

private Schema<?> get(final Class<?> cls, Cache<Class<?>, Schema<?>> cache) {
    try {//from   w ww  .ja va 2 s  .co m
        return cache.get(cls, new Callable<RuntimeSchema<?>>() {
            public RuntimeSchema<?> call() throws Exception {
                return RuntimeSchema.createFrom(cls);
            }
        });
    } catch (ExecutionException e) {
        return null;
    }
}

From source file:com.facebook.buck.rules.keys.SingleBuildRuleKeyCache.java

private <K> V getInternal(Cache<K, V> cache, K key, Function<K, V> create) {
    try {/*  w  ww.j a v  a 2 s.c om*/
        return cache.get(key, () -> create.apply(key));
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.grouplens.lenskit.eval.traintest.CachingDAOProvider.java

@SuppressWarnings("unchecked")
@Override/*from w  w  w  . j a  va  2  s  . c  o  m*/
public T get() {
    Cache<EventDAO, Object> cache = CACHE_MAP.get(getClass());
    assert cache != null;
    try {
        return (T) cache.get(eventDAO, new Callable<Object>() {
            @Override
            public Object call() {
                return create(eventDAO);
            }
        });
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    }
}

From source file:org.haiku.haikudepotserver.pkg.RenderedPkgIconRepositoryImpl.java

@Override
public Optional<byte[]> render(int size, ObjectContext context, Pkg pkg) {

    Preconditions.checkArgument(size <= SIZE_MAX && size >= SIZE_MIN, "bad size");
    Preconditions.checkArgument(null != context, "an object context is required");
    Preconditions.checkArgument(null != pkg, "a package is required");

    Cache<Integer, Optional<byte[]>> pkgCache = getOrCreatePkgCache(pkg.getName());

    try {//  ww w  . j  a v a  2  s .  c om
        return pkgCache.get(size, () -> {

            // first look for the HVIF icon and render the icon from that.

            {
                MediaType hvifMediaType = MediaType.getByCode(context, MediaType.MEDIATYPE_HAIKUVECTORICONFILE);
                Optional<PkgIcon> hvifPkgIconOptional = pkg.getPkgIcon(hvifMediaType, null);

                if (hvifPkgIconOptional.isPresent()) {
                    byte[] hvifData = hvifPkgIconOptional.get().getPkgIconImage().getData();
                    byte[] pngData = pngOptimizationService
                            .optimize(hvifRenderingService.render(size, hvifData));
                    return Optional.of(pngData);
                }
            }

            // If there is no HVIF then it is possible to fall back to PNG images.

            {
                List<PkgIcon> pkgIconList = pkg.getPkgIcons().stream()
                        .filter(pi -> pi.getMediaType().getCode()
                                .equals(com.google.common.net.MediaType.PNG.toString()))
                        .sorted(Comparator.comparing(_PkgIcon::getSize)).collect(Collectors.toList());

                for (PkgIcon pkgIcon : pkgIconList) {
                    if (pkgIcon.getSize() >= size) {
                        return Optional.of(pkgIcon.getPkgIconImage().getData());
                    }
                }

                if (!pkgIconList.isEmpty()) {
                    return Optional.of(pkgIconList.get(pkgIconList.size() - 1).getPkgIconImage().getData());
                }

            }

            return Optional.empty();
        });
    } catch (Exception e) {
        throw new RuntimeException("unable to get the rendered package icon for; " + pkg.getName(), e);
    }

}

From source file:com.google.api.server.spi.discovery.CachingDiscoveryProvider.java

private <T> T getDiscoveryDoc(Cache<ApiKey, T> cache, String root, String name, String version,
        Callable<T> loader) throws NotFoundException, InternalServerErrorException {
    ApiKey key = new ApiKey(name, version, root);
    try {/*ww  w . j  a  v  a  2  s  .  com*/
        return cache.get(key, loader);
    } catch (ExecutionException | UncheckedExecutionException e) {
        // Cast here so we can maintain specific errors for documentation in throws clauses.
        if (e.getCause() instanceof NotFoundException) {
            throw (NotFoundException) e.getCause();
        } else if (e.getCause() instanceof InternalServerErrorException) {
            throw (InternalServerErrorException) e.getCause();
        } else {
            logger.log(Level.SEVERE, "Could not generate or cache discovery doc", e.getCause());
            throw new InternalServerErrorException("Internal Server Error", e.getCause());
        }
    }
}

From source file:com.eucalyptus.auth.euare.CachingPrincipalProvider.java

private UserPrincipal cache(final PrincipalCacheKey key, final PrincipalLoader loader) throws AuthException {
    PrincipalCacheValue principalValue = null;
    final Cache<PrincipalCacheKey, PrincipalCacheValue> cache = cache();
    try {/*  ww w  .j av a2s.com*/
        principalValue = cache.get(key, loader.callable(null));
        if (principalValue.updated + AuthenticationProperties.getAuthorizationExpiry() < System
                .currentTimeMillis()) {
            cache.invalidate(key); // invalidate expired and refresh
            principalValue = cache.get(key, loader.callable(principalValue.principal));
        }
        return principalValue.principal;
    } catch (final ExecutionException e) {
        // reuse cached value on failure within configured limit, but not for web service error responses
        if (!AsyncExceptions.asWebServiceError(e).isPresent() && principalValue != null
                && principalValue.created + AuthenticationProperties.getAuthorizationReuseExpiry() > System
                        .currentTimeMillis()) {
            cache.put(key, new PrincipalCacheValue(principalValue));
            return principalValue.principal;
        }
        if (e.getCause() instanceof AuthException) {
            throw (AuthException) e.getCause();
        } else {
            throw new AuthException(e);
        }
    }
}

From source file:rickbw.incubator.cache.MultiCache.java

@Override
public final @Nonnull V get(final K elementKey, final Callable<? extends V> valueLoader)
        throws ExecutionException {
    final Cache<K, V> cache = getCache(elementKey);
    if (cache != null) {
        return cache.get(elementKey, valueLoader);
    } else {//from   w w  w  . ja v a2  s  . c om
        throw new UncheckedExecutionException(noCacheForKey(elementKey));
    }
}