protected Cache getGatewayKeyCache() { String apimGWCacheExpiry = ServiceReferenceHolder.getInstance() .getAPIManagerConfiguration() .getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY); if (!gatewayKeyCacheInit) { gatewayKeyCacheInit = true; if (apimGWCacheExpiry != null) { return APIUtil.getCache( APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.GATEWAY_KEY_CACHE_NAME, Long.parseLong(apimGWCacheExpiry), Long.parseLong(apimGWCacheExpiry)); } else { long defaultCacheTimeout = Long.valueOf( ServerConfiguration.getInstance() .getFirstProperty(APIConstants.DEFAULT_CACHE_TIMEOUT)) * 60; return APIUtil.getCache( APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.GATEWAY_KEY_CACHE_NAME, defaultCacheTimeout, defaultCacheTimeout); } } return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER) .getCache(APIConstants.GATEWAY_KEY_CACHE_NAME); }
/** * Run a task defined by the {@link Runnable} instance with a {@link CachingProvider} making sure * that the caching provider is closed after use. * * @param r task to execute with caching provider */ public static void withCachingProvider(JCacheRunnable r) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); CachingProvider p = Caching.getCachingProvider(new TestClassLoader(tccl)); try { r.run(p); } finally { p.close(); } }
@Bean public JCacheCacheManager cacheManager() { System.out.println("hoge"); CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(); MutableConfiguration<Object, Domain> configuration = new MutableConfiguration<>(); configuration.setExpiryPolicyFactory(new SampleExpiryFactory()); configuration.setStoreByValue(false); cacheManager.createCache("domainCache", configuration); return new JCacheCacheManager(cacheManager); }
private void clearConfigCache() { Cache workflowCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER) .getCache(APIConstants.WORKFLOW_CACHE_NAME); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String cacheName = tenantDomain + "_" + APIConstants.WORKFLOW_CACHE_NAME; if (workflowCache.containsKey(cacheName)) { workflowCache.remove(cacheName); } }
@Test public void testCacheLoader() { final CacheLoader<String, Integer> cacheLoader = new CacheLoader<String, Integer>() { @Override public Integer load(String key) throws CacheLoaderException { return Integer.valueOf(key); } @Override public Map<String, Integer> loadAll(Iterable<? extends String> keys) throws CacheLoaderException { Map<String, Integer> map = new HashMap<>(); for (String key : keys) { map.put(key, Integer.valueOf(key)); } return map; } }; try (CachingProvider cachingProvider = Caching.getCachingProvider(GuavaCachingProvider.class.getName())) { CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<String, Integer> custom = new MutableConfiguration<>(); custom.setStoreByValue(false); custom.setTypes(String.class, Integer.class); custom.setReadThrough(true); custom.setCacheLoaderFactory( new Factory<CacheLoader<String, Integer>>() { @Override public CacheLoader<String, Integer> create() { return cacheLoader; } }); Cache<String, Integer> loadingCache = cacheManager.createCache("loadingCache", custom); assertEquals(Integer.valueOf(1), loadingCache.get("1")); assertEquals(Integer.valueOf(2), loadingCache.get("2")); assertEquals(Integer.valueOf(3), loadingCache.get("3")); Set<String> keys = Sets.newHashSet("4", "5", "6"); Map<String, Integer> map = loadingCache.getAll(keys); assertEquals(3, map.size()); assertEquals(Integer.valueOf(4), map.get("4")); assertEquals(Integer.valueOf(5), map.get("5")); assertEquals(Integer.valueOf(6), map.get("6")); } }
@Test public void testJCacheGettingStarted() { try (CachingProvider provider = Caching.getCachingProvider(); CacheManager manager = provider.getCacheManager(); Cache<String, String> cache = manager.createCache("testCache", new MutableConfiguration<>())) { cache.put("key", "value"); assertThat(cache.get("key")).isEqualTo("value"); cache.remove("key"); assertThat(cache.get("key")).isNull(); } }
@Test public void testWithoutEhcacheExplicitDependencyCanSpecifyXML() throws Exception { // tag::jsr107UsingXMLConfigExample[] CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager manager = cachingProvider.getCacheManager( // <1> getClass().getResource("/org/ehcache/docs/ehcache-jsr107-config.xml").toURI(), // <2> getClass().getClassLoader()); // <3> Cache<Long, Product> readyCache = manager.getCache("ready-cache", Long.class, Product.class); // <4> // end::jsr107UsingXMLConfigExample[] assertThat(readyCache, notNullValue()); }
@Test public void hazelcastAsJCacheWithCaches() { String cachingProviderFqn = HazelcastCachingProvider.class.getName(); try { load( DefaultCacheConfiguration.class, "spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar"); JCacheCacheManager cacheManager = validateCacheManager(JCacheCacheManager.class); assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar")); assertThat(cacheManager.getCacheNames(), hasSize(2)); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); } }
protected Cache getResourceCache() { if (!resourceCacheInit) { resourceCacheInit = true; long defaultCacheTimeout = Long.valueOf( ServerConfiguration.getInstance() .getFirstProperty(APIConstants.DEFAULT_CACHE_TIMEOUT)) * 60; return APIUtil.getCache( APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.RESOURCE_CACHE_NAME, defaultCacheTimeout, defaultCacheTimeout); } return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER) .getCache(APIConstants.RESOURCE_CACHE_NAME); }
@Test public void testCacheExpired() throws Exception { Configuration<String, String> configuration = new MutableConfiguration<String, String>() .setExpiryPolicyFactory( AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 3))); try (CachingProvider provider = Caching.getCachingProvider(); CacheManager manager = provider.getCacheManager(); Cache<String, String> cache = manager.createCache("testCache", configuration)) { cache.put("key1", "value1"); cache.put("key2", "value2"); TimeUnit.SECONDS.sleep(1); cache.get("key2"); TimeUnit.SECONDS.sleep(2); assertThat(cache.get("key1")).isNull(); assertThat(cache.get("key2")).isEqualTo("value2"); } }
@Ignore @Test public void testWithHazelcastConfiguration() throws Exception { // wrong use!! ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URI uri = classLoader.getResource("hazelcast-jcache.xml").toURI(); try (CachingProvider provider = Caching.getCachingProvider(); CacheManager manager = provider.getCacheManager(uri, classLoader); Cache<String, String> cache = manager.getCache("testCache")) { cache.put("key1", "value1"); cache.put("key2", "value2"); TimeUnit.SECONDS.sleep(1); cache.get("key2"); TimeUnit.SECONDS.sleep(2); assertThat(cache.get("key1")).isNull(); assertThat(cache.get("key2")).isEqualTo("value2"); } }
@Test(timeout = 5000L) public void testCacheLoaderAsyncLoadAll() throws InterruptedException { final AtomicInteger loads = new AtomicInteger(); final CacheLoader<String, Integer> cacheLoader = new CacheLoader<String, Integer>() { @Override public Integer load(String key) throws CacheLoaderException { loads.incrementAndGet(); return Integer.valueOf(key); } @Override public Map<String, Integer> loadAll(Iterable<? extends String> keys) throws CacheLoaderException { throw new UnsupportedOperationException("Not supported yet."); } }; final AtomicBoolean completed = new AtomicBoolean(false); final CompletionListener completionListener = new CompletionListener() { @Override public void onCompletion() { completed.set(true); } @Override public void onException(Exception e) { System.err.println(e); } }; try (CachingProvider cachingProvider = Caching.getCachingProvider(GuavaCachingProvider.class.getName())) { CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<String, Integer> custom = new MutableConfiguration<>(); custom.setStoreByValue(false); custom.setTypes(String.class, Integer.class); custom.setReadThrough(true); custom.setCacheLoaderFactory( new Factory<CacheLoader<String, Integer>>() { @Override public CacheLoader<String, Integer> create() { return cacheLoader; } }); Cache<String, Integer> loadingCache = cacheManager.createCache("loadingCache", custom); loadingCache.put("1", 1); loadingCache.put("2", 2); loadingCache.put("3", 3); Set<String> keys = Sets.newHashSet("1", "2", "3", "4", "5", "6"); loadingCache.loadAll(keys, false, completionListener); while (!completed.get()) { Thread.sleep(250); } assertEquals(3, loads.getAndSet(0)); completed.set(false); loadingCache.loadAll(keys, true, completionListener); while (!completed.get()) { Thread.sleep(250); } assertEquals(6, loads.get()); assertEquals(Integer.valueOf(1), loadingCache.getAndRemove("1")); assertEquals(Integer.valueOf(2), loadingCache.getAndRemove("2")); assertEquals(Integer.valueOf(3), loadingCache.getAndRemove("3")); assertEquals(Integer.valueOf(4), loadingCache.getAndRemove("4")); assertEquals(Integer.valueOf(5), loadingCache.getAndRemove("5")); assertEquals(Integer.valueOf(6), loadingCache.getAndRemove("6")); } }
/** {@link DataModelAccessor} implementation based on {@link Cache}. */ public class CacheBasedDataModelAccessor implements DataModelAccessor { private static final Logger log = LoggerFactory.getLogger(CacheBasedDataModelAccessor.class); public static final String DATA_MODEL_TO_ID_CACHE_NAME = "dataModelToIdCache"; public static final String DATA_MODEL_TO_NAME_CACHE_NAME = "dataModelToNameCache"; public static final String DATA_MODELS_FOR_EXECUTION_CACHE_NAME = "dataModelsForExecutionCache"; protected Cache<IDataModelId, IDataModel> dataModelToIdCache = Caching.getCache(DATA_MODEL_TO_ID_CACHE_NAME, IDataModelId.class, IDataModel.class); protected Cache<String, IDataModel> dataModelToNameCache = Caching.getCache(DATA_MODEL_TO_NAME_CACHE_NAME, String.class, IDataModel.class); @Override public void add(IDataModel dataModel) { this.dataModelToIdCache.put(dataModel.getDataModelId(), dataModel); this.dataModelToNameCache.put(dataModel.getName(), dataModel); log.debug("DataModel {} is added to DataModelStorage.", dataModel.getName()); } @Override public void addAll(Collection<IDataModel> dataModels) { dataModels.forEach( dm -> { if (dm == null) { return; } this.dataModelToIdCache.put(dm.getDataModelId(), dm); this.dataModelToNameCache.put(dm.getName(), dm); }); log.debug( "DataModels {} are added to DataModelStorage.", dataModels.stream().map(IDataModel::toString).collect(Collectors.<String>toList())); } @Override public IDataModel get(IDataModelId dataModelId) { return this.dataModelToIdCache.get(dataModelId); } @Override public IDataModel get(String dataModelName) { return this.dataModelToNameCache.get(dataModelName); } @Override public Map<IDataModelId, IDataModel> getAll() { Map<IDataModelId, IDataModel> dms = new HashMap<>(); for (Entry<IDataModelId, IDataModel> entry : this.dataModelToIdCache) { dms.put(entry.getKey(), entry.getValue()); } return Collections.<IDataModelId, IDataModel>unmodifiableMap(dms); } public void setDataModelToIdCache(Cache<IDataModelId, IDataModel> dataModelToIdCache) { this.dataModelToIdCache = dataModelToIdCache; } public void setDataModelToNameCache(Cache<String, IDataModel> dataModelToNameCache) { this.dataModelToNameCache = dataModelToNameCache; } }
protected Cache initCache() { return Caching.getCacheManager("API_MANAGER_CACHE").getCache("keyCache"); // return PrivilegedCarbonContext.getCurrentContext(axisConfig).getCache("keyCache"); }
protected Cache initResourceCache() { return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER) .getCache(APIConstants.RESOURCE_CACHE_NAME); // return PrivilegedCarbonContext.getCurrentContext(axisConfig).getCache("resourceCache"); }
protected CachingProvider getCachingProvider() { return Caching.getCachingProvider(); }
/** * Instantiates a new caching attributes principal factory. * * @param config the config * @param cacheProviderFullClassName the cache provider full class name */ private CachingPrincipalAttributesRepository( final MutableConfiguration<String, Map<String, Object>> config, final String cacheProviderFullClassName) { this(config, Caching.getCachingProvider(cacheProviderFullClassName).getCacheManager()); }
@Before public void setUp() throws Exception { cachingProvider = Caching.getCachingProvider(); cacheManager = cachingProvider.getCacheManager(); }
@Override public void initialize(Class<K> keyClass, Class<T> persistentClass, Properties properties) { super.initialize(keyClass, persistentClass, properties); CachingProvider cachingProvider = Caching.getCachingProvider(properties.getProperty(GORA_DEFAULT_JCACHE_PROVIDER_KEY)); if (properties.getProperty(JCACHE_CACHE_NAMESPACE_PROPERTY_KEY) != null) { goraCacheNamespace = properties.getProperty(JCACHE_CACHE_NAMESPACE_PROPERTY_KEY); } try { this.persistentDataStore = DataStoreFactory.getDataStore(keyClass, persistentClass, new Configuration()); } catch (GoraException ex) { LOG.error("Couldn't initialize persistent DataStore.", ex); } if (properties .getProperty(GORA_DEFAULT_JCACHE_PROVIDER_KEY) .contains(HAZELCAST_SERVER_CACHE_PROVIDER_IDENTIFIER)) { Config config = new ClasspathXmlConfig(properties.getProperty(GORA_DEFAULT_JCACHE_HAZELCAST_CONFIG_KEY)); hazelcastInstance = Hazelcast.newHazelcastInstance(config); } else { try { ClientConfig config = new XmlClientConfigBuilder( properties.getProperty(GORA_DEFAULT_JCACHE_HAZELCAST_CONFIG_KEY)) .build(); hazelcastInstance = HazelcastClient.newHazelcastClient(config); } catch (IOException ex) { LOG.error("Couldn't locate the client side cache provider configuration.", ex); } } Properties providerProperties = new Properties(); providerProperties.setProperty( HazelcastCachingProvider.HAZELCAST_INSTANCE_NAME, hazelcastInstance.getName()); try { manager = cachingProvider.getCacheManager(new URI(goraCacheNamespace), null, providerProperties); } catch (URISyntaxException ex) { LOG.error("Couldn't initialize cache manager to bounded hazelcast instance.", ex); manager = cachingProvider.getCacheManager(); } if (((properties.getProperty(JCACHE_AUTO_CREATE_CACHE_PROPERTY_KEY) != null) && Boolean.valueOf(properties.getProperty(JCACHE_AUTO_CREATE_CACHE_PROPERTY_KEY))) || ((manager.getCache(super.getPersistentClass().getSimpleName(), keyClass, persistentClass) == null))) { cacheEntryList = new ConcurrentSkipListSet<>(); cacheConfig = new CacheConfig<K, T>(); cacheConfig.setTypes(keyClass, persistentClass); if (properties.getProperty(JCACHE_READ_THROUGH_PROPERTY_KEY) != null) { cacheConfig.setReadThrough( Boolean.valueOf(properties.getProperty(JCACHE_READ_THROUGH_PROPERTY_KEY))); } else { cacheConfig.setReadThrough(true); } if (properties.getProperty(JCACHE_WRITE_THROUGH_PROPERTY_KEY) != null) { cacheConfig.setWriteThrough( Boolean.valueOf(properties.getProperty(JCACHE_WRITE_THROUGH_PROPERTY_KEY))); } else { cacheConfig.setWriteThrough(true); } if (properties.getProperty(JCACHE_STORE_BY_VALUE_PROPERTY_KEY) != null) { cacheConfig.setStoreByValue( Boolean.valueOf(properties.getProperty(JCACHE_STORE_BY_VALUE_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_STATISTICS_PROPERTY_KEY) != null) { cacheConfig.setStatisticsEnabled( Boolean.valueOf(properties.getProperty(JCACHE_STATISTICS_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_MANAGEMENT_PROPERTY_KEY) != null) { cacheConfig.setStatisticsEnabled( Boolean.valueOf(properties.getProperty(JCACHE_MANAGEMENT_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EVICTION_POLICY_PROPERTY_KEY) != null) { cacheConfig .getEvictionConfig() .setEvictionPolicy( EvictionPolicy.valueOf( properties.getProperty(JCACHE_EVICTION_POLICY_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EVICTION_MAX_SIZE_POLICY_PROPERTY_KEY) != null) { cacheConfig .getEvictionConfig() .setMaximumSizePolicy( EvictionConfig.MaxSizePolicy.valueOf( properties.getProperty(JCACHE_EVICTION_MAX_SIZE_POLICY_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EVICTION_SIZE_PROPERTY_KEY) != null) { cacheConfig .getEvictionConfig() .setSize(Integer.valueOf(properties.getProperty(JCACHE_EVICTION_SIZE_PROPERTY_KEY))); } if (properties.getProperty(JCACHE_EXPIRE_POLICY_PROPERTY_KEY) != null) { String expiryPolicyIdentifier = properties.getProperty(JCACHE_EXPIRE_POLICY_PROPERTY_KEY); if (expiryPolicyIdentifier.equals(JCACHE_ACCESSED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new AccessedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } else if (expiryPolicyIdentifier.equals(JCACHE_CREATED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new CreatedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } else if (expiryPolicyIdentifier.equals(JCACHE_MODIFIED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new ModifiedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } else if (expiryPolicyIdentifier.equals(JCACHE_TOUCHED_EXPIRY_IDENTIFIER)) { cacheConfig.setExpiryPolicyFactory( FactoryBuilder.factoryOf( new TouchedExpiryPolicy( new Duration( TimeUnit.SECONDS, Integer.valueOf( properties.getProperty( JCACHE_EXPIRE_POLICY_DURATION_PROPERTY_KEY)))))); } } if (properties.getProperty(HAZELCAST_CACHE_IN_MEMORY_FORMAT_PROPERTY_KEY) != null) { String inMemoryFormat = properties.getProperty(HAZELCAST_CACHE_IN_MEMORY_FORMAT_PROPERTY_KEY); if (inMemoryFormat.equals(HAZELCAST_CACHE_BINARY_IN_MEMORY_FORMAT_IDENTIFIER) || inMemoryFormat.equals(HAZELCAST_CACHE_OBJECT_IN_MEMORY_FORMAT_IDENTIFIER) || inMemoryFormat.equals(HAZELCAST_CACHE_NATIVE_IN_MEMORY_FORMAT_IDENTIFIER)) { cacheConfig.setInMemoryFormat(InMemoryFormat.valueOf(inMemoryFormat)); } } cacheConfig.setCacheLoaderFactory( JCacheCacheFactoryBuilder.factoryOfCacheLoader( this.persistentDataStore, keyClass, persistentClass)); cacheConfig.setCacheWriterFactory( JCacheCacheFactoryBuilder.factoryOfCacheWriter( this.persistentDataStore, keyClass, persistentClass)); cache = manager.createCache(persistentClass.getSimpleName(), cacheConfig).unwrap(ICache.class); } else { cache = manager .getCache(super.getPersistentClass().getSimpleName(), keyClass, persistentClass) .unwrap(ICache.class); this.populateLocalCacheEntrySet(cache); } cache.registerCacheEntryListener( new MutableCacheEntryListenerConfiguration<>( JCacheCacheFactoryBuilder.factoryOfEntryListener( new JCacheCacheEntryListener<K, T>(cacheEntryList)), null, true, true)); LOG.info("JCache Gora datastore initialized successfully."); }