类com.google.common.cache.CacheBuilderSpec源码实例Demo

下面列出了怎么用com.google.common.cache.CacheBuilderSpec的API类实例代码及写法,或者点击链接到github查看源代码。

/**
 * 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);
}
 
@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;
}
 
/**
 * 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"));
}
 
/**
 * 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;
}
 
@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);
  }
}
 
@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));
}
 
源代码7 项目: bazel   文件: Converters.java
@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);
  }
}
 
源代码8 项目: simple-json-rpc   文件: JsonRpcServer.java
/**
 * 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);
                }
            });
}
 
源代码9 项目: ServerListPlus   文件: BungeePlugin.java
@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;
    }
}
 
源代码10 项目: ServerListPlus   文件: BukkitPlugin.java
@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;
    }
}
 
源代码11 项目: ServerListPlus   文件: ServerListPlusCore.java
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);
}
 
源代码12 项目: ServerListPlus   文件: VelocityPlugin.java
@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;
    }
}
 
源代码13 项目: ServerListPlus   文件: CanaryPlugin.java
@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;
    }
}
 
源代码14 项目: ServerListPlus   文件: ServerListPlusServer.java
@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;
    }
}
 
源代码15 项目: ServerListPlus   文件: SpongePlugin.java
@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;
    }
}
 
源代码16 项目: rufus   文件: RufusConfiguration.java
public CacheBuilderSpec getAuthenticationCachePolicy() {
    return authenticationCachePolicy;
}
 
源代码17 项目: dropwizard-graphql   文件: GraphQLFactory.java
@JsonProperty
public CacheBuilderSpec getQueryCache() {
  return queryCache;
}
 
源代码18 项目: dropwizard-graphql   文件: GraphQLFactory.java
@JsonProperty
public void setQueryCache(String queryCache) {
  this.queryCache = CacheBuilderSpec.parse(queryCache);
}
 
源代码19 项目: emodb   文件: GuavaCacheManager.java
public GuavaCacheManager(CacheRegistry cacheRegistry, String cacheBuilderSpec) {
    _spec = CacheBuilderSpec.parse(checkNotNull(cacheBuilderSpec));
    _cacheRegistry = cacheRegistry;
}
 
public CacheBuilderSpec getCacheSpec() {
  return cacheSpec;
}
 
源代码21 项目: eagle   文件: BasicAuthBuilder.java
private Authenticator<BasicCredentials, User> cache(Authenticator<BasicCredentials, User> authenticator) {
    return new CachingAuthenticator<>(environment.metrics(), authenticator, CacheBuilderSpec.parse(authConfig.getCachePolicy()));
}
 
源代码22 项目: SciGraph   文件: ApiConfiguration.java
public CacheBuilderSpec getAuthenticationCachePolicy() {
  return authenticationCachePolicy;
}
 
@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"));

}
 
源代码24 项目: jpmml-evaluator   文件: CacheUtil.java
static
public CacheBuilderSpec getCacheBuilderSpec(){
	return CacheUtil.cacheBuilderSpec;
}
 
源代码25 项目: jpmml-evaluator   文件: CacheUtil.java
static
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec){
	CacheUtil.cacheBuilderSpec = Objects.requireNonNull(cacheBuilderSpec);
}
 
源代码26 项目: dropwizard-auth-ldap   文件: LdapConfiguration.java
public CacheBuilderSpec getCachePolicy() {
    return cachePolicy;
}
 
源代码27 项目: dropwizard-auth-ldap   文件: LdapConfiguration.java
public LdapConfiguration setCachePolicy(CacheBuilderSpec cachePolicy) {
    this.cachePolicy = cachePolicy;
    return this;
}
 
源代码28 项目: lams   文件: GuavaCacheManager.java
/**
 * 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));
}
 
源代码29 项目: rdf4j   文件: SourceSelectionMemoryCache.java
/**
 *
 * @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();
}
 
源代码30 项目: spring4-understanding   文件: GuavaCacheManager.java
/**
 * 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));
}