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

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

Introduction

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

Prototype

public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(CacheLoader<? super K1, V1> loader) 

Source Link

Document

Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied CacheLoader .

Usage

From source file:org.restheart.cache.impl.GuavaLoadingCache.java

public GuavaLoadingCache(long size, EXPIRE_POLICY expirePolicy, long ttl, Function<K, V> loader) {
    CacheBuilder builder = CacheBuilder.newBuilder();

    builder.maximumSize(size);/*from  w ww .  j  av a2s .c  o m*/

    if (ttl > 0 && expirePolicy == EXPIRE_POLICY.AFTER_WRITE) {
        builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    } else if (ttl > 0 && expirePolicy == EXPIRE_POLICY.AFTER_READ) {
        builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    }

    wrapped = builder.build(new CacheLoader<K, Optional<V>>() {
        @Override
        public Optional<V> load(K key) throws Exception {
            return Optional.ofNullable(loader.apply(key));
        }
    });
}

From source file:com.davidbracewell.cache.impl.GuavaLoadingCache.java

public GuavaLoadingCache(CacheSpec<K, V> specification) {
    super(Preconditions.checkNotNull(specification));
    Preconditions.checkNotNull(specification.getFunction());
    CacheBuilder<K, V> cacheBuilder = GuavaCacheUtils.cacheBuilderFromSpec(specification);
    CacheLoader<K, V> loader = new CacheLoader<K, V>() {
        @Override/*from  w w w .  j a  v a 2s.  com*/
        public V load(K key) throws Exception {
            return function.apply(key);
        }
    };
    if (specification.getRemovalListener() == null) {
        this.cache = cacheBuilder.build(loader);
    } else {
        this.cache = cacheBuilder.removalListener(specification.getRemovalListener()).build(loader);
    }
}

From source file:com.softinstigate.restheart.handlers.injectors.LocalCachesSingleton.java

private void setup() {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }//from w  w  w  .  j  a  v  a2 s .c  om

    CacheBuilder builder = CacheBuilder.newBuilder();

    builder.maximumSize(maxCacheSize);

    if (ttl > 0) {
        builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    }

    if (enabled) {
        this.dbPropsCache = builder.build(new CacheLoader<String, Optional<DBObject>>() {
            @Override
            public Optional<DBObject> load(String key) throws Exception {
                return Optional.ofNullable(DBDAO.getDbProps(key));
            }
        });

        this.collectionPropsCache = builder.build(new CacheLoader<String, Optional<DBObject>>() {
            @Override
            public Optional<DBObject> load(String key) throws Exception {
                String[] dbNameAndCollectionName = key.split(SEPARATOR);
                return Optional.ofNullable(CollectionDAO.getCollectionProps(dbNameAndCollectionName[0],
                        dbNameAndCollectionName[1]));
            }
        });
    }
}

From source file:org.apache.nifi.processors.standard.TransformXml.java

@OnScheduled
public void onScheduled(final ProcessContext context) {
    final ComponentLog logger = getLogger();
    final Integer cacheSize = context.getProperty(CACHE_SIZE).asInteger();
    final Long cacheTTL = context.getProperty(CACHE_TTL_AFTER_LAST_ACCESS).asTimePeriod(TimeUnit.SECONDS);

    if (cacheSize > 0) {
        CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(cacheSize);
        if (cacheTTL > 0) {
            cacheBuilder = cacheBuilder.expireAfterAccess(cacheTTL, TimeUnit.SECONDS);
        }/*from   w w w .  ja  v  a2s  .  c o  m*/

        cache = cacheBuilder.build(new CacheLoader<String, Templates>() {
            public Templates load(String path) throws TransformerConfigurationException {
                return newTemplates(path);
            }
        });
    } else {
        cache = null;
        logger.warn("Stylesheet cache disabled because cache size is set to 0");
    }
}

From source file:org.jboss.weld.bean.proxy.ClientProxyProvider.java

/**
 * Constructor/*from  ww w . jav a 2s.  c o m*/
 */
public ClientProxyProvider(String contextId) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    this.CREATE_BEAN_TYPE_CLOSURE_CLIENT_PROXY = new CreateClientProxy();
    this.CREATE_REQUESTED_TYPE_CLOSURE_CLIENT_PROXY = new CreateClientProxyForType();
    this.beanTypeClosureProxyPool = cacheBuilder.build(CREATE_BEAN_TYPE_CLOSURE_CLIENT_PROXY);
    this.requestedTypeClosureProxyPool = cacheBuilder.build(CREATE_REQUESTED_TYPE_CLOSURE_CLIENT_PROXY);
    this.contextId = contextId;
}

From source file:com.streamsets.pipeline.stage.processor.kudulookup.KuduLookupLoader.java

public KuduLookupLoader(Stage.Context context, AsyncKuduClient kuduClient, List<String> keyColumns,
        Map<String, String> columnToField, KuduLookupConfig conf) {
    this.selectMeter = context.createMeter("Select Queries");
    this.selectTimer = context.createTimer("Select Queries");
    this.kuduClient = kuduClient;
    this.keyColumns = keyColumns;
    this.columnToField = columnToField;
    this.conf = conf;

    // output fields
    for (KuduOutputColumnMapping columnConfig : conf.outputColumnMapping) {
        String columnName = conf.caseSensitive ? columnConfig.columnName
                : columnConfig.columnName.toLowerCase();
        projectColumns.add(columnName);/* w  w  w.  j  a v a  2  s.c  o m*/
        outputColumnToField.put(columnName, columnConfig.field);
        outputDefault.put(columnName, columnConfig.defaultValue);
    }
    // Build table cache.
    CacheBuilder cacheBuilder;
    if (conf.enableTableCache) {
        cacheBuilder = CacheBuilder.newBuilder().maximumSize(0);
    } else {
        cacheBuilder = CacheBuilder.newBuilder().maximumSize(conf.cacheSize);
    }

    tableCache = cacheBuilder.build(new CacheLoader<String, KuduTable>() {
        @Override
        public KuduTable load(String tableName) throws Exception {
            return kuduClient.openTable(tableName).join();
        }
    });
}

From source file:org.apache.nifi.processors.automna.Parser.java

@OnScheduled
public void onScheduled(final ProcessContext context) {
    final ComponentLog logger = getLogger();

    if (CACHE_SIZE > 0) {
        CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(CACHE_SIZE);
        if (CACHE_TTL_AFTER_LAST_ACCESS > 0) {
            cacheBuilder = cacheBuilder.expireAfterAccess(CACHE_TTL_AFTER_LAST_ACCESS, TimeUnit.SECONDS);
        }//ww w.  j  a v a 2 s .  c  om

        cache = cacheBuilder.build(new CacheLoader<String, Templates>() {
            public Templates load(String path) throws TransformerConfigurationException {
                return newTemplates(path);
            }
        });
    } else {
        cache = null;
        logger.warn("Stylesheet cache disabled because cache size is set to 0");
    }
}

From source file:com.streamsets.pipeline.stage.bigquery.destination.BigQueryTarget.java

@Override
@SuppressWarnings("unchecked")
public List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();

    conf.credentials.getCredentialsProvider(getContext(), issues).ifPresent(provider -> {
        if (issues.isEmpty()) {
            try {
                Optional.ofNullable(provider.getCredentials())
                        .ifPresent(c -> bigQuery = BigQueryDelegate.getBigquery(c, conf.credentials.projectId));
            } catch (IOException e) {
                LOG.error(Errors.BIGQUERY_05.getMessage(), e);
                issues.add(getContext().createConfigIssue(Groups.CREDENTIALS.name(),
                        "conf.credentials.credentialsProvider", Errors.BIGQUERY_05));
            }//w  w w .j  a v a 2  s . c  o  m
        }
    });

    dataSetEval = getContext().createELEval("datasetEL");
    tableNameELEval = getContext().createELEval("tableNameEL");
    rowIdELEval = getContext().createELEval("rowIdExpression");

    CacheBuilder tableIdExistsCacheBuilder = CacheBuilder.newBuilder();
    if (conf.maxCacheSize != -1) {
        tableIdExistsCacheBuilder.maximumSize(conf.maxCacheSize);
    }

    tableIdExistsCache = tableIdExistsCacheBuilder.build(new CacheLoader<TableId, Boolean>() {
        @Override
        public Boolean load(TableId key) throws Exception {
            return bigQuery.getTable(key) != null;
        }
    });

    return issues;
}

From source file:org.jpmml.evaluator.ModelEvaluatorCache.java

public ModelEvaluatorCache(ModelEvaluatorFactory modelEvaluatorFactory,
        CacheBuilder<Object, Object> cacheBuilder) {
    setModelEvaluatorFactory(modelEvaluatorFactory);

    CacheLoader<URI, ModelEvaluator<?>> cacheLoader = new CacheLoader<URI, ModelEvaluator<?>>() {

        @Override//ww  w .j  a  va  2 s. c  o  m
        public ModelEvaluator<?> load(URI uri) throws Exception {
            return ModelEvaluatorCache.this.loadModelEvaluator(uri);
        }
    };

    this.cache = cacheBuilder.build(cacheLoader);
}

From source file:org.jpmml.runtime.ModelManagerCache.java

public ModelManagerCache(ModelManagerFactory modelManagerFactory, CacheBuilder<Object, Object> cacheBuilder) {
    setModelEvaluatorFactory(modelManagerFactory);

    CacheLoader<Class<?>, ModelManager<? extends Model>> cacheLoader = new CacheLoader<Class<?>, ModelManager<? extends Model>>() {

        @Override// w w w .j ava2 s.  c o  m
        public ModelManager<? extends Model> load(Class<?> clazz) throws Exception {
            return ModelManagerCache.this.loadModelManager(clazz);
        }
    };

    this.cache = cacheBuilder.build(cacheLoader);
}