下面列出了怎么用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));
}
@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);
}
}
/**
* 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);
}
});
}
@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;
}
}
@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;
}
}
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);
}
@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;
}
}
@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;
}
}
@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;
}
}
@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;
}
}
public CacheBuilderSpec getAuthenticationCachePolicy() {
return authenticationCachePolicy;
}
@JsonProperty
public CacheBuilderSpec getQueryCache() {
return queryCache;
}
@JsonProperty
public void setQueryCache(String queryCache) {
this.queryCache = CacheBuilderSpec.parse(queryCache);
}
public GuavaCacheManager(CacheRegistry cacheRegistry, String cacheBuilderSpec) {
_spec = CacheBuilderSpec.parse(checkNotNull(cacheBuilderSpec));
_cacheRegistry = cacheRegistry;
}
public CacheBuilderSpec getCacheSpec() {
return cacheSpec;
}
private Authenticator<BasicCredentials, User> cache(Authenticator<BasicCredentials, User> authenticator) {
return new CachingAuthenticator<>(environment.metrics(), authenticator, CacheBuilderSpec.parse(authConfig.getCachePolicy()));
}
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"));
}
static
public CacheBuilderSpec getCacheBuilderSpec(){
return CacheUtil.cacheBuilderSpec;
}
static
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec){
CacheUtil.cacheBuilderSpec = Objects.requireNonNull(cacheBuilderSpec);
}
public CacheBuilderSpec getCachePolicy() {
return cachePolicy;
}
public LdapConfiguration setCachePolicy(CacheBuilderSpec cachePolicy) {
this.cachePolicy = cachePolicy;
return this;
}
/**
* 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));
}
/**
*
* @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();
}
/**
* 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));
}