Example usage for com.google.common.cache CacheBuilder from

List of usage examples for com.google.common.cache CacheBuilder from

Introduction

In this page you can find the example usage for com.google.common.cache CacheBuilder from.

Prototype

@GwtIncompatible("To be supported")
public static CacheBuilder<Object, Object> from(String spec) 

Source Link

Document

Constructs a new CacheBuilder instance with the settings specified in spec .

Usage

From source file:com.heliosapm.filewatcher.ScriptFileWatcher.java

/**
 * Creates a new ScriptFileWatcher/*from ww w  .  j a v  a 2  s  .  c o  m*/
 */
private ScriptFileWatcher() {
    super(SharedNotificationExecutor.getInstance(), notificationInfos);
    keepRunning.set(true);
    try {
        watcher = FileSystems.getDefault().newWatchService();
    } catch (Exception ex) {
        log.error("Failed to create default WatchService", ex);
        throw new RuntimeException("Failed to create default WatchService", ex);
    }
    eventHandlerPool = new JMXManagedThreadPool(THREAD_POOL_OBJECT_NAME, "FileWatcherThreadPool", CORES,
            CORES * 2, 1024, 60000, 100, 90);
    hotDirs = CacheStatistics.getJMXStatisticsEnableCache(
            CacheBuilder
                    .from(ConfigurationHelper.getSystemThenEnvProperty(DIR_CACHE_PROP, DIR_CACHE_DEFAULT_SPEC)),
            "watchedDirectories");
    // Cache<Path, WatchKey>
    templateWatches = CacheStatistics.getJMXStatisticsEnableCache(
            CacheBuilder.from(
                    ConfigurationHelper.getSystemThenEnvProperty(TWATCH_CACHE_PROP, DIR_CACHE_DEFAULT_SPEC)),
            "templateWatches");
    // Cache<Path, Set<File>>
    templateMappings = CacheStatistics.getJMXStatisticsEnableCache(
            CacheBuilder.from(
                    ConfigurationHelper.getSystemThenEnvProperty(TMAP_CACHE_PROP, DIR_CACHE_DEFAULT_SPEC)),
            "templateMappings");

    scriptManager = StateService.getInstance();
    Map<WatchEventType, Set<FileChangeEventHandler>> tmpHandlerMap = new EnumMap<WatchEventType, Set<FileChangeEventHandler>>(
            WatchEventType.class);
    for (WatchEventType type : WatchEventType.values()) {
        tmpHandlerMap.put(type, new NonBlockingHashSet<FileChangeEventHandler>());
    }
    eventHandlers = Collections.unmodifiableMap(tmpHandlerMap);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            shutdown();
        }
    });
    JMXHelper.registerMBean(OBJECT_NAME, this);
    registerEventHandler(newDirectoryHandler);
    registerEventHandler(newFileHandler);
    registerEventHandler(deletedFileHandler);
    registerEventHandler(deletedDirectoryHandler);
    addDefaultHotDirs();
    startFileEventListener();

}

From source file:librec.data.SparseMatrix.java

/**
 * create a column cache of a matrix/*from w ww  . jav a 2 s.  c o m*/
 * 
 * @param cacheSpec
 *            cache specification
 * @return a matrix column cache
 */
public LoadingCache<Integer, SparseVector> columnCache(String cacheSpec) {
    LoadingCache<Integer, SparseVector> cache = CacheBuilder.from(cacheSpec)
            .build(new CacheLoader<Integer, SparseVector>() {

                @Override
                public SparseVector load(Integer columnId) throws Exception {
                    return column(columnId);
                }
            });

    return cache;
}

From source file:net.minecrell.serverlistplus.bungee.BungeePlugin.java

@Override
public void reloadFaviconCache(CacheBuilderSpec spec) {
    if (spec != null) {
        this.faviconCache = CacheBuilder.from(spec).build(faviconLoader);
    } else {//from  www  . j  a va  2 s .c o m
        // Delete favicon cache
        faviconCache.invalidateAll();
        faviconCache.cleanUp();
        this.faviconCache = null;
    }
}

From source file:librec.data.SparseMatrix.java

/**
 * create a row cache of a matrix in {row, row-specific columns}
 * //from   w w  w  . j a v a2  s  .  com
 * @param cacheSpec
 *            cache specification
 * @return a matrix row cache in {row, row-specific columns}
 */
public LoadingCache<Integer, List<Integer>> columnRowsCache(String cacheSpec) {
    LoadingCache<Integer, List<Integer>> cache = CacheBuilder.from(cacheSpec)
            .build(new CacheLoader<Integer, List<Integer>>() {

                @Override
                public List<Integer> load(Integer colId) throws Exception {
                    return getRows(colId);
                }
            });

    return cache;
}

From source file:net.minecrell.serverlistplus.bukkit.BukkitPlugin.java

@Override
public void reloadCaches(ServerListPlusCore core) {
    CoreConf conf = core.getConf(CoreConf.class);
    // Check if request cache configuration has been changed
    if (requestCacheConf == null || requestCache == null || !requestCacheConf.equals(conf.Caches.Request)) {
        if (requestCache != null) {
            // Delete the request cache
            getLogger().log(DEBUG, "Deleting old request cache due to configuration changes.");
            requestCache.invalidateAll();
            requestCache.cleanUp();/*from  ww  w.  j  a  va 2  s .c  o  m*/
            this.requestCache = null;
        }

        getLogger().log(DEBUG, "Creating new request cache...");

        try {
            this.requestCacheConf = conf.Caches.Request;
            this.requestCache = CacheBuilder.from(requestCacheConf).build(requestLoader);
        } catch (IllegalArgumentException e) {
            getLogger().log(ERROR, "Unable to create request cache using configuration settings.", e);
            this.requestCacheConf = core.getDefaultConf(CoreConf.class).Caches.Request;
            this.requestCache = CacheBuilder.from(requestCacheConf).build(requestLoader);
        }

        getLogger().log(DEBUG, "Request cache created.");
    }
}

From source file:com.heliosapm.script.StateService.java

/**
 * Returns the cached compiled script for the passed source code, compiling it if it does not exist
 * @param extension The script extension
 * @param code The source code to get the compiled script for
 * @return the compiled script/*  w w w .  j a va2  s  .co  m*/
 */
public CompiledScript getCompiledScript(final String extension, final String code) {
    if (code == null || code.trim().isEmpty())
        throw new IllegalArgumentException("The passed code was null or empty");
    if (extension == null || extension.trim().isEmpty())
        throw new IllegalArgumentException("The passed extension was null or empty");
    final String key = extension.trim().toLowerCase();
    final Compilable compiler = getCompilerForExtension(key);
    try {
        final Cache<String, CompiledScript> extensionCache = scriptCache.get(key,
                new Callable<Cache<String, CompiledScript>>() {
                    @Override
                    public Cache<String, CompiledScript> call() throws Exception {
                        return CacheBuilder.from(ConfigurationHelper
                                .getSystemThenEnvProperty(STATE_SCRIPT_CACHE_PROP, STATE_CACHE_DEFAULT_SPEC))
                                .build();
                    }
                });
        return extensionCache.get(code, new Callable<CompiledScript>() {
            @Override
            public CompiledScript call() throws Exception {
                return compiler.compile(code);
            }
        });
    } catch (Exception ex) {
        if (ex instanceof ScriptException) {
            throw new RuntimeException("Exception compiling script for [" + code + "]", ex);
        }
        throw new RuntimeException("Unexpected exception getting compiled script for [" + code + "]", ex);
    }
}

From source file:com.heliosapm.streams.admin.nodes.NodeConfigurationServer.java

/**
 * {@inheritDoc}//from w ww  . j  a  va 2 s .  c  o  m
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
@Override
public void afterPropertiesSet() throws Exception {
    configDir = new File(configDirName).getAbsoluteFile();
    appDir = new File(appDirName).getAbsoluteFile();
    if (!configDir.isDirectory())
        throw new IllegalArgumentException("The configuration directory [" + configDirName + "] is invalid");
    if (!appDir.exists()) {
        appDir.mkdirs();
    }
    if (!appDir.isDirectory())
        throw new IllegalArgumentException("The app directory [" + appDirName + "] is invalid");
    log.info("Configuration Directory: [{}]", configDir);
    if (!cacheSpec.contains("recordStats"))
        cacheSpec = cacheSpec + ",recordStats";

    configCache = CacheBuilder.from(cacheSpec).build(configCacheLoader);
    configCacheStats = new CachedGauge<CacheStats>(5, TimeUnit.SECONDS) {
        @Override
        protected CacheStats loadValue() {
            return configCache.stats();
        }
    };
    appJarCache = CacheBuilder.from(cacheSpec).build(appJarCacheLoader);
    appJarCacheStats = new CachedGauge<CacheStats>(5, TimeUnit.SECONDS) {
        @Override
        protected CacheStats loadValue() {
            return appJarCache.stats();
        }
    };

    reloadConfigCache();
    log.info("Loaded [{}] App Configurations", configCache.size());
    reloadAppJarCache();
    log.info("Loaded [{}] App Jar Sets", appJarCache.size());
}

From source file:net.librec.math.structure.SparseMatrix.java

/**
 * create a row cache of a matrix in {row, row-specific columns}
 *
 * @param cacheSpec cache specification/*from ww w .ja  v a2  s  .  c om*/
 * @return a matrix row cache in {row, row-specific columns}
 */
public LoadingCache<Integer, Set<Integer>> rowColumnsSetCache(String cacheSpec) {
    LoadingCache<Integer, Set<Integer>> cache = CacheBuilder.from(cacheSpec)
            .build(new CacheLoader<Integer, Set<Integer>>() {

                @Override
                public Set<Integer> load(Integer rowId) throws Exception {
                    return getColumnsSet(rowId);
                }
            });

    return cache;
}

From source file:org.jooby.ftl.Ftl.java

@Override
public void configure(final Env env, final Config config, final Binder binder) throws TemplateException {
    Configuration freemarker = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    log.debug("Freemarker: {}", Configuration.getVersion());
    freemarker.setSettings(properties(config));
    freemarker.setTemplateLoader(new ClassTemplateLoader(getClass().getClassLoader(), prefix));

    // cache/*  ww w .  j av a 2  s.co  m*/
    if ("dev".equals(env.name()) || config.getString("freemarker.cache").isEmpty()) {
        // noop cache
        freemarker.setCacheStorage(NullCacheStorage.INSTANCE);
    } else {
        freemarker.setCacheStorage(
                new GuavaCacheStorage(CacheBuilder.from(config.getString("freemarker.cache")).build()));
    }

    freemarker.setOutputFormat(HTMLOutputFormat.INSTANCE);

    if (configurer != null) {
        configurer.accept(freemarker, config);
    }

    binder.bind(Configuration.class).toInstance(freemarker);

    Engine engine = new Engine(freemarker, suffix, new XssDirective(env));

    Multibinder.newSetBinder(binder, Renderer.class).addBinding().toInstance(engine);
}

From source file:org.jooby.guava.GuavaCache.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   w w w  . j a v a 2 s. com*/
public void configure(final Env env, final Config conf, final Binder binder) {
    Config gconf = conf.hasPath(name) ? conf : ConfigFactory.empty();

    gconf = gconf
            .withFallback(ConfigFactory.empty().withValue("guava.cache", ConfigValueFactory.fromAnyRef("")));

    gconf.getObject(name).unwrapped().forEach((name, spec) -> {
        CacheBuilder<K, V> cb = (CacheBuilder<K, V>) CacheBuilder.from(toSpec(spec));

        Cache<K, V> cache = callback.apply(name, cb);

        List<TypeLiteral> types = cacheType(name, cache, getClass().getGenericSuperclass());

        types.forEach(type -> {
            binder.bind(Key.get(type, Names.named(name))).toInstance(cache);
            if (name.equals("cache")) {
                // unnamed cache for default cache
                binder.bind(type).toInstance(cache);
                // raw type for default cache
                binder.bind(type.getRawType()).toInstance(cache);
            }
            if (name.equals("session")) {
                binder.bind(Key.get(type, Names.named(name))).toInstance(cache);
                binder.bind(Key.get(type.getRawType(), Names.named(name))).toInstance(cache);
            }
        });
    });
}