com.google.common.cache.CacheLoader Java Examples
The following examples show how to use
com.google.common.cache.CacheLoader.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitLabAccess.java From git-as-svn with GNU General Public License v2.0 | 7 votes |
GitLabAccess(@NotNull LocalContext local, @NotNull GitLabMappingConfig config, int projectId) { this.environment = Collections.singletonMap("GL_REPOSITORY", String.format("project-%s", projectId)); final GitLabContext context = GitLabContext.sure(local.getShared()); this.cache = CacheBuilder.newBuilder() .maximumSize(config.getCacheMaximumSize()) .expireAfterWrite(config.getCacheTimeSec(), TimeUnit.SECONDS) .build( new CacheLoader<String, GitlabProject>() { @Override public GitlabProject load(@NotNull String userId) throws Exception { if (userId.isEmpty()) return GitlabAPI.connect(context.getGitLabUrl(), null).getProject(projectId); final GitlabAPI api = context.connect(); final String tailUrl = GitlabProject.URL + "/" + projectId + "?sudo=" + userId; return api.retrieve().to(tailUrl, GitlabProject.class); } } ); }
Example #2
Source File: DbDicService.java From qmq with Apache License 2.0 | 6 votes |
public DbDicService(DicStore dicStore, String pattern) { this.dicStore = dicStore; this.pattern = pattern; this.name2IdCache = CacheBuilder.newBuilder() .maximumSize(MAX_SIZE).expireAfterAccess(1, TimeUnit.DAYS) .build(new CacheLoader<String, String>() { @Override public String load(String key) { try { return getOrCreateId(key); } catch (EmptyResultDataAccessException e) { return ""; } } }); }
Example #3
Source File: ThriftHiveMetastore.java From presto with Apache License 2.0 | 6 votes |
public ThriftHiveMetastore(MetastoreLocator metastoreLocator, HiveConfig hiveConfig, ThriftMetastoreConfig thriftConfig, HdfsEnvironment hdfsEnvironment, boolean authenticationEnabled) { this.hdfsContext = new HdfsContext(ConnectorIdentity.ofUser(DEFAULT_METASTORE_USER)); this.clientProvider = requireNonNull(metastoreLocator, "metastoreLocator is null"); this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.backoffScaleFactor = thriftConfig.getBackoffScaleFactor(); this.minBackoffDelay = thriftConfig.getMinBackoffDelay(); this.maxBackoffDelay = thriftConfig.getMaxBackoffDelay(); this.maxRetryTime = thriftConfig.getMaxRetryTime(); this.maxRetries = thriftConfig.getMaxRetries(); this.impersonationEnabled = thriftConfig.isImpersonationEnabled(); this.deleteFilesOnDrop = thriftConfig.isDeleteFilesOnDrop(); this.translateHiveViews = hiveConfig.isTranslateHiveViews(); this.maxWaitForLock = thriftConfig.getMaxWaitForTransactionLock(); this.authenticationEnabled = authenticationEnabled; this.delegationTokenCache = CacheBuilder.newBuilder() .expireAfterWrite(thriftConfig.getDelegationTokenCacheTtl().toMillis(), MILLISECONDS) .maximumSize(thriftConfig.getDelegationTokenCacheMaximumSize()) .build(CacheLoader.from(this::loadDelegationToken)); }
Example #4
Source File: PriceLookup.java From 07kit with GNU General Public License v3.0 | 6 votes |
public static List<PriceInfo> search(String term, int limit) { try { Request request = Request.Get(API_URL + "search?term=" + URLEncoder.encode(term, "UTF-8") + "&limit=" + limit); request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken()); HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse(); if (response != null) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { byte[] bytes = EntityUtils.toByteArray(response.getEntity()); return GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE); } } return new ArrayList<>(); } catch (IOException | CacheLoader.InvalidCacheLoadException e) { e.printStackTrace(); return new ArrayList<>(); } }
Example #5
Source File: ChallengeCompletionLogic.java From uSkyBlock with GNU General Public License v3.0 | 6 votes |
public ChallengeCompletionLogic(uSkyBlock plugin, FileConfiguration config) { this.plugin = plugin; storeOnIsland = config.getString("challengeSharing", "island").equalsIgnoreCase("island"); completionCache = CacheBuilder .from(plugin.getConfig().getString("options.advanced.completionCache", "maximumSize=200,expireAfterWrite=15m,expireAfterAccess=10m")) .removalListener(new RemovalListener<String, Map<String, ChallengeCompletion>>() { @Override public void onRemoval(RemovalNotification<String, Map<String, ChallengeCompletion>> removal) { saveToFile(removal.getKey(), removal.getValue()); } }) .build(new CacheLoader<String, Map<String, ChallengeCompletion>>() { @Override public Map<String, ChallengeCompletion> load(String id) throws Exception { return loadFromFile(id); } } ); storageFolder = new File(plugin.getDataFolder(), "completion"); if (!storageFolder.exists() || !storageFolder.isDirectory()) { storageFolder.mkdirs(); } }
Example #6
Source File: DruidSchema.java From calcite with Apache License 2.0 | 6 votes |
@Override protected Map<String, Table> getTableMap() { if (!discoverTables) { return ImmutableMap.of(); } if (tableMap == null) { final DruidConnectionImpl connection = new DruidConnectionImpl(url, coordinatorUrl); Set<String> tableNames = connection.tableNames(); tableMap = Maps.asMap( ImmutableSet.copyOf(tableNames), CacheBuilder.newBuilder() .build(CacheLoader.from(name -> table(name, connection)))); } return tableMap; }
Example #7
Source File: StandAloneLimiter.java From neural with MIT License | 6 votes |
@Override protected boolean tryRefresh(LimiterConfig config) { // rate limiter this.rateLimiter = AdjustableRateLimiter.create(config.getRate().getMaxRate()); // concurrent limiter this.semaphore = new AdjustableSemaphore(config.getConcurrent().getMaxPermit(), true); // counter limiter // request limiter CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); cacheBuilder.expireAfterWrite(config.getCounter().getTimeout(), TimeUnit.MILLISECONDS); this.counter = cacheBuilder.build(CacheLoader.from(() -> new AtomicLong(0))); // the refresh rateLimiter rateLimiter.setRate(config.getRate().getRateUnit()); // the refresh semaphore semaphore.setMaxPermits(config.getConcurrent().getMaxPermit()); return true; }
Example #8
Source File: SkylarkRuleContextAttr.java From buck with Apache License 2.0 | 6 votes |
/** * @param methodName the name of the implementation method in the extension file * @param methodParameters a mapping of field names to values for a given rule * @param attributes a mapping of field names to attributes for a given rule * com.facebook.buck.core.artifact.Artifact}s * @param context mapping of build targets to {@link ProviderInfoCollection} for rules that this * rule */ private SkylarkRuleContextAttr( String methodName, Map<String, Object> methodParameters, Map<String, Attribute<?>> attributes, RuleAnalysisContext context) { this.methodName = methodName; this.attributes = attributes; this.postCoercionTransformValues = CacheBuilder.newBuilder() .build( new CacheLoader<String, Object>() { @Override public Object load(String paramName) { Object coercedValue = Preconditions.checkNotNull(methodParameters.get(paramName)); return Preconditions.checkNotNull(attributes.get(paramName)) .getPostCoercionTransform() .postCoercionTransform(coercedValue, context); } }); }
Example #9
Source File: ScmSourceProviderImpl.java From fullstop with Apache License 2.0 | 6 votes |
public ScmSourceProviderImpl(final Function<String, PieroneOperations> pieroneOperationsProvider) { this.pieroneOperationsProvider = pieroneOperationsProvider; this.cache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterAccess(5, MINUTES) .build(new CacheLoader<String, Optional<Map<String, String>>>() { @Override public Optional<Map<String, String>> load(@Nonnull final String source) throws Exception { final Optional<Map<String, String>> result = scmSourceFor(source); if (!result.isPresent()) { log.warn("Could not find scm source '{}' in Pierone", source); } return result; } }); }
Example #10
Source File: AppleDependenciesCache.java From buck with Apache License 2.0 | 6 votes |
public AppleDependenciesCache(TargetGraph projectGraph) { this.depsCache = CacheBuilder.newBuilder() .build( CacheLoader.from( node -> { ImmutableSortedSet.Builder<TargetNode<?>> defaultDepsBuilder = ImmutableSortedSet.naturalOrder(); ImmutableSortedSet.Builder<TargetNode<?>> exportedDepsBuilder = ImmutableSortedSet.naturalOrder(); AppleBuildRules.addDirectAndExportedDeps( projectGraph, node, defaultDepsBuilder, exportedDepsBuilder, Optional.empty()); return new CacheItem(defaultDepsBuilder.build(), exportedDepsBuilder.build()); })); }
Example #11
Source File: ApplicationIdCacheImpl.java From usergrid with Apache License 2.0 | 6 votes |
public ApplicationIdCacheImpl( final EntityManager managementEnityManager, ManagerCache managerCache, ApplicationIdCacheFig fig) { this.managementEnityManager = managementEnityManager; this.managerCache = managerCache; appCache = CacheBuilder.newBuilder() .maximumSize(fig.getCacheSize()) .expireAfterWrite(fig.getCacheTimeout(), TimeUnit.MILLISECONDS) .build(new CacheLoader<String, UUID>() { @Override public UUID load(final String key) throws Exception { UUID appId = fetchApplicationId(key); if ( appId == null ) { throw new PersistenceException("Error getting applicationId"); } return appId; } }); }
Example #12
Source File: PageCacheBuilder.java From hermes with Apache License 2.0 | 6 votes |
private LoadingCache<Long, Page<T>> buildCache(int size) { return CacheBuilder.newBuilder().concurrencyLevel(1).initialCapacity(size).maximumSize(size) .removalListener(new RemovalListener<Long, Page<T>>() { @Override public void onRemoval(RemovalNotification<Long, Page<T>> notification) { m_recentlyExpiredPagesCache.get().put(notification.getKey(), true); } }).build(new CacheLoader<Long, Page<T>>() { @Override public Page<T> load(Long pageNo) throws Exception { return new Page<>(pageNo, m_pageSize, m_pageLoadIntervalMillis); } }); }
Example #13
Source File: AbstractSnapshotDeserializer.java From registry with Apache License 2.0 | 6 votes |
@Override protected void doInit(Map<String, ?> config) { schemaCache = CacheBuilder.newBuilder() .maximumSize(getCacheMaxSize(config)) .expireAfterAccess(getCacheExpiryInSecs(config), TimeUnit.SECONDS) .build(new CacheLoader<SchemaVersionKey, S>() { @Override public S load(SchemaVersionKey schemaVersionKey) { try { return getParsedSchema(schemaVersionKey); } catch (SchemaNotFoundException | InvalidSchemaException e) { throw new RegistryException(e); } } }); }
Example #14
Source File: ClassLoaderCache.java From registry with Apache License 2.0 | 6 votes |
public ClassLoaderCache(final SchemaRegistryClient schemaRegistryClient) { this.schemaRegistryClient = schemaRegistryClient; CacheLoader<String, ClassLoader> cacheLoader = new CacheLoader<String, ClassLoader>() { @Override public ClassLoader load(String fileId) throws Exception { File file = getFile(fileId); return new URLClassLoader(new URL[]{file.toURI().toURL()}); } }; SchemaRegistryClient.Configuration configuration = schemaRegistryClient.getConfiguration(); loadingCache = CacheBuilder.newBuilder() .maximumSize(((Number) configuration.getValue(CACHE_SIZE_KEY)).longValue()) .expireAfterAccess(((Number) configuration.getValue(CACHE_EXPIRY_INTERVAL_KEY)).longValue(), TimeUnit.SECONDS) .build(cacheLoader); localJarsDir = new File((String) this.schemaRegistryClient.getConfiguration().getValue(SchemaRegistryClient.Configuration.LOCAL_JAR_PATH.name())); ensureLocalDirsExist(); }
Example #15
Source File: CachingAsyncLeaderElector.java From atomix with Apache License 2.0 | 6 votes |
public CachingAsyncLeaderElector(AsyncLeaderElector<T> delegateLeaderElector, CacheConfig cacheConfig) { super(delegateLeaderElector); cache = CacheBuilder.newBuilder() .maximumSize(cacheConfig.getSize()) .build(CacheLoader.from(super::getLeadership)); cacheUpdater = event -> { Leadership<T> leadership = event.newLeadership(); cache.put(event.topic(), CompletableFuture.completedFuture(leadership)); }; statusListener = status -> { if (status == PrimitiveState.SUSPENDED || status == PrimitiveState.CLOSED) { cache.invalidateAll(); } }; addListener(cacheUpdater); addStateChangeListener(statusListener); }
Example #16
Source File: ZookeeperLock.java From conductor with Apache License 2.0 | 6 votes |
@Inject public ZookeeperLock(ZookeeperConfiguration config) { LOCK_NAMESPACE = config.getProperty("workflow.decider.locking.namespace", ""); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); client = CuratorFrameworkFactory.newClient( config.getZkConnection(), config.getZkSessiontimeoutMs(), config.getZkConnectiontimeoutMs(), retryPolicy ); client.start(); zkLocks = CacheBuilder.newBuilder() .maximumSize(CACHE_MAXSIZE) .expireAfterAccess(CACHE_EXPIRY_TIME, TimeUnit.MINUTES) .build(new CacheLoader<String, InterProcessMutex>() { @Override public InterProcessMutex load(String key) throws Exception { return new InterProcessMutex(client, zkPath.concat(key)); } } ); zkPath = StringUtils.isEmpty(LOCK_NAMESPACE) ? ("/conductor/") : ("/conductor/" + LOCK_NAMESPACE + "/"); }
Example #17
Source File: TaskWriter.java From DataLink with Apache License 2.0 | 6 votes |
/** * Initialize this TaskWriter with the specified context object. */ @SuppressWarnings("unchecked") public void initialize(TaskWriterContext context) { this.context = context; this.parameter = (T) context.getWriterParameter(); this.handlers = CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends Record>, Handler>() { @Override public Handler load(Class<? extends Record> clazz) throws Exception { Handler handler = getHandler(clazz); if (handler == null) { throw new RecordNotSupportException(clazz); } handler.initialize(context); return handler; } }); }
Example #18
Source File: ArchiveManager.java From digdag with Apache License 2.0 | 6 votes |
@Inject public ArchiveManager(StorageManager storageManager, Config systemConfig) { this.storageManager = storageManager; this.storageCache = CacheBuilder.newBuilder() .maximumSize(2) .build( new CacheLoader<ArchiveType, Storage>() { public Storage load(ArchiveType type) { return openStorage(type); } }); this.systemConfig = systemConfig; this.uploadArchiveType = systemConfig.get("archive.type", ArchiveType.class, ArchiveType.DB); this.pathPrefix = getArchivePathPrefix(systemConfig, uploadArchiveType); this.directDownloadEnabled = systemConfig.get("archive." + uploadArchiveType + ".direct_download", Boolean.class, false); }
Example #19
Source File: AmazonS3Provider.java From emodb with Apache License 2.0 | 6 votes |
@VisibleForTesting public AmazonS3Provider(AWSCredentialsProvider credentialsProvider, String localRegionName) { _credentialsProvider = credentialsProvider; _localRegionName = localRegionName; _clientsByRegion = CacheBuilder.newBuilder() .maximumSize(4) .build(new CacheLoader<String, AmazonS3>() { @Override public AmazonS3 load(String regionName) throws Exception { return createS3ClientForRegion(regionName); } }); _clientsByBucket = CacheBuilder.newBuilder() .maximumSize(10) .build(); }
Example #20
Source File: LockCache.java From datacollector with Apache License 2.0 | 5 votes |
@Inject public LockCache() { cache = CacheBuilder.newBuilder().weakValues().build(new CacheLoader<K, Object>() { @Override public Object load(K key) { return new Object(); } }); }
Example #21
Source File: AbstractDbDialect.java From DataLink with Apache License 2.0 | 5 votes |
private void initTables(final JdbcTemplate jdbcTemplate) { this.tables = CacheBuilder.newBuilder().softValues().build(new CacheLoader<List<String>, Table>() { @Override public Table load(List<String> names) throws Exception { Assert.isTrue(names.size() == 2); try { beforeFindTable(jdbcTemplate, names.get(0), names.get(0), names.get(1)); DdlUtilsFilter filter = getDdlUtilsFilter(jdbcTemplate, names.get(0), names.get(0), names.get(1)); Table table = DdlUtils.findTable( jdbcTemplate, getActualSchemaName(names.get(0)), isGetTablesWithSchema() ? getActualSchemaName(names.get(0)) : null, names.get(1), filter); afterFindTable(table, jdbcTemplate, names.get(0), names.get(0), names.get(1)); if (table == null) { throw new NestableRuntimeException("no found table [" + names.get(0) + "." + names.get(1) + "] , pls check"); } else { return table; } } catch (Exception e) { throw new NestableRuntimeException("find table [" + names.get(0) + "." + names.get(1) + "] error", e); } } }); }
Example #22
Source File: RangerPolicyEnginePerformanceTest.java From ranger with Apache License 2.0 | 5 votes |
private static CacheLoader<Integer, ServicePolicies> createServicePoliciesCacheLoader() { return new CacheLoader<Integer, ServicePolicies>() { @Override public ServicePolicies load(Integer numberOfPolicies) throws Exception { return RangerPolicyFactory.createServicePolicy(numberOfPolicies); } }; }
Example #23
Source File: CachedSimilarityMeasure.java From metanome-algorithms with Apache License 2.0 | 5 votes |
private LoadingCache<UnorderedPair<T>, Double> createCache() { CacheLoader<UnorderedPair<T>, Double> loader = CacheLoader .from(similarityMeasure::calculateSimilarity); return CacheBuilder.newBuilder() .maximumSize(maximumSize) .build(loader); }
Example #24
Source File: BufferedSolrInputDocumentWriter.java From hbase-indexer with Apache License 2.0 | 5 votes |
/** * Instantiate with the underlying writer to delegate to, and the size of the internal buffer to use. * * @param delegateWriter underlying writer to delegate writes and deletes to * @param bufferSize size of the internal write buffer to use * @param documentOutputCounter Hadoop counter for recording the number of Solr documents output * @param documentBatchOutputCounter Hadoop counter for recording the number of document batches output */ public BufferedSolrInputDocumentWriter(SolrInputDocumentWriter delegateWriter, int bufferSize, Counter documentOutputCounter, Counter documentBatchOutputCounter) { this.delegateWriter = delegateWriter; this.bufferSize = bufferSize; this.adds = 0; this.writeBuffers = CacheBuilder.newBuilder().build(new CacheLoader<Integer, Map<String, SolrInputDocument>>() { @Override public Map<String, SolrInputDocument> load(Integer key) throws Exception { return new HashMap(BufferedSolrInputDocumentWriter.this.bufferSize); } }); this.docOutputCounter = documentOutputCounter; this.docBatchCounter = documentBatchOutputCounter; }
Example #25
Source File: Writes.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
Writes(Supplier<Instance> instanceSupplier, long writeExpiresAfter, TimeUnit writeExpiresUnit) { this.instanceSupplier = instanceSupplier; blobWriteInstances = CacheBuilder.newBuilder() .expireAfterWrite(writeExpiresAfter, writeExpiresUnit) .build( new CacheLoader<BlobWriteKey, Instance>() { @Override public Instance load(BlobWriteKey key) { return instanceSupplier.get(); } }); }
Example #26
Source File: GlobalEngine.java From tajo with Apache License 2.0 | 5 votes |
private QueryContext createQueryContext(Session session) { QueryContext newQueryContext = new QueryContext(context.getConf(), session); // Set default space uri and its root uri newQueryContext.setDefaultSpaceUri(TablespaceManager.getDefault().getUri()); newQueryContext.setDefaultSpaceRootUri(TablespaceManager.getDefault().getRootUri()); if (TajoConstants.IS_TEST_MODE) { newQueryContext.putAll(CommonTestingUtil.getSessionVarsForTest()); } // Set queryCache in session int queryCacheSize = context.getConf().getIntVar(TajoConf.ConfVars.QUERY_SESSION_QUERY_CACHE_SIZE); if (queryCacheSize > 0 && session.getQueryCache() == null) { Weigher<String, Expr> weighByLength = new Weigher<String, Expr>() { public int weigh(String key, Expr expr) { return key.length(); } }; LoadingCache<String, Expr> cache = CacheBuilder.newBuilder() .maximumWeight(queryCacheSize * 1024) .weigher(weighByLength) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, Expr>() { public Expr load(String sql) throws SQLSyntaxError { return analyzer.parse(sql); } }); session.setQueryCache(cache); } return newQueryContext; }
Example #27
Source File: SimpleHoconConfigTest.java From kite with Apache License 2.0 | 5 votes |
@Test public void testCacheBuilder() throws ExecutionException { LoadingCache<String, Matcher> cache = CacheBuilder.newBuilder() .maximumSize(10) .build( new CacheLoader<String, Matcher>() { public Matcher load(String key) { return Pattern.compile(key).matcher(""); } }); Matcher m = cache.get(".*"); Matcher m2 = cache.get(".*"); }
Example #28
Source File: StaticDatabaseMappingService.java From waggle-dance with Apache License 2.0 | 5 votes |
public StaticDatabaseMappingService( MetaStoreMappingFactory metaStoreMappingFactory, List<AbstractMetaStore> initialMetastores) { this.metaStoreMappingFactory = metaStoreMappingFactory; primaryDatabasesCache = CacheBuilder .newBuilder() .expireAfterAccess(1, TimeUnit.MINUTES) .maximumSize(1) .build(new CacheLoader<String, List<String>>() { @Override public List<String> load(String key) throws Exception { if (primaryDatabaseMapping != null) { return primaryDatabaseMapping.getClient().get_all_databases(); } else { return Lists.newArrayList(); } } }); mappingsByMetaStoreName = Collections.synchronizedMap(new LinkedHashMap<>()); mappingsByDatabaseName = Collections.synchronizedMap(new LinkedHashMap<>()); databaseMappingToDatabaseList = new ConcurrentHashMap<>(); for (AbstractMetaStore federatedMetaStore : initialMetastores) { add(federatedMetaStore); } }
Example #29
Source File: PageLoader.java From TinkerTime with GNU General Public License v3.0 | 5 votes |
public PageLoader(){ System.setProperty("http.agent", "TinkerTime Mod Manager Agent"); cache = CacheBuilder.newBuilder() .expireAfterAccess(CACHING_EXIPIRY_MINUTES, TimeUnit.MINUTES) .build( new CacheLoader<URL, T>() { @Override public T load(URL url) throws IOException { return loadPage(url); } }); }
Example #30
Source File: PremiumList.java From nomulus with Apache License 2.0 | 5 votes |
@VisibleForTesting static LoadingCache<String, PremiumList> createCachePremiumLists(Duration cachePersistDuration) { return CacheBuilder.newBuilder() .expireAfterWrite(cachePersistDuration.getMillis(), MILLISECONDS) .build( new CacheLoader<String, PremiumList>() { @Override public PremiumList load(final String name) { return tm().doTransactionless(() -> loadPremiumList(name)); } }); }