CassandraStorage(Builder builder) { this.contactPoints = builder.contactPoints; this.maxConnections = builder.maxConnections; this.localDc = builder.localDc; this.username = builder.username; this.password = builder.password; this.ensureSchema = builder.ensureSchema; this.keyspace = builder.keyspace; this.maxTraceCols = builder.maxTraceCols; this.indexTtl = builder.indexTtl; this.spanTtl = builder.spanTtl; this.bucketCount = builder.bucketCount; this.session = new LazySession(builder.sessionFactory, this); this.indexCacheSpec = builder.indexCacheMax == 0 ? null : CacheBuilderSpec.parse("maximumSize=" + builder.indexCacheMax + ",expireAfterWrite=" + builder.indexCacheTtl + "s"); this.indexFetchMultiplier = builder.indexFetchMultiplier; }
/** * 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); }
@Test public void testCacheInvalidation() throws InterruptedException { final String itemKey = "test key"; final String itemValue = "test value"; final int cacheTtlSeconds = 4; GuavaCacheManager manager = new GuavaCacheManager(); manager.setCacheBuilderSpec(CacheBuilderSpec.parse(String.format("expireAfterWrite=%ds", cacheTtlSeconds))); Cache testCache = manager.getCache("testCache"); testCache.put(itemKey, itemValue); Assert.assertEquals(itemValue, testCache.get(itemKey).get()); Thread.sleep((cacheTtlSeconds + 2) * 1000); Assert.assertNull(testCache.get(itemKey)); }
private static CacheBuilderSpec getCacheSpec(Map<String, String> props, String key) { String value = props.get(key); if (value == null) { value = ""; } return CacheBuilderSpec.parse(value); }
CompositeIndexer(Session session, CacheBuilderSpec spec, int bucketCount, @Nullable Integer indexTtl) { this.sharedState = spec == null ? null : CacheBuilder.from(spec).<PartitionKeyToTraceId, Pair<Long>>build().asMap(); Indexer.Factory factory = new Indexer.Factory(session, indexTtl, sharedState); this.indexers = ImmutableSet.of( factory.create(new InsertTraceIdByServiceName(bucketCount)), factory.create(new InsertTraceIdBySpanName()), factory.create(new InsertTraceIdByAnnotation(bucketCount)) ); }
CassandraSpanConsumer(Session session, int bucketCount, int spanTtl, int indexTtl, @Nullable CacheBuilderSpec indexCacheSpec) { this.session = session; this.timestampCodec = new TimestampCodec(session); this.spanTtl = spanTtl; this.metadata = Schema.readMetadata(session); this.indexTtl = metadata.hasDefaultTtl ? null : indexTtl; insertSpan = session.prepare( maybeUseTtl(QueryBuilder .insertInto("traces") .value("trace_id", QueryBuilder.bindMarker("trace_id")) .value("ts", QueryBuilder.bindMarker("ts")) .value("span_name", QueryBuilder.bindMarker("span_name")) .value("span", QueryBuilder.bindMarker("span")))); insertServiceName = session.prepare( maybeUseTtl(QueryBuilder .insertInto(Tables.SERVICE_NAMES) .value("service_name", QueryBuilder.bindMarker("service_name")))); insertSpanName = session.prepare( maybeUseTtl(QueryBuilder .insertInto(Tables.SPAN_NAMES) .value("service_name", QueryBuilder.bindMarker("service_name")) .value("bucket", 0) // bucket is deprecated on this index .value("span_name", QueryBuilder.bindMarker("span_name")))); deduplicatingExecutor = new DeduplicatingExecutor(session, WRITTEN_NAMES_TTL); indexer = new CompositeIndexer(session, indexCacheSpec, bucketCount, this.indexTtl); }
GuavaCacheConfiguration(CacheProperties cacheProperties, CacheManagerCustomizers customizers, ObjectProvider<CacheBuilder<Object, Object>> cacheBuilderProvider, ObjectProvider<CacheBuilderSpec> cacheBuilderSpecProvider, ObjectProvider<CacheLoader<Object, Object>> cacheLoaderProvider) { this.cacheProperties = cacheProperties; this.customizers = customizers; this.cacheBuilder = cacheBuilderProvider.getIfAvailable(); this.cacheBuilderSpec = cacheBuilderSpecProvider.getIfAvailable(); this.cacheLoader = cacheLoaderProvider.getIfAvailable(); }
/** * Construct a {@link MarkdownAssetsServlet} configured with provided parameters, having a wrapped default * {@link AssetServlet} for fulfilling non-markdown asset requests. * <p> * {@code MarkdownAssetsServlet} and {@link AssetServlet} serve 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. * @param resourcePath the base URL from which assets are loaded * @param uriPath the URI path fragment in which all requests are rooted * @param indexFile the filename to use when directories are requested * @param defaultCharset the default character set * @param configuration environment-specific configuration properties * @param extensions Flexmark-Java markdown rendering extensions to use * @param options Flexmark-Java markdown rendering options * @param cacheBuilderSpec {@link CacheBuilderSpec} for rendered pages */ public MarkdownAssetsServlet(@NotNull String resourcePath, @NotNull String uriPath, @NotNull String indexFile, @NotNull Charset defaultCharset, @NotNull MarkdownAssetsConfiguration configuration, @NotNull List<Extension> extensions, @NotNull DataHolder options, @NotNull CacheBuilderSpec cacheBuilderSpec) { this.resourcePath = resourcePath; this.uriPath = uriPath; this.indexFile = indexFile; this.defaultCharset = defaultCharset; this.configuration = configuration; parser = Parser.builder(options).extensions(extensions).build(); renderer = HtmlRenderer.builder(options).extensions(extensions).build(); assetServlet = new AssetServlet(resourcePath, uriPath, indexFile, defaultCharset); pageCache = CacheBuilder.from(cacheBuilderSpec) .build(new CacheLoader<URL, CachedPage>() { @Override public CachedPage load(@NotNull URL key) throws Exception { return renderPage(key); } }); try { URL resource = this.getClass().getResource(resourcePath); Preconditions.checkNotNull(resource, "Resource root URL (" + resourcePath + ") was not found"); resourceRootURL = resource.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Resource root URL (" + resourcePath + ") was ind", e); } }
/** * 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)); }
@Test public void testCreateCachingAuthentiator() throws AuthenticationException { AllowedPeerConfiguration config = new AllowedPeerConfiguration(); config.setCredentialFile("peers/test-peers.properties"); config.setCachePolicy(CacheBuilderSpec.parse("maximumSize=100, expireAfterAccess=10m")); CachingAuthenticator<BasicCredentials, Peer> cachingAuthenticator = config.createCachingAuthenticator(new MetricRegistry()); assertTrue(cachingAuthenticator.authenticate(new BasicCredentials("foo", "bar")).isPresent()); }
private BasicAuthFactory<String> createBasicAuthFactory(AuthConfiguration config, MetricRegistry metrics) { Authenticator<BasicCredentials, String> authenticator = createAuthenticator(config); Optional<String> cacheSpec = config.getCacheSpec(); if (cacheSpec.isPresent()) { CacheBuilderSpec spec = CacheBuilderSpec.parse(cacheSpec.get()); authenticator = new CachingAuthenticator<>(metrics, authenticator, spec); } return new BasicAuthFactory<>(authenticator, config.getRealm(), String.class); }
/** * Creates a singleton cache from a CacheBuilderSpec * * @param <V> * @param cacheName * @param spec * @return */ public <V> SingletonCache<V> singletonCache(String cacheName, CacheBuilderSpec spec) { synchronized (caches) { checkName(cacheName); SingletonCache<V> cache = SingletonCache.fromSpec(cacheName,spec); caches.put(cacheName, cache); return cache; } }
/** * Creates a basic cache from a CacheBuilderSpec * * @param <K> * @param <V> * @param cacheName * @param spec * @return */ public <K, V> GuavaBasicCache<K,V> guavaCache(String cacheName, CacheBuilderSpec spec) { synchronized (caches) { checkName(cacheName); GuavaBasicCache<K,V> cache = GuavaBasicCache.fromSpec(cacheName, spec); caches.put(cacheName, cache); return cache; } }
public SwagrCacheDelegate() { cacheManager = CacheManager.createCacheManager("swagr"); CacheBuilderSpec spec = CacheBuilderSpec.parse("expireAfterAccess=12h,maximumSize=1000"); STAT_CACHE = cacheManager.guavaCache("SwagrFullRequestCache", spec); CHART_FORMAT_STAT_CACHE = cacheManager.guavaCache("SwagrFormattedRequestCache",spec); LOCATION_CACHE = cacheManager.singletonCache("SwagrLocationCache"); SERVICE_CACHE = cacheManager.singletonCache("SwagrServiceCache"); }
/** * example of registering cache authenticator * * @param e */ private void registerCacheAuthenticator(Environment e) { CachingAuthenticator<BasicCredentials, Boolean> authenticator = new CachingAuthenticator<BasicCredentials, Boolean>( e.metrics(), new DefaultAuthenticator(), CacheBuilderSpec.parse("maximumSize=100, expireAfterAccess=30m") ); e.jersey().register(new BasicAuthProvider<Boolean>(authenticator, "Cached restfull API authentication")); }
public RestWarsModule(UniverseConfiguration universeConfiguration, ManagedDataSource managedDataSource, int passwordIterations, CacheBuilderSpec credentialsCache, MetricRegistry metricRegistry, String securityRealm) { this.securityRealm = Preconditions.checkNotNull(securityRealm, "securityRealm"); this.metricRegistry = Preconditions.checkNotNull(metricRegistry, "metricRegistry"); this.credentialsCache = Preconditions.checkNotNull(credentialsCache, "credentialsCache"); this.managedDataSource = Preconditions.checkNotNull(managedDataSource, "managedDataSource"); this.universeConfiguration = Preconditions.checkNotNull(universeConfiguration, "universeConfiguration"); this.passwordIterations = passwordIterations; }
/** * 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); } }); }
@Test public void testCacheItem() { final String itemKey = "test key"; final String itemValue = "test value"; GuavaCacheManager manager = new GuavaCacheManager(); manager.setCacheBuilderSpec(CacheBuilderSpec.parse("expireAfterWrite=1m")); Cache testCache = manager.getCache("testCache"); testCache.put(itemKey, itemValue); Assert.assertEquals(itemValue, testCache.get(itemKey).get()); }
@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); }
public ConfigurableMapMakerCache(final CacheBuilderSpec specification) throws IllegalArgumentException { Preconditions.checkNotNull(specification, "specification may not be null."); Preconditions.checkArgument(!specification.toParsableString().isEmpty(), "specification may not be empty."); backingMap = CacheBuilder.from(specification).<Integer, T>build().asMap(); log.info(String.format("Created map with %s specification.", specification)); }
@JsonProperty("authenticationCachePolicy") public CacheBuilderSpec getAuthenticationCachePolicy() { return CacheBuilderSpec.parse(authenticationCachePolicy); }
public CacheBuilderSpec getAuthenticationCachePolicy() { return authenticationCachePolicy; }
public CacheBuilderSpec getAuthenticationCachePolicy() { return CacheBuilderSpec.parse(authenticationCachePolicy); }
public GuavaCacheManager(CacheRegistry cacheRegistry, String cacheBuilderSpec) { _spec = CacheBuilderSpec.parse(checkNotNull(cacheBuilderSpec)); _cacheRegistry = cacheRegistry; }
public void setAuthenticationCachePolicy(final CacheBuilderSpec authenticationCachePolicy) { this.authenticationCachePolicy = authenticationCachePolicy; }
public CacheBuilderSpec getCacheSpec() { return cacheSpec; }
/** * @return A String conforming to Guava's CacheBuilderSpec that is used if/when returning a CachingAuthenticator. */ public CacheBuilderSpec getCachePolicy() { return cachePolicy; }
/** * @param cachePolicy A String conforming to Guava's CacheBuilderSpec that is used if/when returning a CachingAuthenticator. */ public void setCachePolicy(CacheBuilderSpec cachePolicy) { this.cachePolicy = cachePolicy; }
private AuthDMO() { cacheManager = CacheManager.createCacheManager("auth"); CacheBuilderSpec spec = CacheBuilderSpec.parse("expireAfterAccess=4h,maximumSize=1000000"); //4 hours of no calls it expires. max capacity is 1M sessions SESSION_STATS = cacheManager.guavaCache("Auth_SessionStats", spec); }