类com.google.common.cache.CacheLoader源码实例Demo

下面列出了怎么用com.google.common.cache.CacheLoader的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: registry   文件: ClassLoaderCache.java
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();
}
 
源代码2 项目: qmq   文件: DbDicService.java
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 "";
                    }
                }
            });
}
 
源代码3 项目: registry   文件: AbstractSnapshotDeserializer.java
@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);
                    }
                }
            });
}
 
源代码4 项目: 07kit   文件: PriceLookup.java
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<>();
	}
}
 
源代码5 项目: buck   文件: SkylarkRuleContextAttr.java
/**
 * @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);
                }
              });
}
 
源代码6 项目: usergrid   文件: ApplicationIdCacheImpl.java
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;
            }
        });
}
 
源代码7 项目: hermes   文件: PageCacheBuilder.java
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);
		      }

	      });
}
 
源代码8 项目: presto   文件: ThriftHiveMetastore.java
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));
}
 
源代码9 项目: uSkyBlock   文件: ChallengeCompletionLogic.java
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();
    }
}
 
源代码10 项目: fullstop   文件: ScmSourceProviderImpl.java
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;
        }
    });
}
 
源代码11 项目: buck   文件: AppleDependenciesCache.java
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());
                  }));
}
 
源代码12 项目: conductor   文件: ZookeeperLock.java
@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 + "/");
}
 
源代码13 项目: digdag   文件: ArchiveManager.java
@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);
}
 
源代码14 项目: emodb   文件: AmazonS3Provider.java
@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();
}
 
源代码15 项目: git-as-svn   文件: GitLabAccess.java
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);
            }
          }
      );
}
 
源代码16 项目: neural   文件: StandAloneLimiter.java
@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;
}
 
源代码17 项目: calcite   文件: DruidSchema.java
@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;
}
 
源代码18 项目: atomix   文件: CachingAsyncLeaderElector.java
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);
}
 
源代码19 项目: DataLink   文件: TaskWriter.java
/**
 * 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;
        }
    });
}
 
源代码20 项目: atomix   文件: CachingAsyncAtomicMap.java
/**
 * Constructor to configure cache size.
 *
 * @param backingMap  a distributed, strongly consistent map for backing
 * @param cacheConfig the cache configuration
 */
public CachingAsyncAtomicMap(AsyncAtomicMap<K, V> backingMap, CacheConfig cacheConfig) {
  super(backingMap);
  this.backingMap = backingMap;
  cache = CacheBuilder.newBuilder()
      .maximumSize(cacheConfig.getSize())
      .build(CacheLoader.from(CachingAsyncAtomicMap.super::get));
  cacheUpdater = event -> {
    Versioned<V> newValue = event.newValue();
    if (newValue == null) {
      cache.invalidate(event.key());
    } else {
      cache.put(event.key(), CompletableFuture.completedFuture(newValue));
    }
    mapEventListeners.forEach((listener, executor) -> executor.execute(() -> listener.event(event)));
  };
  statusListener = status -> {
    log.debug("{} status changed to {}", this.name(), status);
    // If the status of the underlying map is SUSPENDED or INACTIVE
    // we can no longer guarantee that the cache will be in sync.
    if (status == PrimitiveState.SUSPENDED || status == PrimitiveState.CLOSED) {
      cache.invalidateAll();
    }
  };
  super.addListener(cacheUpdater, MoreExecutors.directExecutor());
  super.addStateChangeListener(statusListener);
}
 
源代码21 项目: act-platform   文件: FactManager.java
private LoadingCache<String, FactTypeEntity> createFactTypeByNameCache() {
  return CacheBuilder.newBuilder()
          .expireAfterAccess(10, TimeUnit.MINUTES)
          .build(new CacheLoader<String, FactTypeEntity>() {
            @Override
            public FactTypeEntity load(String key) throws Exception {
              return ObjectUtils.notNull(factTypeDao.get(key), new Exception(String.format("FactType with name = %s does not exist.", key)));
            }
          });
}
 
源代码22 项目: act-platform   文件: ObjectManager.java
private LoadingCache<String, ObjectTypeEntity> createObjectTypeByNameCache() {
  return CacheBuilder.newBuilder()
          .expireAfterAccess(10, TimeUnit.MINUTES)
          .build(new CacheLoader<String, ObjectTypeEntity>() {
            @Override
            public ObjectTypeEntity load(String key) throws Exception {
              return ObjectUtils.notNull(objectTypeDao.get(key), new Exception(String.format("ObjectType with name = %s does not exist.", key)));
            }
          });
}
 
源代码23 项目: tac-kbp-eal   文件: CorpusQueryExecutor2016.java
/**
 * The default query matching strategy for the 2016 evaluation.
 */
public static EREBasedCorpusQueryExecutor createDefaultFor2016(
    final Map<Symbol, File> docIdToEREMap,
    final ERELoader ereLoader, final EREToKBPEventOntologyMapper ontologyMapper,
    int slack, double minNominalCASOverlap,
    boolean requireBestCASType) {
  final LoadingCache<Symbol, EREDocument> ereDocCache = CacheBuilder.newBuilder()
      .maximumSize(50)
      .build(new CacheLoader<Symbol, EREDocument>() {
        @Override
        public EREDocument load(final Symbol docID) throws Exception {
          final File ereFileName = docIdToEREMap.get(docID);
          if (ereFileName != null) {
            return ereLoader.loadFrom(ereFileName);
          } else {
            throw new TACKBPEALException("Cannot find ERE file for " + docID);
          }
        }
      });

  final ResponsePJContainsEntryPJWithSlack commonPJMatchStrategy =
      new ResponsePJContainsEntryPJWithSlack(slack);
  final ImmutableList<AlignmentConfiguration> alignmentConfigs = ImmutableList.of(
      AlignmentConfiguration.of(ExactCASMatch.INSTANCE, commonPJMatchStrategy),
      AlignmentConfiguration.of(QueryNameContainsSystemCAS.INSTANCE, commonPJMatchStrategy),
      AlignmentConfiguration.of(QueryNameContainedBySystemCAS.INSTANCE, commonPJMatchStrategy),
      AlignmentConfiguration.of(
          new NominalsContainOneAnotherWithMinimumOverlap(minNominalCASOverlap),
          commonPJMatchStrategy));

  return new EREBasedCorpusQueryExecutor(alignmentConfigs, ereDocCache, ontologyMapper,
      requireBestCASType);
}
 
源代码24 项目: quilt   文件: JwtHs256BearerTokenSupplier.java
/**
 * Required-args Constructor.
 *
 * @param sharedSecretBytesSupplier A {@link SharedSecretBytesSupplier} that returns a copy of the shared secret used
 *                                  to sign JWTs using the HS_256 algorithm.
 * @param outgoingLinkSettings      A {@link OutgoingLinkSettings} that contains all settings required to construct a
 *                                  bearer token that can auth an outgoing request.
 */
public JwtHs256BearerTokenSupplier(
    final SharedSecretBytesSupplier sharedSecretBytesSupplier,
    final OutgoingLinkSettings outgoingLinkSettings
) {
  Objects.requireNonNull(sharedSecretBytesSupplier);
  Objects.requireNonNull(outgoingLinkSettings);

  this.outgoingLinkSettings = Objects.requireNonNull(outgoingLinkSettings);

  ilpOverHttpAuthTokens = CacheBuilder.newBuilder()
      // There should only ever be 1 or 2 tokens in-memory for a given client instance.
      .maximumSize(3)
      // Expire after this duration, which will correspond to the last incoming request from the peer.
      .expireAfterAccess(getExpiryInMinutes(Duration.of(30, ChronoUnit.MINUTES)).toMinutes(), TimeUnit.MINUTES)
      .removalListener((RemovalListener<String, String>) notification ->
          logger.debug("Removing IlpOverHttp AuthToken from Cache for Principal: {}", notification.getKey())
      )
      .build(new CacheLoader<String, String>() {
        public String load(final String authSubject) {
          Objects.requireNonNull(authSubject);

          final byte[] sharedSecretBytes = sharedSecretBytesSupplier.get();
          try {
            return JWT.create()
                .withSubject(outgoingLinkSettings.jwtAuthSettings().get().tokenSubject()) // account identifier at the remote server.
                // Expire at the appointed time, or else after 15 minutes.
                .withExpiresAt(
                    Date.from(DateUtils.now().plus(getExpiryInMinutes(Duration.of(15, ChronoUnit.MINUTES))))
                )
                .sign(Algorithm.HMAC256(sharedSecretBytes));
          } finally {
            // Zero-out all bytes in the `sharedSecretBytes` array.
            Arrays.fill(sharedSecretBytes, (byte) 0);
          }
        }
      });
}
 
源代码25 项目: styx   文件: Caches.java
/**
 * Creates a LoadingCache with default settings.
 *
 * @param loadingFunction loading function
 * @param <K> key type
 * @param <V> value type
 * @return loading cache
 */
public static <K, V> LoadingCache<K, V> cache(Function<K, V> loadingFunction) {
    return CacheBuilder.newBuilder()
            .build(new CacheLoader<K, V>() {
                @Override
                public V load(K key) throws Exception {
                    return loadingFunction.apply(key);
                }
            });
}
 
源代码26 项目: flowable-engine   文件: UserCacheImpl.java
@PostConstruct
protected void initCache() {
    FlowableCommonAppProperties.Cache cache = properties.getCacheUsers();
    long userCacheMaxSize = cache.getMaxSize();
    long userCacheMaxAge = cache.getMaxAge();

    userCache = CacheBuilder.newBuilder().maximumSize(userCacheMaxSize)
        .expireAfterAccess(userCacheMaxAge, TimeUnit.SECONDS).recordStats().build(new CacheLoader<String, CachedUser>() {

                public CachedUser load(final String userId) throws Exception {
                    User userFromDatabase = null;
                    if (ldapProperties == null || !ldapProperties.isEnabled()) {
                        userFromDatabase = identityService.createUserQuery().userIdIgnoreCase(userId.toLowerCase()).singleResult();
                    } else {
                        userFromDatabase = identityService.createUserQuery().userId(userId).singleResult();
                    }

                    if (userFromDatabase == null) {
                        throw new UsernameNotFoundException("User " + userId + " was not found in the database");
                    }

                    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                    UserInformation userInformation = userService.getUserInformation(userFromDatabase.getId());
                    for (String privilege : userInformation.getPrivileges()) {
                        grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
                    }

                    return new CachedUser(userFromDatabase, grantedAuthorities);
                }

            });
}
 
源代码27 项目: presto   文件: CachingJdbcClient.java
public CachingJdbcClient(JdbcClient delegate, Duration metadataCachingTtl, boolean cacheMissing)
{
    this.delegate = requireNonNull(delegate, "delegate is null");
    this.cacheMissing = cacheMissing;

    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .expireAfterWrite(metadataCachingTtl.toMillis(), TimeUnit.MILLISECONDS);
    schemaNamesCache = cacheBuilder.build(CacheLoader.from(delegate::getSchemaNames));
    tableNamesCache = cacheBuilder.build(CacheLoader.from(key -> delegate.getTableNames(key.identity, key.schemaName)));
    tableHandleCache = cacheBuilder.build(CacheLoader.from(key -> delegate.getTableHandle(key.identity, key.tableName)));

    // TODO use LoadingCache for columns (columns depend on session and session cannot be used in cache key)
    columnsCache = cacheBuilder.build();
}
 
源代码28 项目: GraceKelly   文件: GuavaCacheProvider.java
public GuavaCacheProvider(long maximumSize) {
  this.cache = CacheBuilder.newBuilder()
      .maximumSize(maximumSize)
      .build(
          new CacheLoader<String, CacheEntry<T>>() {
            @Override
            public CacheEntry<T> load(String s) throws Exception {
              return null;
            }
          }
      );
}
 
源代码29 项目: j2cl   文件: FileCache.java
public FileCache(FileFunction<T> fn, int cacheSize, int parallelism) {
  this.fn = fn;
  this.cache =
      CacheBuilder.newBuilder()
          .maximumSize(cacheSize)
          .concurrencyLevel(parallelism)
          .build(CacheLoader.from(CachedFile::new));
}
 
源代码30 项目: canal   文件: MigrateMap.java
public static <K, V> ConcurrentMap<K, V> makeComputingMap(CacheBuilder<Object, Object> builder,
                                                          Function<? super K, ? extends V> computingFunction) {
    final Function<? super K, ? extends V> function = computingFunction;
    LoadingCache<K, V> computingCache = builder.build(new CacheLoader<K, V>() {

        @Override
        public V load(K key) throws Exception {
            return function.apply(key);
        }
    });

    return new MigrateConcurrentMap<K, V>(computingCache);
}