com.google.common.cache.CacheBuilderSpec Java Examples

The following examples show how to use com.google.common.cache.CacheBuilderSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AssetServlet.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@code AssetServlet} that serves static assets loaded from {@code resourceURL}
 * (typically a file: or jar: URL). The assets are served at URIs rooted at {@code uriPath}. For
 * example, given a {@code resourceURL} of {@code "file:/data/assets"} and a {@code uriPath} of
 * {@code "/js"}, an {@code AssetServlet} would serve the contents of {@code
 * /data/assets/example.js} in response to a request for {@code /js/example.js}. If a directory
 * is requested and {@code indexFile} is defined, then {@code AssetServlet} will attempt to
 * serve a file with that name in that directory. If a directory is requested and {@code
 * indexFile} is null, it will serve a 404.
 *
 * @param resourcePathToUriPathMapping A mapping from base URL's from which assets are loaded to
 *                                     the URI path fragment in which the requests for that asset
 *                                     are rooted
 * @param indexFile                    the filename to use when directories are requested, or null
 *                                     to serve no indexes
 * @param defaultCharset               the default character set
 * @param spec                         the CacheBuilderSpec to use
 * @param overrides                    the path overrides
 * @param mimeTypes                    the mimeType overrides
 */
public AssetServlet(Iterable<Map.Entry<String, String>> resourcePathToUriPathMapping,
                    String indexFile,
                    Charset defaultCharset,
                    CacheBuilderSpec spec,
                    Iterable<Map.Entry<String, String>> overrides,
                    Iterable<Map.Entry<String, String>> mimeTypes) {
  this.defaultCharset = defaultCharset;
  AssetLoader loader = new AssetLoader(resourcePathToUriPathMapping, indexFile, overrides);

  CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.from(spec);
  // Don't add the weigher if we are using maximumSize instead of maximumWeight.
  if (spec.toParsableString().contains("maximumWeight=")) {
    cacheBuilder.weigher(new AssetSizeWeigher());
  }
  this.cache = cacheBuilder.build(loader);

  this.cacheSpec = spec;
  this.mimeTypes = new MimeTypes();
  this.setMimeTypes(mimeTypes);
}
 
Example #2
Source File: AssetsBundleTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Test
public void canOverrideCacheSpec() throws Exception {
  final String cacheSpec = "expireAfterAccess=20m";

  AssetsBundleConfiguration config = new AssetsBundleConfiguration() {
    @Override
    public AssetsConfiguration getAssetsConfiguration() {
      return AssetsConfiguration.builder().cacheSpec(cacheSpec).build();
    }
  };

  runBundle(new ConfiguredAssetsBundle(), "assets", config);
  assertThat(servlet.getCacheSpec()).isEqualTo(CacheBuilderSpec.parse(cacheSpec));
}
 
Example #3
Source File: SpongePlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}
 
Example #4
Source File: ServerListPlusServer.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}
 
Example #5
Source File: CanaryPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}
 
Example #6
Source File: VelocityPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}
 
Example #7
Source File: ServerListPlusCore.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
private void reloadCaches() {
    CoreConf conf = this.getConf(CoreConf.class);
    boolean enabled = statusManager.hasFavicon();

    // Check if favicon cache configuration has been changed
    if (!enabled || (faviconCacheConf == null || conf.Caches == null ||
            !faviconCacheConf.equals(conf.Caches.Favicon))) {
        if (plugin.getFaviconCache() != null) {
            getLogger().log(DEBUG, "Deleting old favicon cache due to configuration changes.");
            plugin.reloadFaviconCache(null); // Delete the old favicon cache
        }

        if (enabled) {
            getLogger().log(DEBUG, "Creating new favicon cache...");

            try {
                this.faviconCacheConf = conf.Caches.Favicon;
                plugin.reloadFaviconCache(CacheBuilderSpec.parse(faviconCacheConf));
            } catch (IllegalArgumentException e) {
                getLogger().log(e, "Unable to create favicon cache using configuration settings.");
                this.faviconCacheConf = getDefaultConf(CoreConf.class).Caches.Favicon;
                plugin.reloadFaviconCache(CacheBuilderSpec.parse(faviconCacheConf));
            }

            getLogger().log(DEBUG, "Favicon cache created.");
        } else
            faviconCacheConf = null; // Not used, so there is also no cache
    }

    plugin.reloadCaches(this);
}
 
Example #8
Source File: BukkitPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}
 
Example #9
Source File: BungeePlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}
 
Example #10
Source File: JsonRpcServer.java    From simple-json-rpc with MIT License 5 votes vote down vote up
/**
 * Init JSON-RPC server
 *
 * @param mapper           used-defined JSON mapper
 * @param cacheBuilderSpec classes metadata cache specification
 */
public JsonRpcServer(@NotNull ObjectMapper mapper, @NotNull CacheBuilderSpec cacheBuilderSpec) {
    this.mapper = mapper;
    classesMetadata = CacheBuilder.from(cacheBuilderSpec).build(
            new CacheLoader<Class<?>, ClassMetadata>() {
                @Override
                public ClassMetadata load(Class<?> clazz) throws Exception {
                    return Reflections.getClassMetadata(clazz);
                }
            });
}
 
Example #11
Source File: Converters.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public CacheBuilderSpec convert(String spec) throws OptionsParsingException {
  try {
    return Strings.isNullOrEmpty(spec) ? null : CacheBuilderSpec.parse(spec);
  } catch (IllegalArgumentException e) {
    throw new OptionsParsingException("Failed to parse CacheBuilderSpec: " + e.getMessage(), e);
  }
}
 
Example #12
Source File: ConfiguredAssetsBundle.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
@Override
public void run(AssetsBundleConfiguration bundleConfig, Environment env) throws Exception {
  AssetsConfiguration config = bundleConfig.getAssetsConfiguration();

  // Let the cache spec from the configuration override the one specified in the code
  CacheBuilderSpec spec = (config.getCacheSpec() != null)
      ? CacheBuilderSpec.parse(config.getCacheSpec())
      : cacheBuilderSpec;

  Iterable<Map.Entry<String, String>> overrides = config.getOverrides().entrySet();
  Iterable<Map.Entry<String, String>> mimeTypes = config.getMimeTypes().entrySet();

  Iterable<Map.Entry<String, String>> servletResourcePathToUriMappings;

  if (!config.getResourcePathToUriMappings().isEmpty()) {
    servletResourcePathToUriMappings = config.getResourcePathToUriMappings().entrySet();
  } else {
    servletResourcePathToUriMappings = resourcePathToUriMappings;
  }
  AssetServlet servlet = new AssetServlet(servletResourcePathToUriMappings, indexFile,
      Charsets.UTF_8, spec, overrides, mimeTypes);

  for (Map.Entry<String, String> mapping : servletResourcePathToUriMappings) {
    String mappingPath = mapping.getValue();
    if (!mappingPath.endsWith("/")) {
      mappingPath += '/';
    }
    mappingPath += "*";
    servlet.setCacheControlHeader(config.getCacheControlHeader());
    LOGGER.info("Registering ConfiguredAssetBundle with name: {} for path {}", assetsName,
        mappingPath);
    env.servlets().addServlet(assetsName, servlet).addMapping(mappingPath);
  }
}
 
Example #13
Source File: ConfiguredAssetsBundle.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link ConfiguredAssetsBundle} which will configure the service to serve the
 * static files located in {@code src/main/resources/${resourcePath}} as {@code /${uriPath}}. For
 * example, given a {@code resourcePath} of {@code "/assets"} and a uriPath of {@code "/js"},
 * {@code src/main/resources/assets/example.js} would be served up from {@code /js/example.js}.
 *
 * @param resourcePathToUriMappings a series of mappings from resource paths (in the classpath)
 *                                  to the uri path that hosts the resource
 * @param cacheBuilderSpec          the spec for the cache builder
 * @param indexFile                 the name of the index file to use
 * @param assetsName                the name of servlet mapping used for this assets bundle
 */
public ConfiguredAssetsBundle(Map<String, String> resourcePathToUriMappings, String indexFile,
                              String assetsName, CacheBuilderSpec cacheBuilderSpec) {
  for (Map.Entry<String, String> mapping : resourcePathToUriMappings.entrySet()) {
    String resourcePath = mapping.getKey();
    checkArgument(resourcePath.startsWith("/"), "%s is not an absolute path", resourcePath);
    checkArgument(!"/".equals(resourcePath), "%s is the classpath root", resourcePath);
  }
  this.resourcePathToUriMappings =
      Iterables.unmodifiableIterable(resourcePathToUriMappings.entrySet());
  this.cacheBuilderSpec = cacheBuilderSpec;
  this.indexFile = indexFile;
  this.assetsName = assetsName;
}
 
Example #14
Source File: GuavaSerializers.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type,
        BeanDescription beanDesc, JsonFormat.Value formatOverrides)
{
    Class<?> raw = type.getRawClass();
    if (RangeSet.class.isAssignableFrom(raw)) {
        return new RangeSetSerializer();
    }
    if (Range.class.isAssignableFrom(raw)) {
        return new RangeSerializer(_findDeclared(type, Range.class));
    }
    if (Table.class.isAssignableFrom(raw)) {
        return new TableSerializer(_findDeclared(type, Table.class));
    }
    if (HostAndPort.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (InternetDomainName.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    // not sure how useful, but why not?
    if (CacheBuilderSpec.class.isAssignableFrom(raw) || CacheBuilder.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (HashCode.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (FluentIterable.class.isAssignableFrom(raw)) {
        JavaType iterableType = _findDeclared(type, Iterable.class);
        return new StdDelegatingSerializer(FluentConverter.instance, iterableType, null, null);
    }
    return null;
}
 
Example #15
Source File: CachingPreparsedDocumentProvider.java    From dropwizard-graphql with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param spec Specification for the cache
 * @param registry Metric registry
 */
public CachingPreparsedDocumentProvider(CacheBuilderSpec spec, MetricRegistry registry) {
  LOGGER.info("Query Cache: {}", spec);
  cache = CacheBuilder.from(spec).build();

  cacheMisses =
      registry.meter(MetricRegistry.name(CachingPreparsedDocumentProvider.class, "cache-misses"));
}
 
Example #16
Source File: GraphQLFactory.java    From dropwizard-graphql with Apache License 2.0 4 votes vote down vote up
@JsonProperty
public void setQueryCache(String queryCache) {
  this.queryCache = CacheBuilderSpec.parse(queryCache);
}
 
Example #17
Source File: CacheUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec){
	CacheUtil.cacheBuilderSpec = Objects.requireNonNull(cacheBuilderSpec);
}
 
Example #18
Source File: CacheUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
public CacheBuilderSpec getCacheBuilderSpec(){
	return CacheUtil.cacheBuilderSpec;
}
 
Example #19
Source File: LdapConfiguration.java    From dropwizard-auth-ldap with Apache License 2.0 4 votes vote down vote up
public CacheBuilderSpec getCachePolicy() {
    return cachePolicy;
}
 
Example #20
Source File: GuavaCacheManager.java    From emodb with Apache License 2.0 4 votes vote down vote up
public GuavaCacheManager(CacheRegistry cacheRegistry, String cacheBuilderSpec) {
    _spec = CacheBuilderSpec.parse(checkNotNull(cacheBuilderSpec));
    _cacheRegistry = cacheRegistry;
}
 
Example #21
Source File: LdapConfiguration.java    From dropwizard-auth-ldap with Apache License 2.0 4 votes vote down vote up
public LdapConfiguration setCachePolicy(CacheBuilderSpec cachePolicy) {
    this.cachePolicy = cachePolicy;
    return this;
}
 
Example #22
Source File: CachingAuthenticatorTest.java    From dropwizard-java8 with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(underlying.authenticate(anyString())).thenReturn(Optional.<Principal>of(new PrincipalImpl("principal")));
    cached = new CachingAuthenticator<>(new MetricRegistry(), underlying, CacheBuilderSpec.parse("maximumSize=1"));

}
 
Example #23
Source File: ApiConfiguration.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
public CacheBuilderSpec getAuthenticationCachePolicy() {
  return authenticationCachePolicy;
}
 
Example #24
Source File: BasicAuthBuilder.java    From eagle with Apache License 2.0 4 votes vote down vote up
private Authenticator<BasicCredentials, User> cache(Authenticator<BasicCredentials, User> authenticator) {
    return new CachingAuthenticator<>(environment.metrics(), authenticator, CacheBuilderSpec.parse(authConfig.getCachePolicy()));
}
 
Example #25
Source File: RufusConfiguration.java    From rufus with MIT License 4 votes vote down vote up
public CacheBuilderSpec getAuthenticationCachePolicy() {
    return authenticationCachePolicy;
}
 
Example #26
Source File: AssetServlet.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 4 votes vote down vote up
public CacheBuilderSpec getCacheSpec() {
  return cacheSpec;
}
 
Example #27
Source File: GraphQLFactory.java    From dropwizard-graphql with Apache License 2.0 4 votes vote down vote up
@JsonProperty
public CacheBuilderSpec getQueryCache() {
  return queryCache;
}
 
Example #28
Source File: GuavaCacheManager.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Set the Guava CacheBuilderSpec to use for building each individual
 * {@link GuavaCache} instance.
 * @see #createNativeGuavaCache
 * @see com.google.common.cache.CacheBuilder#from(CacheBuilderSpec)
 */
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec) {
	doSetCacheBuilder(CacheBuilder.from(cacheBuilderSpec));
}
 
Example #29
Source File: GuavaCacheManager.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Set the Guava CacheBuilderSpec to use for building each individual
 * {@link GuavaCache} instance.
 * @see #createNativeGuavaCache
 * @see com.google.common.cache.CacheBuilder#from(CacheBuilderSpec)
 */
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec) {
	doSetCacheBuilder(CacheBuilder.from(cacheBuilderSpec));
}
 
Example #30
Source File: SourceSelectionMemoryCache.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 *
 * @param cacheSpec a Guava compatible {@link CacheBuilderSpec}, if <code>null</code> the
 *                  {@link #DEFAULT_CACHE_SPEC} is used
 */
public SourceSelectionMemoryCache(String cacheSpec) {
	cacheSpec = cacheSpec == null ? DEFAULT_CACHE_SPEC : cacheSpec;
	this.cache = CacheBuilder.from(CacheBuilderSpec.parse(cacheSpec)).build();
}