Java Examples for net.sf.ehcache.Cache
The following java examples will help you to understand the usage of net.sf.ehcache.Cache. These source code samples are taken from different open source projects.
Example 1
| Project: mybatis-ehcache-spring-master File: MybatisMetricsEhcacheFactory.java View source code |
@Override public Cache getCache(String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } if (!cacheManager.cacheExists(id)) { CacheConfiguration temp = null; if (cacheConfiguration != null) { temp = cacheConfiguration.clone(); } else { // based on defaultCache temp = cacheManager.getConfiguration().getDefaultCacheConfiguration().clone(); } temp.setName(id); net.sf.ehcache.Cache cache = new net.sf.ehcache.Cache(temp); Ehcache instrumentCache = InstrumentedEhcache.instrument(registry, cache); cacheManager.addCache(instrumentCache); } return new EhcacheCache(id, cacheManager.getEhcache(id)); }
Example 2
| Project: AXON-E-Tools-master File: CacheEHCache.java View source code |
public static <I, J> CacheEHCache<I, J> instance(File tmpDir, Realm<I, J> realm, long size) {
CacheConfiguration config = new CacheConfiguration();
config.setName(realm.name());
config.setDiskPersistent(true);
config.setDiskStorePath(tmpDir.getAbsolutePath());
config.setMaxEntriesLocalHeap(size);
CacheManager manager = CacheManager.getInstance();
net.sf.ehcache.Cache newCache = new net.sf.ehcache.Cache(config);
manager.addCacheIfAbsent(newCache);
Status status = newCache.getStatus();
if (status != Status.STATUS_ALIVE) {
throw new IllegalStateException(realm.name() + " is not alive (" + status + ")");
}
return new CacheEHCache<I, J>(realm, newCache);
}Example 3
| Project: shopizer-master File: CacheUtils.java View source code |
public List<String> getCacheKeys(MerchantStore store) throws Exception {
net.sf.ehcache.Cache cacheImpl = (net.sf.ehcache.Cache) cache.getNativeCache();
List<String> returnKeys = new ArrayList<String>();
for (Object key : cacheImpl.getKeys()) {
try {
String sKey = (String) key;
// a key should be <storeId>_<rest of the key>
int delimiterPosition = sKey.indexOf(KEY_DELIMITER);
if (delimiterPosition > 0 && Character.isDigit(sKey.charAt(0))) {
String keyRemaining = sKey.substring(delimiterPosition + 1);
returnKeys.add(keyRemaining);
}
} catch (Exception e) {
LOGGER.equals("key " + key + " cannot be converted to a String or parsed");
}
}
return returnKeys;
}Example 4
| Project: kaleido-repository-master File: EhCacheManagerImpl.java View source code |
/*
* (non-Javadoc)
* @see org.kaleidofoundry.core.cache.CacheFactory#dumpStatistics(java.lang.String)
*/
@Override
public Map<String, Object> dumpStatistics(final String cacheName) {
final Cache<?, ?> cache = getCache(cacheName);
if (cache != null) {
final net.sf.ehcache.Cache ehcache = ((EhCacheImpl<?, ?>) cache).getCache();
final Map<String, Object> lcacheStats = new LinkedHashMap<String, Object>();
lcacheStats.put("CacheSize", ehcache.getSize());
lcacheStats.put("MemoryStoreSize", ehcache.getStatistics().getMemoryStoreObjectCount());
lcacheStats.put("DiskStoreSize", ehcache.getStatistics().getDiskStoreObjectCount());
lcacheStats.put("MemoryHits", ehcache.getStatistics().getInMemoryHits());
lcacheStats.put("DiskHits", ehcache.getStatistics().getOnDiskHits());
return lcacheStats;
} else {
return null;
}
}Example 5
| Project: find-master File: AutoCreatingEhCacheCacheManager.java View source code |
@Override protected Cache getMissingCache(final String name) { final Cache missingCache = super.getMissingCache(name); if (missingCache == null) { final CacheConfiguration cacheConfiguration = defaults.clone().name(name); final String cacheName = getCacheName(name); if (cacheExpires.containsKey(cacheName)) { cacheConfiguration.setTimeToLiveSeconds(cacheExpires.get(cacheName)); } final net.sf.ehcache.Cache ehcache = new net.sf.ehcache.Cache(cacheConfiguration); ehcache.initialise(); return new EhCacheCache(ehcache); } else { return missingCache; } }
Example 6
| Project: OpenLegislation-master File: CacheConfigurationTests.java View source code |
private void getCacheStats() {
/* get stats for all known caches */
StringBuilder sb = new StringBuilder();
for (String name : cacheManager.getCacheNames()) {
Cache cache = cacheManager.getCache(name);
StatisticsGateway stats = cache.getStatistics();
logger.debug(OutputUtils.toJson(stats));
}
}Example 7
| Project: sakai-cle-master File: EhCacheFactoryBean.java View source code |
/** * Create a raw Cache object based on the configuration of this FactoryBean. */ protected Cache createCache() { // Only call EHCache 1.6 constructor if actually necessary (for compatibility with EHCache 1.3+) Cache cache = (!this.clearOnFlush) ? new Cache(this.cacheName, this.maxElementsInMemory, this.memoryStoreEvictionPolicy, this.overflowToDisk, null, this.eternal, this.timeToLive, this.timeToIdle, this.diskPersistent, this.diskExpiryThreadIntervalSeconds, null, this.bootstrapCacheLoader, this.maxElementsOnDisk, this.diskSpoolBufferSize, this.clearOnFlush) : new Cache(this.cacheName, this.maxElementsInMemory, this.memoryStoreEvictionPolicy, this.overflowToDisk, null, this.eternal, this.timeToLive, this.timeToIdle, this.diskPersistent, this.diskExpiryThreadIntervalSeconds, null, this.bootstrapCacheLoader, this.maxElementsOnDisk, this.diskSpoolBufferSize); if (this.cacheEventListeners != null) { for (CacheEventListener listener : this.cacheEventListeners) { cache.getCacheEventNotificationService().registerListener(listener); } } if (this.disabled) { cache.setDisabled(true); } net.sf.ehcache.config.CacheConfiguration config = cache.getCacheConfiguration(); config.setMaxEntriesLocalHeap(maxElementsInMemory); return cache; }
Example 8
| Project: jboss-seam-2.3.0.Final-Hibernate.3-master File: EhCacheProvider.java View source code |
private net.sf.ehcache.Cache getCacheRegion(String regionName) { if (regionName == null) { regionName = getDefaultRegion(); } Cache result = cacheManager.getCache(regionName); if (result == null) { log.debug("Could not find configuration for region [" + regionName + "]; using defaults."); cacheManager.addCache(regionName); result = cacheManager.getCache(regionName); log.debug("EHCache region created: " + regionName); } return result; }
Example 9
| Project: resthub-master File: Cache.java View source code |
@Get
public void describe() throws ResourceException {
if (qmd != null) {
net.sf.ehcache.Cache c = ccf.get(qmd);
if (c == null) {
throw new ClientErrorException(Status.CLIENT_ERROR_NOT_FOUND);
}
StatisticsGateway st = c.getStatistics();
JSONObject ret = new JSONObject(st);
getResponse().setEntity(new JsonRepresentation(ret));
} else if (tmd != null) {
if (!tmd.isCacheable()) {
throw new ClientErrorException(Status.CLIENT_ERROR_NOT_FOUND);
}
JSONArray ret = new JSONArray();
for (String qid : qf.getQueries(tmd.getId())) {
ret.put(getReference("query", qid, "cache"));
}
getResponse().setEntity(new JsonRepresentation(ret));
}
}Example 10
| Project: rsimulator-master File: CoreModule.java View source code |
/*
* (non-Javadoc)
*
* @see com.google.inject.AbstractModule#configure()
*/
@Override
protected void configure() {
// ***** Properties *****
URL resource = getClass().getResource("/rsimulator.properties");
if (resource == null) {
log.debug("No /rsimulator.properties resource exists. Configuring /rsimulator-default.properties");
resource = getClass().getResource("/rsimulator-default.properties");
}
bind(Path.class).annotatedWith(Names.named("rsimulator-core-properties")).toInstance(new File(resource.getFile()).toPath());
// ***** Handlers *****
Map<String, Handler> map = new HashMap<String, Handler>();
JsonHandler jsonHandler = new JsonHandler();
requestInjection(jsonHandler);
TxtHandler txtHandler = new TxtHandler();
requestInjection(txtHandler);
XmlHandler xmlHandler = new XmlHandler();
requestInjection(xmlHandler);
map.put("json", jsonHandler);
map.put("txt", txtHandler);
map.put("xml", xmlHandler);
bind(new TypeLiteral<Map<String, Handler>>() {
}).annotatedWith(Names.named("handlers")).toInstance(map);
// ***** Interceptors for cache and script *****
CacheManager.create();
bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named("SimulatorCache")).toInstance(CacheManager.create().getCache("SimulatorCache"));
bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named("FileUtilsCache")).toInstance(CacheManager.create().getCache("FileUtilsCache"));
bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named("PropsCache")).toInstance(CacheManager.create().getCache("PropsCache"));
SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor();
SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor();
SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor();
FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor();
PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor();
requestInjection(simulatorPropertiesInterceptor);
requestInjection(simulatorCacheInterceptor);
requestInjection(simulatorScriptInterceptor);
requestInjection(fileUtilsCacheInterceptor);
requestInjection(propsCacheInterceptor);
// Order is significant
bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), simulatorPropertiesInterceptor);
bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), simulatorCacheInterceptor);
bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), simulatorScriptInterceptor);
bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), fileUtilsCacheInterceptor);
bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), propsCacheInterceptor);
}Example 11
| Project: seam-2.2-master File: EHCacheProvider.java View source code |
public Cache buildCache(String name, Properties properties) throws CacheException { try { net.sf.ehcache.Cache cache = getCacheManager().getCache(name); if (cache == null) { log.warn("Could not find configuration [" + name + "]; using defaults."); getCacheManager().addCache(name); cache = getCacheManager().getCache(name); log.debug("started EHCache region: " + name); } return new EhCache(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } }
Example 12
| Project: seam-revisited-master File: EhCacheProvider.java View source code |
private net.sf.ehcache.Cache getCacheRegion(String regionName) { if (regionName == null) { regionName = getDefaultRegion(); } Cache result = cacheManager.getCache(regionName); if (result == null) { log.debug("Could not find configuration for region [" + regionName + "]; using defaults."); cacheManager.addCache(regionName); result = cacheManager.getCache(regionName); log.debug("EHCache region created: " + regionName); } return result; }
Example 13
| Project: seam2jsf2-master File: EHCacheProvider.java View source code |
public Cache buildCache(String name, Properties properties) throws CacheException { try { net.sf.ehcache.Cache cache = getCacheManager().getCache(name); if (cache == null) { log.warn("Could not find configuration [" + name + "]; using defaults."); getCacheManager().addCache(name); cache = getCacheManager().getCache(name); log.debug("started EHCache region: " + name); } return new EhCache(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } }
Example 14
| Project: taylor-seam-jsf2-master File: EhCacheProvider.java View source code |
private net.sf.ehcache.Cache getCacheRegion(String regionName) { if (regionName == null) { regionName = getDefaultRegion(); } Cache result = getCacheManager().getCache(regionName); if (result == null) { synchronized (cacheManager) { if (!cacheManager.cacheExists(regionName)) { log.debug("Could not find configuration for region [" + regionName + "]; using defaults."); cacheManager.addCache(regionName); log.debug("EHCache region created: " + regionName); } } result = cacheManager.getCache(regionName); } return result; }
Example 15
| Project: EECE496-master File: EhcacheNonceVerifier.java View source code |
public void setCache(Cache cache) { if (cache.getTimeToLiveSeconds() != _maxAgeSeconds) { throw new IllegalArgumentException("Max Age: " + _maxAgeSeconds + ", same expected for cache, but found: " + cache.getTimeToLiveSeconds()); } if (cache.getTimeToLiveSeconds() != cache.getTimeToIdleSeconds()) { throw new IllegalArgumentException("Cache must have same timeToLive (" + cache.getTimeToLiveSeconds() + ") as timeToIdle (" + cache.getTimeToIdleSeconds() + ")"); } _cache = cache; }
Example 16
| Project: Katari-master File: EhCacheRegionFactoryTest.java View source code |
@Test
public void test() {
SpringTestUtils.beginTransaction();
for (int i = 0; i < 100; i++) {
repository.save(new OneHibernateEntity("a_" + i));
}
SpringTestUtils.endTransaction();
CacheManager manager = CacheManager.getInstance();
Cache queryCache = manager.getCache(QUERY_CACHE_NAME);
Cache objectCache = manager.getCache(OBJECT_CACHE_NAME);
assertThat(queryCache.getSize(), is(0));
repository.getAll();
assertThat(queryCache.getSize(), is(1));
repository.get(1);
assertThat(objectCache.getSize(), is(100));
}Example 17
| Project: metr-master File: InstrumentedEhcacheTest.java View source code |
@Test
public void measuresGetsAndPuts() throws Exception {
cache.get("woo");
cache.put(new Element("woo", "whee"));
final Timer gets = registry.timer(name(Cache.class, "test", "gets"));
assertThat(gets.getCount()).isEqualTo(1);
final Timer puts = registry.timer(name(Cache.class, "test", "puts"));
assertThat(puts.getCount()).isEqualTo(1);
}Example 18
| Project: metric-master File: InstrumentedEhcacheTest.java View source code |
@Test
public void measuresGetsAndPuts() throws Exception {
cache.get("woo");
cache.put(new Element("woo", "whee"));
final Timer gets = registry.timer(name(Cache.class, "test", "gets"));
assertThat(gets.getCount()).isEqualTo(1);
final Timer puts = registry.timer(name(Cache.class, "test", "puts"));
assertThat(puts.getCount()).isEqualTo(1);
}Example 19
| Project: metrics-master File: InstrumentedEhcacheTest.java View source code |
@Test
public void measuresGetsAndPuts() throws Exception {
cache.get("woo");
cache.put(new Element("woo", "whee"));
final Timer gets = registry.timer(name(Cache.class, "test", "gets"));
assertThat(gets.getCount()).isEqualTo(1);
final Timer puts = registry.timer(name(Cache.class, "test", "puts"));
assertThat(puts.getCount()).isEqualTo(1);
}Example 20
| Project: openid4java-openidorgfix-master File: EhcacheNonceVerifier.java View source code |
public void setCache(Cache cache) { if (cache.getTimeToLiveSeconds() != _maxAgeSeconds) { throw new IllegalArgumentException("Max Age: " + _maxAgeSeconds + ", same expected for cache, but found: " + cache.getTimeToLiveSeconds()); } if (cache.getTimeToLiveSeconds() != cache.getTimeToIdleSeconds()) { throw new IllegalArgumentException("Cache must have same timeToLive (" + cache.getTimeToLiveSeconds() + ") as timeToIdle (" + cache.getTimeToIdleSeconds() + ")"); } _cache = cache; }
Example 21
| Project: openmicroscopy-master File: SessionDestructionTest.java View source code |
@Test(groups = "integration")
public void testTwoClientsSessionGlacierDestruction() throws Exception {
fixture = new MockFixture(this);
Session s = fixture.session();
net.sf.ehcache.Cache c = fixture.cache();
ServiceFactoryPrx sf1 = fixture.createServiceFactory(s, c, "sf1");
ServiceFactoryPrx sf2 = fixture.createServiceFactory(s, c, "sf2");
sf1.closeOnDestroy();
sf2.closeOnDestroy();
sf1.getAdminService();
sf2.getAdminService();
fixture.mock("sessionsMock").expects(once()).method("detach").will(returnValue(1));
sf1.destroy();
fixture.mock("sessionsMock").expects(once()).method("detach").will(returnValue(0));
fixture.mock("sessionsMock").expects(once()).method("close").will(returnValue(-2));
sf2.destroy();
}Example 22
| Project: owsi-core-parent-master File: EhCacheCacheModificationPanel.java View source code |
@Override
protected Component createBody(String wicketId) {
DelegatedMarkupPanel body = new DelegatedMarkupPanel(wicketId, EhCacheCacheModificationPanel.class);
cacheForm = new Form<Cache>("cacheForm");
maxSizeField = new TextField<Long>("maxSize", BindingModel.of(getModel(), CoreWicketMoreBindings.ehCacheCacheInformation().maxElementsInMemory()));
maxSizeField.setLabel(new ResourceModel("console.maintenance.ehcache.portfolio.max"));
cacheForm.add(maxSizeField);
body.add(cacheForm);
return body;
}Example 23
| Project: railo-master File: EHCacheSupport.java View source code |
@Override
public void register(CacheEventListener listener) {
//RegisteredEventListeners listeners=cache.getCacheEventNotificationService();
//listeners.registerListener(new ExpiresCacheEventListener());
net.sf.ehcache.Cache cache = getCache();
RegisteredEventListeners service = cache.getCacheEventNotificationService();
service.registerListener(new EHCacheEventListener(listener));
//.getCacheEventListeners().add(new EHCacheEventListener(listener));
}Example 24
| Project: argus-pep-server-master File: ClearResponseCacheCommand.java View source code |
/** {@inheritDoc} */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CacheManager cacheMgr = CacheManager.getInstance();
if (cacheMgr != null && cacheMgr.getStatus() == Status.STATUS_ALIVE) {
log.info("Clearing PDP response cache");
Cache responseCache = cacheMgr.getCache(PEPDaemonRequestHandler.RESPONSE_CACHE_NAME);
if (responseCache != null) {
responseCache.removeAll();
}
}
resp.setStatus(HttpServletResponse.SC_OK);
}Example 25
| Project: bard-master File: CachingService.java View source code |
public Ehcache getCache(String name) {
Ehcache cache = cacheManager.getEhcache(name);
if (cache == null) {
cache = new Cache(name, maxCacheSize, // overflowToDisk
false, // eternal (never expire)
false, // time to live (seconds)
10 * 60 * 60, // time to idle (seconds)
10 * 60 * 60);
cacheManager.addCacheIfAbsent(cache);
cache.setStatisticsEnabled(true);
}
return cache;
}Example 26
| Project: beume-master File: SPCacheFactory.java View source code |
public static SelfPopulatingCache createCache(String ehcachename, CacheEntryFactory cu) {
Logger.getLogger(SPCacheFactory.class.getName()).log(Level.INFO, "Setting up cache... {0}", ehcachename);
MulticastKeepaliveHeartbeatSender.setHeartBeatInterval(1000);
Logger.getLogger(SPCacheFactory.class.getName()).log(Level.INFO, "Waiting cluster {0}", manager.getName());
SPCacheFactory.waitForClusterMembership(10, TimeUnit.SECONDS, Collections.singleton(ehcachename), manager);
Logger.getLogger(SPCacheFactory.class.getName()).log(Level.INFO, "Cluster connected.");
Cache orig_ehcache = manager.getCache(ehcachename);
if (orig_ehcache == null) {
return null;
}
orig_ehcache.bootstrap();
SelfPopulatingCache ehcache = new SelfPopulatingCache(orig_ehcache, cu);
ehcache.bootstrap();
return ehcache;
}Example 27
| Project: Broadleaf-eCommerce-master File: ServiceResponseCache.java View source code |
public Object processRequest(ProceedingJoinPoint call) throws Throwable {
CacheRequest cacheRequest = (CacheRequest) call.getArgs()[0];
Cache cache = ((ServiceResponseCacheable) call.getTarget()).getCache();
List<Serializable> cacheItemResponses = new ArrayList<Serializable>();
Iterator<CacheItemRequest> itr = cacheRequest.getCacheItemRequests().iterator();
while (itr.hasNext()) {
CacheItemRequest itemRequest = itr.next();
if (cache.isKeyInCache(itemRequest.key())) {
cacheItemResponses.add(cache.get(itemRequest.key()).getValue());
itr.remove();
}
}
CacheResponse returnValue = (CacheResponse) call.proceed();
Object[] responses = new Object[cacheItemResponses.size() + returnValue.getCacheItemResponses().length];
responses = cacheItemResponses.toArray(responses);
for (int j = 0; j < returnValue.getCacheItemResponses().length; j++) {
Element element = new Element(cacheRequest.getCacheItemRequests().get(j).key(), returnValue.getCacheItemResponses()[j]);
cache.put(element);
}
System.arraycopy(returnValue.getCacheItemResponses(), 0, responses, cacheItemResponses.size(), returnValue.getCacheItemResponses().length);
returnValue.setCacheItemResponses(responses);
return returnValue;
}Example 28
| Project: BroadleafCommerce-master File: ServiceResponseCache.java View source code |
public Object processRequest(ProceedingJoinPoint call) throws Throwable {
CacheRequest cacheRequest = (CacheRequest) call.getArgs()[0];
Cache cache = ((ServiceResponseCacheable) call.getTarget()).getCache();
List<Serializable> cacheItemResponses = new ArrayList<Serializable>();
Iterator<CacheItemRequest> itr = cacheRequest.getCacheItemRequests().iterator();
while (itr.hasNext()) {
CacheItemRequest itemRequest = itr.next();
if (cache.isKeyInCache(itemRequest.key())) {
cacheItemResponses.add(cache.get(itemRequest.key()).getValue());
itr.remove();
}
}
CacheResponse returnValue = (CacheResponse) call.proceed();
Object[] responses = new Object[cacheItemResponses.size() + returnValue.getCacheItemResponses().length];
responses = cacheItemResponses.toArray(responses);
for (int j = 0; j < returnValue.getCacheItemResponses().length; j++) {
Element element = new Element(cacheRequest.getCacheItemRequests().get(j).key(), returnValue.getCacheItemResponses()[j]);
cache.put(element);
}
System.arraycopy(returnValue.getCacheItemResponses(), 0, responses, cacheItemResponses.size(), returnValue.getCacheItemResponses().length);
returnValue.setCacheItemResponses(responses);
return returnValue;
}Example 29
| Project: caldav4j-master File: CaldavFixtureHarness.java View source code |
/**
*
*/
public static EhCacheResourceCache createSimpleCache() {
//initialize cache
CacheManager cacheManager = CacheManager.create();
EhCacheResourceCache myCache = new EhCacheResourceCache();
Cache uidToHrefCache = new Cache(UID_TO_HREF_CACHE, 1000, false, false, 600, 300, false, 0);
Cache hrefToResourceCache = new Cache(HREF_TO_RESOURCE_CACHE, 1000, false, false, 600, 300, false, 0);
myCache.setHrefToResourceCache(hrefToResourceCache);
myCache.setUidToHrefCache(uidToHrefCache);
cacheManager.addCache(uidToHrefCache);
cacheManager.addCache(hrefToResourceCache);
return myCache;
}Example 30
| Project: cevent-app-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getJavaType().getName();
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Integer.class, 3600));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 31
| Project: com.idega.cluster-master File: ClusterCacheMapListenerSetter.java View source code |
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
// get ehcache cache manager
CacheManager cacheManager = CacheManager.getInstance();
long start = System.currentTimeMillis();
// wait for creation of the cache!!!!!!!!!!!
while (!cacheManager.cacheExists(cacheName)) {
long currentTime = System.currentTimeMillis();
long difference = currentTime - start;
// wait not forever
if (difference > ClusterCacheSettings.WAITING_TIME_PERIOD_CACHE_CREATION) {
return;
}
}
// cache was created
Cache cache = cacheManager.getCache(cacheName);
// needed for adding a listener
RegisteredEventListeners registeredEventListeners = cache.getCacheEventNotificationService();
// creating a listener for this cache map
ClusterCacheEventListener clusterCacheMapListener = new ClusterCacheEventListener(cacheName, applicationMessenger);
// adding this listener to the cache
registeredEventListeners.registerListener(clusterCacheMapListener);
}Example 32
| Project: commerce-master File: ServiceResponseCache.java View source code |
public Object processRequest(ProceedingJoinPoint call) throws Throwable {
CacheRequest cacheRequest = (CacheRequest) call.getArgs()[0];
Cache cache = ((ServiceResponseCacheable) call.getTarget()).getCache();
List<Serializable> cacheItemResponses = new ArrayList<Serializable>();
Iterator<CacheItemRequest> itr = cacheRequest.getCacheItemRequests().iterator();
while (itr.hasNext()) {
CacheItemRequest itemRequest = itr.next();
if (cache.isKeyInCache(itemRequest.key())) {
cacheItemResponses.add(cache.get(itemRequest.key()).getValue());
itr.remove();
}
}
CacheResponse returnValue = (CacheResponse) call.proceed();
Object[] responses = new Object[cacheItemResponses.size() + returnValue.getCacheItemResponses().length];
responses = cacheItemResponses.toArray(responses);
for (int j = 0; j < returnValue.getCacheItemResponses().length; j++) {
Element element = new Element(cacheRequest.getCacheItemRequests().get(j).key(), returnValue.getCacheItemResponses()[j]);
cache.put(element);
}
System.arraycopy(returnValue.getCacheItemResponses(), 0, responses, cacheItemResponses.size(), returnValue.getCacheItemResponses().length);
returnValue.setCacheItemResponses(responses);
return returnValue;
}Example 33
| Project: gocd-master File: UserCacheFactory.java View source code |
public Cache createCache() throws IOException { factoryBean.setCacheManager(createCacheManager()); factoryBean.setCacheName("userCache"); factoryBean.setDiskPersistent(false); factoryBean.setOverflowToDisk(false); factoryBean.setMaxElementsInMemory(1000); factoryBean.setEternal(true); factoryBean.setMemoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU); factoryBean.afterPropertiesSet(); return (Cache) factoryBean.getObject(); }
Example 34
| Project: java-cas-client-master File: EhCacheBackedProxyGrantingTicketStorageImplTests.java View source code |
public void testEncryptionMechanisms() throws Exception {
final Cache ehcache = new Cache("name", 100, false, false, 500, 500);
CacheManager.getInstance().addCache(ehcache);
final EhcacheBackedProxyGrantingTicketStorageImpl cache = new EhcacheBackedProxyGrantingTicketStorageImpl(ehcache);
// cache.setSecretKey("thismustbeatleast24charactersandcannotbelessthanthat1234");
assertNull(cache.retrieve(null));
assertNull(cache.retrieve("foobar"));
cache.save("proxyGrantingTicketIou", "proxyGrantingTicket");
assertEquals("proxyGrantingTicket", cache.retrieve("proxyGrantingTicketIou"));
assertTrue("proxyGrantingTicket".equals(ehcache.get("proxyGrantingTicketIou").getValue()));
}Example 35
| Project: JavascriptGame-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Integer.class, 3600));
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 36
| Project: jhipster-sample-app-java7-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager(JHipsterProperties jHipsterProperties) {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap());
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds());
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 37
| Project: kevoree-library-master File: TesterMetier2.java View source code |
@Override
public void run() {
while (alive) {
try {
CacheManager c = this.getPortByName("ehCacheService", IehcacheService.class).getCacheManger();
Cache myCache = c.getCache("jed");
myCache.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.print(evt.getPropertyName() + " old=" + evt.getOldValue() + " new=" + evt.getNewValue());
}
});
} catch (Exception e) {
logger.error("error");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}Example 38
| Project: li-old-master File: CacheUtil.java View source code |
/**
* @param cacheName
*/
public static Cache getOrAddCache(String cacheName) {
Cache cache = cacheManager.getCache(cacheName);
if (cache == null) {
synchronized (cacheManager) {
cache = cacheManager.getCache(cacheName);
if (cache == null) {
cacheManager.addCacheIfAbsent(cacheName);
cache = cacheManager.getCache(cacheName);
}
}
}
return cache;
}Example 39
| Project: OG-Platform-master File: EHCachingRegionSource.java View source code |
@Override
public Region getHighestLevelRegion(ExternalIdBundle bundle) {
Region result = null;
Element element = _cache.get(bundle);
if (element != null) {
s_logger.debug("Cache hit on {}", bundle);
result = (Region) element.getObjectValue();
} else {
s_logger.debug("Cache miss on {}", bundle);
result = getUnderlying().getHighestLevelRegion(bundle);
s_logger.debug("Caching regions {}", result);
element = new Element(bundle, result);
_cache.put(element);
if (result != null) {
_cache.put(new Element(result.getUniqueId(), result));
}
}
return result;
}Example 40
| Project: openmrs-core-master File: OpenmrsCacheManagerFactoryBean.java View source code |
@Override
public CacheManager getObject() {
CacheManager cacheManager = super.getObject();
Map<String, CacheConfiguration> cacheConfig = cacheManager.getConfiguration().getCacheConfigurations();
List<CacheConfiguration> cacheConfigurations = CachePropertiesUtil.getCacheConfigurations();
cacheConfigurations.stream().filter( cc -> cacheConfig.get(cc.getName()) == null).forEach( cc -> cacheManager.addCache(new Cache(cc)));
return cacheManager;
}Example 41
| Project: PF-CORE-master File: FileInfoDAOEhcacheTest.java View source code |
@Override
protected void setUp() throws Exception {
super.setUp();
TestHelper.cleanTestDir();
// Create a CacheManager using defaults
CacheManager manager = CacheManager.create();
// Create a Cache specifying its configuration.
cache = new Cache("test", 30000, MemoryStoreEvictionPolicy.LRU, true, "build/test/ehcache", true, 60, 30, true, 0, null);
manager.addCache(cache);
}Example 42
| Project: rapa-master File: RestClientBuilder.java View source code |
public RestClient build() throws MalformedURLException {
HttpClientAdapterImpl httpClientAdapter = new HttpClientAdapterImpl(username, password, host(), port(), realm, scheme, authenticationPrefefences);
HttpMethodProvider httpMethodProvider = new HttpMethodProvider();
CacheManager singletonCacheManager = CacheManager.getInstance();
singletonCacheManager.addCache("client cache");
Cache clientCache = singletonCacheManager.getCache("client cache");
HttpMethodExecutor httpMethodExecutor = new HttpMethodExecutor(httpClientAdapter, httpMethodProvider, clientCache, singletonCacheManager);
Url resourceUrl = new Url(url, formatHandler.getExtension(), formatAsExtenstion);
return new RestClient(resourceUrl, formatHandler, httpMethodExecutor);
}Example 43
| Project: smart-cms-master File: CacheProvider.java View source code |
public Cache get() { if (logger.isDebugEnabled()) { logger.debug("Trying for cache with name " + trialName); } if (StringUtils.isNotBlank(trialName)) { try { Cache cache = manager.getCache(trialName); if (cache != null) { if (logger.isDebugEnabled()) { logger.debug("Return special cache with name " + trialName); } return cache; } } catch (Exception ex) { logger.warn(ex.getMessage(), ex); } } logger.debug("Return default cache!"); return defaultCache; }
Example 44
| Project: tatami-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
cacheManager = new net.sf.ehcache.CacheManager();
if (env.acceptsProfiles(Constants.SPRING_PROFILE_METRICS)) {
log.debug("Ehcache Metrics monitoring enabled");
Cache statusCache = cacheManager.getCache("status-cache");
Ehcache decoratedStatusCache = InstrumentedEhcache.instrument(statusCache);
cacheManager.replaceCacheWithDecoratedCache(statusCache, decoratedStatusCache);
Cache userCache = cacheManager.getCache("user-cache");
Ehcache decoratedUserCache = InstrumentedEhcache.instrument(userCache);
cacheManager.replaceCacheWithDecoratedCache(userCache, decoratedUserCache);
Cache attachmentCache = cacheManager.getCache("attachment-cache");
Ehcache decoratedAttachmentCache = InstrumentedEhcache.instrument(attachmentCache);
cacheManager.replaceCacheWithDecoratedCache(attachmentCache, decoratedAttachmentCache);
Cache friendsCache = cacheManager.getCache("friends-cache");
Ehcache decoratedFriendsCache = InstrumentedEhcache.instrument(friendsCache);
cacheManager.replaceCacheWithDecoratedCache(friendsCache, decoratedFriendsCache);
Cache followersCache = cacheManager.getCache("followers-cache");
Ehcache decoratedFollowersCache = InstrumentedEhcache.instrument(followersCache);
cacheManager.replaceCacheWithDecoratedCache(followersCache, decoratedFollowersCache);
Cache groupCache = cacheManager.getCache("group-cache");
Ehcache decoratedGroupCache = InstrumentedEhcache.instrument(groupCache);
cacheManager.replaceCacheWithDecoratedCache(groupCache, decoratedGroupCache);
Cache groupUserCache = cacheManager.getCache("group-user-cache");
Ehcache decoratedGroupUserCache = InstrumentedEhcache.instrument(groupUserCache);
cacheManager.replaceCacheWithDecoratedCache(groupUserCache, decoratedGroupUserCache);
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 45
| Project: AxonFramework-master File: CachingSagaStoreTest.java View source code |
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
ehCache = new net.sf.ehcache.Cache("test", 100, false, false, 10, 10);
cacheManager = CacheManager.create();
cacheManager.addCache(ehCache);
associationsCache = spy(new EhCacheAdapter(ehCache));
sagaCache = spy(new EhCacheAdapter(ehCache));
mockSagaStore = spy(new InMemorySagaStore());
testSubject = new CachingSagaStore(mockSagaStore, associationsCache, sagaCache);
}Example 46
| Project: hibernate-master-class-master File: ReadWriteCacheConcurrencyStrategyWithLockTimeoutTest.java View source code |
@Test
public void testRepositoryEntityUpdate() {
try {
doInTransaction( session -> {
Repository repository = (Repository) session.get(Repository.class, 1L);
repository.setName("High-Performance Hibernate");
applyInterceptor.set(true);
});
} catch (Exception e) {
LOGGER.info("Expected", e);
}
applyInterceptor.set(false);
AtomicReference<Object> previousCacheEntryReference = new AtomicReference<>();
AtomicBoolean cacheEntryChanged = new AtomicBoolean();
while (!cacheEntryChanged.get()) {
doInTransaction( session -> {
boolean entryChange;
session.get(Repository.class, 1L);
try {
Object previousCacheEntry = previousCacheEntryReference.get();
Object cacheEntry = getCacheEntry(Repository.class, 1L);
entryChange = previousCacheEntry != null && previousCacheEntry != cacheEntry;
previousCacheEntryReference.set(cacheEntry);
LOGGER.info("Cache entry {}", ToStringBuilder.reflectionToString(cacheEntry));
if (!entryChange) {
sleep(100);
} else {
cacheEntryChanged.set(true);
}
} catch (IllegalAccessException e) {
LOGGER.error("Error accessing Cache", e);
}
});
}
}Example 47
| Project: ngrinder-master File: StatisticsController.java View source code |
/**
* Get all cache statistics.<br>
* size is object count in memory & disk<br>
* heap is object count in memory<br>
* hit & miss is cache hit & miss count
*
* @return Ehcache statistics list, group by cacheName
*/
private List<Map<String, Object>> getEhcacheStat() {
List<Map<String, Object>> stats = new LinkedList<Map<String, Object>>();
for (String cacheName : cacheManager.getCacheNames()) {
Cache cache = cacheManager.getCache(cacheName);
net.sf.ehcache.Cache ehcache = (net.sf.ehcache.Cache) cache.getNativeCache();
Statistics statistics = ehcache.getStatistics();
Map<String, Object> stat = new HashMap<String, Object>();
stat.put("cacheName", cacheName);
stat.put("size", statistics.getObjectCount());
stat.put("heap", statistics.getMemoryStoreObjectCount());
stat.put("hit", statistics.getCacheHits());
stat.put("miss", statistics.getCacheMisses());
stats.add(stat);
}
return stats;
}Example 48
| Project: qi4j-extensions-master File: EhCachePoolMixin.java View source code |
public <T> Cache<T> fetchCache(String cacheId, Class<T> valueType) { // Note: Small bug in Ehcache; If the cache name is an empty String it will actually work until // you try to remove the Cache instance from the CacheManager, at which point it is silently // ignored but not removed so there is an follow up problem of too much in the CacheManager. NullArgumentException.validateNotEmpty("cacheId", cacheId); EhCacheImpl<T> cache = caches.get(cacheId); if (cache == null) { cache = createNewCache(cacheId, valueType); caches.put(cacheId, cache); } cache.incRefCount(); return cache; }
Example 49
| Project: qi4j-sdk-master File: EhCachePoolMixin.java View source code |
@Override public <T> Cache<T> fetchCache(String cacheId, Class<T> valueType) { // Note: Small bug in Ehcache; If the cache name is an empty String it will actually work until // you try to remove the Cache instance from the CacheManager, at which point it is silently // ignored but not removed so there is an follow up problem of too much in the CacheManager. NullArgumentException.validateNotEmpty("cacheId", cacheId); @SuppressWarnings("unchecked") EhCacheImpl<T> cache = caches.get(cacheId); if (cache == null) { cache = createNewCache(cacheId, valueType); caches.put(cacheId, cache); } cache.incRefCount(); return cache; }
Example 50
| Project: ABC-Go-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 51
| Project: BikeMan-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 52
| Project: BikeRentalServiceManager-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Integer.class, 3600));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 53
| Project: cache4guice-master File: EhCacheModule.java View source code |
@Override
protected void configure() {
// load external properties
Names.bindProperties(binder(), loadProperties());
bind(Cache.class).toProvider(CacheProvider.class).in(Singleton.class);
bind(CacheAdapter.class).to(EhCache.class).in(Singleton.class);
CacheInterceptor cacheInterceptor = new CacheInterceptor();
requestInjection(cacheInterceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Cached.class), cacheInterceptor);
}Example 54
| Project: CAJPII-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 55
| Project: cas-server-4.0.1-master File: EncryptedMapDecoratorTests.java View source code |
@Before
public void setUp() throws Exception {
try {
this.cacheManager = new CacheManager(this.getClass().getClassLoader().getResourceAsStream("ehcacheClearPass.xml"));
final Cache cache = this.cacheManager.getCache("clearPassCache");
this.map = new EhcacheBackedMap(cache);
this.decorator = new EncryptedMapDecorator(map);
} catch (final Exception e) {
fail(e.getMessage());
}
}Example 56
| Project: CBIRestAPI-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 57
| Project: csrf-jhipster-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds((long) env.getProperty("cache.timeToLiveSeconds", Integer.class, 3600));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 58
| Project: ehcache3-master File: Ehcache2.java View source code |
@Test
public void ehcache2Expiry() throws Exception {
// tag::CustomExpiryEhcache2[]
int defaultCacheTTLInSeconds = 20;
CacheManager cacheManager = initCacheManager();
CacheConfiguration cacheConfiguration = new CacheConfiguration().name("cache").maxEntriesLocalHeap(100).timeToLiveSeconds(// <1>
defaultCacheTTLInSeconds);
cacheManager.addCache(new Cache(cacheConfiguration));
Element element = new Element(10L, "Hello");
// <2>
int ttlInSeconds = getTimeToLiveInSeconds((Long) element.getObjectKey(), (String) element.getObjectValue());
if (ttlInSeconds != defaultCacheTTLInSeconds) {
// <3>
element.setTimeToLive(ttlInSeconds);
}
cacheManager.getCache("cache").put(element);
System.out.println(cacheManager.getCache("cache").get(10L).getObjectValue());
// <4>
sleep(2100);
// Now the returned element should be null, as the mapping is expired.
System.out.println(cacheManager.getCache("cache").get(10L));
// end::CustomExpiryEhcache2[]
}Example 59
| Project: ewcms-master File: EhcacheResultCache.java View source code |
@Override
public CacheResultable putResultInCache(CacheResultable result) {
Cache cache = getCache();
if (result.getCacheKey() == null || result.getCacheKey().isEmpty()) {
String cacheKey = getCacheKey();
result = new CacheResult(cacheKey, (CacheResult) result);
}
if (result.isModified()) {
Element element = new Element(result.getCacheKey(), result);
cache.put(element);
if (logger.isDebugEnabled()) {
logger.debug("Ehcache memory store size is {}", cache.calculateInMemorySize());
}
}
return result;
}Example 60
| Project: fensy-master File: EhCacheProvider.java View source code |
/**
* Builds a Cache.
* <p>
* Even though this method provides properties, they are not used.
* Properties for EHCache are specified in the ehcache.xml file.
* Configuration will be read from ehcache.xml for a cache declaration
* where the name attribute matches the name parameter in this builder.
*
* @param name the name of the cache. Must match a cache configured in ehcache.xml
* @param properties not used
* @return a newly built cache will be built and initialised
* @throws CacheException inter alia, if a cache of the same name already exists
*/
public EhCache buildCache(String name, boolean autoCreate) throws CacheException {
EhCache ehcache = _cacheManager.get(name);
if (ehcache == null && autoCreate) {
try {
net.sf.ehcache.Cache cache = manager.getCache(name);
if (cache == null) {
log.warn("Could not find configuration [" + name + "]; using defaults.");
manager.addCache(name);
cache = manager.getCache(name);
log.debug("started EHCache region: " + name);
}
synchronized (_cacheManager) {
ehcache = new EhCache(cache);
_cacheManager.put(name, ehcache);
return ehcache;
}
} catch (net.sf.ehcache.CacheException e) {
throw new CacheException(e);
}
}
return ehcache;
}Example 61
| Project: Fudan-Sakai-master File: RenderCacheImpl.java View source code |
public String getRenderedContent(String key) {
String cacheValue = null;
try {
Element e = cache.get(key);
if (e != null) {
cacheValue = (String) e.getValue();
}
} catch (Exception ex) {
log.error("RenderCache threw Exception for key: " + key, ex);
}
if (cacheValue != null)
log.debug("Cache hit for " + key + " size " + cacheValue.length());
else
log.debug("Cache miss for " + key);
return cacheValue;
}Example 62
| Project: havrobase-master File: CacherTest.java View source code |
@Test
public void cachingtest() {
FAB<Beacon, byte[]> beaconFAB = new FAB<Beacon, byte[]>("/tmp/cachingtest/beacons", "/tmp/cachingtest/schemas", new Supplier<byte[]>() {
@Override
public byte[] get() {
return Longs.toByteArray(r.nextLong() % 100000);
}
}, Beacon.SCHEMA$, AvroFormat.BINARY, null);
Cacher.KeyMaker<byte[]> keyMaker = new Cacher.KeyMaker<byte[]>() {
public Object make(final byte[] key) {
return new BytesKey(key);
}
};
assertTrue(keyMaker.make(new byte[4]).equals(keyMaker.make(new byte[4])));
CacheManager cm = CacheManager.create();
Cache cache = new Cache("test", 10000, false, true, -1, -1);
Cacher<Beacon, byte[]> beaconCacher = new Cacher<Beacon, byte[]>(beaconFAB, keyMaker, cache);
cm.addCache(cache);
int total = 0;
for (Row<Beacon, byte[]> beaconRow : beaconCacher.scan(null, null)) {
beaconCacher.delete(beaconRow.row);
}
for (Row<Beacon, byte[]> beaconRow : beaconCacher.scan(null, null)) {
total++;
}
assertEquals(0, total);
List<byte[]> rows = new ArrayList<byte[]>();
for (int i = 0; i < 1000; i++) {
Beacon beacon = new Beacon();
beacon.browser = "asdfasdfasdfasd" + i;
beacon.login = "adfasdfasdfasdfsfas" + i;
beacon.useragent = "adfasdfasdfasdfadsfadsf" + i;
beacon.parameters = new HashMap<CharSequence, CharSequence>();
rows.add(beaconCacher.create(beacon));
}
for (Row<Beacon, byte[]> beaconRow : beaconCacher.scan(null, null)) {
total++;
}
{
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
beaconFAB.get(rows.get(r.nextInt(rows.size())));
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
{
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
beaconCacher.get(rows.get(r.nextInt(rows.size())));
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
{
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
beaconCacher.get(Longs.toByteArray(r.nextLong() % 100000));
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
System.out.println(beaconCacher);
}Example 63
| Project: JFOA-master File: CacheKit.java View source code |
static Cache getOrAddCache(String cacheName) { Cache cache = cacheManager.getCache(cacheName); if (cache == null) { synchronized (cacheManager) { cache = cacheManager.getCache(cacheName); if (cache == null) { log.warn("Could not find cache config [" + cacheName + "], using default."); cacheManager.addCacheIfAbsent(cacheName); cache = cacheManager.getCache(cacheName); log.debug("Cache [" + cacheName + "] started."); } } } return cache; }
Example 64
| Project: jhipster-example-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 65
| Project: jhipster-ionic-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 66
| Project: jhipster_myapp-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 67
| Project: lightadmin-jhipster-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 68
| Project: miso-lims-master File: CacheAwareRowMapper.java View source code |
public Cache lookupCache(CacheManager cacheManager) throws CacheException, UnsupportedOperationException { if (cacheEnabled) { if (cacheManager != null) { Cache c = cacheManager.getCache(getCacheName()); if (c != null) { return c; } throw new CacheException("No such cache: " + getCacheName()); } else { return null; } } else { throw new UnsupportedOperationException("Cannot lookup cache when mapping caches aren't enabled"); } }
Example 69
| Project: MLDS-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Integer.class, 3600));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 70
| Project: Mycat-BigSQL-master File: EnchachePooFactory.java View source code |
@Override
public CachePool createCachePool(String poolName, int cacheSize, int expiredSeconds) {
CacheManager cacheManager = CacheManager.create();
Cache enCache = cacheManager.getCache(poolName);
if (enCache == null) {
CacheConfiguration cacheConf = cacheManager.getConfiguration().getDefaultCacheConfiguration().clone();
cacheConf.setName(poolName);
if (cacheConf.getMaxEntriesLocalHeap() != 0) {
cacheConf.setMaxEntriesLocalHeap(cacheSize);
} else {
cacheConf.setMaxBytesLocalHeap(String.valueOf(cacheSize));
}
cacheConf.setTimeToIdleSeconds(expiredSeconds);
Cache cache = new Cache(cacheConf);
cacheManager.addCache(cache);
return new EnchachePool(poolName, cache, cacheSize);
} else {
return new EnchachePool(poolName, enCache, cacheSize);
}
}Example 71
| Project: Mycat-Server-master File: EnchachePooFactory.java View source code |
@Override
public CachePool createCachePool(String poolName, int cacheSize, int expiredSeconds) {
CacheManager cacheManager = CacheManager.create();
Cache enCache = cacheManager.getCache(poolName);
if (enCache == null) {
CacheConfiguration cacheConf = cacheManager.getConfiguration().getDefaultCacheConfiguration().clone();
cacheConf.setName(poolName);
if (cacheConf.getMaxEntriesLocalHeap() != 0) {
cacheConf.setMaxEntriesLocalHeap(cacheSize);
} else {
cacheConf.setMaxBytesLocalHeap(String.valueOf(cacheSize));
}
cacheConf.setTimeToIdleSeconds(expiredSeconds);
Cache cache = new Cache(cacheConf);
cacheManager.addCache(cache);
return new EnchachePool(poolName, cache, cacheSize);
} else {
return new EnchachePool(poolName, enCache, cacheSize);
}
}Example 72
| Project: openclouddb-master File: EnchachePooFactory.java View source code |
@Override
public CachePool createCachePool(String poolName, int cacheSize, int expiredSeconds) {
CacheManager cacheManager = CacheManager.create();
Cache enCache = cacheManager.getCache(poolName);
if (enCache == null) {
CacheConfiguration cacheConf = cacheManager.getConfiguration().getDefaultCacheConfiguration().clone();
cacheConf.setName(poolName);
if (cacheConf.getMaxEntriesLocalHeap() != 0) {
cacheConf.setMaxEntriesLocalHeap(cacheSize);
} else {
cacheConf.setMaxBytesLocalHeap(String.valueOf(cacheSize));
}
cacheConf.setTimeToIdleSeconds(expiredSeconds);
Cache cache = new Cache(cacheConf);
cacheManager.addCache(cache);
return new EnchachePool(poolName, cache, cacheSize);
} else {
return new EnchachePool(poolName, enCache, cacheSize);
}
}Example 73
| Project: parkingfriends-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registring Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Integer.class, 3600));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 74
| Project: Points-master File: CacheConfiguration.java View source code |
private void reconfigureCache(String name, JHipsterProperties jHipsterProperties) {
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds());
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}Example 75
| Project: qafe-platform-master File: CacheManager.java View source code |
public Map getDistributedMap(String name) {
if (ehCacheManager == null) {
return new HashMap();
}
if (distributedQafeCache.equals(name)) {
Cache cache = ehCacheManager.getCache(name);
assert (cache != null);
return new QafeEHCache(cache);
} else {
throw new IllegalStateException("only (" + distributedQafeCache + ") is available ! as a distributed Map");
}
}Example 76
| Project: sched-assist-master File: CacheManagerController.java View source code |
/**
*
* @param model
* @return
*/
@RequestMapping(method = RequestMethod.GET)
public String getCacheStatistics(ModelMap model) {
String[] cacheNames = this.cacheManager.getCacheNames();
model.addAttribute("cacheNames", cacheNames);
Map<String, Statistics> statisticsMap = new HashMap<String, Statistics>();
for (String cacheName : cacheNames) {
Cache cache = this.cacheManager.getCache(cacheName);
Statistics stats = cache.getStatistics();
statisticsMap.put(cacheName, stats);
}
model.addAttribute("statisticsMap", statisticsMap);
return "admin/cache-statistics";
}Example 77
| Project: spark-jhipster-master File: CacheConfiguration.java View source code |
@Bean
public CacheManager cacheManager() {
log.debug("Starting Ehcache");
cacheManager = net.sf.ehcache.CacheManager.create();
cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
log.debug("Registering Ehcache Metrics gauges");
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (EntityType<?> entity : entities) {
String name = entity.getName();
if (name == null || entity.getJavaType() != null) {
name = entity.getJavaType().getName();
}
Assert.notNull(name, "entity cannot exist without a identifier");
net.sf.ehcache.Cache cache = cacheManager.getCache(name);
if (cache != null) {
cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
}
}
EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
ehCacheManager.setCacheManager(cacheManager);
return ehCacheManager;
}Example 78
| Project: spring-data-semantic-master File: EhCacheEntityCache.java View source code |
private Ehcache getCache(Class<?> clazz) {
String cacheName = clazz.getSimpleName();
Ehcache cache = cacheManager.getCache(cacheName);
if (cache == null) {
CacheConfiguration config = new CacheConfiguration(cacheName, 1000).copyOnRead(true).copyOnWrite(true);
cache = new Cache(config);
cacheManager.addCache(cache);
}
return cache;
}Example 79
| Project: spring-framework-master File: EhCacheCacheTests.java View source code |
@Before
public void setUp() {
cacheManager = new CacheManager(new Configuration().name("EhCacheCacheTests").defaultCache(new CacheConfiguration("default", 100)));
nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
cacheManager.addCache(nativeCache);
cache = new EhCacheCache(nativeCache);
}Example 80
| Project: springmvc-uadetector-master File: EhCacheParserConfiguration.java View source code |
protected UADetectorCache cache(UserAgentStringParser parser) {
CacheManager cacheManager = CacheManager.getInstance();
Cache ehCache = cacheManager.getCache("uadetector");
CacheConfiguration configuration = ehCache.getCacheConfiguration();
configuration.setMemoryStoreEvictionPolicy("LRU");
configuration.setMaxEntriesLocalHeap(getMaximumSize());
configuration.setTimeToLiveSeconds(getTimeToLiveInSeconds());
return new EhCacheCache(ehCache, parser);
}Example 81
| Project: uPortal-master File: GroupsCacheAuthenticationListenerTest.java View source code |
@Test
public void testUserAuthenticated() {
final IPerson person = PersonFactory.createPerson();
person.setAttribute(IPerson.USERNAME, "mock.person");
final IEntityGroup group = new MockEntityGroup("mock.group", IPerson.class);
final CacheManager cacheManager = CacheManager.getInstance();
final Cache parentGroupsCache = new Cache("parentGroupsCache", 100, false, false, 0, 0);
cacheManager.addCache(parentGroupsCache);
parentGroupsCache.put(new Element(person.getEntityIdentifier(), Collections.singleton(group)));
final Cache childrenCache = new Cache("childrenCache", 100, false, false, 0, 0);
cacheManager.addCache(childrenCache);
childrenCache.put(new Element(group.getUnderlyingEntityIdentifier(), new Object()));
Assert.assertEquals(parentGroupsCache.getSize(), 1);
Assert.assertEquals(childrenCache.getSize(), 1);
final LocalGroupsCacheAuthenticationListener listener = new LocalGroupsCacheAuthenticationListener();
listener.setParentGroupsCache(parentGroupsCache);
listener.setChildrenCache(childrenCache);
listener.userAuthenticated(person);
Assert.assertEquals(parentGroupsCache.getSize(), 0);
Assert.assertEquals(childrenCache.getSize(), 0);
}Example 82
| Project: wmata-gtfsrealtime-master File: WMATARealtimeModule.java View source code |
@Override
protected void configure() {
bind(CacheManager.class).toInstance(CacheManager.getInstance());
bind(Cache.class).annotatedWith(Names.named("caches.api")).toInstance(CacheManager.getInstance().getCache("wmataapi"));
bind(Cache.class).annotatedWith(Names.named("caches.trip")).toInstance(CacheManager.getInstance().getCache("wmatatrip"));
bind(Cache.class).annotatedWith(Names.named("caches.alertID")).toInstance(CacheManager.getInstance().getCache("wmataalertid"));
bind(CalendarServiceData.class).toProvider(CalendarServiceDataProvider.class).in(Scopes.SINGLETON);
bind(GtfsRelationalDao.class).toProvider(GtfsRelationalDaoProvider.class).in(Scopes.SINGLETON);
bind(TimeZone.class).annotatedWith(AgencyTimeZone.class).toProvider(AgencyTimeZoneProvider.class).in(Scopes.SINGLETON);
requestStaticInjection(DateTimeUtils.class);
}Example 83
| Project: cosmos-message-master File: EHCacheManagerImpl.java View source code |
public void flush() {
String[] names = this.manager.getCacheNames();
logger.debug("cache names is '{}'", names.toString());
if (names == null || names.length < 1) {
logger.warn("get null names!");
return;
}
for (String name : names) {
net.sf.ehcache.Cache cache = this.manager.getCache(name);
cache.removeAll();
}
}Example 84
| Project: filebot-master File: Cache.java View source code |
public Object computeIf(Object key, Predicate<Element> condition, Compute<?> compute) throws Exception {
// get if present
Element element = null;
try {
element = cache.get(key);
if (element != null && !condition.test(element)) {
return getElementValue(element);
}
} catch (Exception e) {
debug.warning(format("Cache computeIf: %s => %s", key, e));
}
// compute if absent
Object value = compute.apply(element);
put(key, value);
return value;
}Example 85
| Project: atricore-idbus-master File: EHCacheIdRegistry.java View source code |
public synchronized void init() {
if (init)
return;
ClassLoader orig = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(applicationContext.getClassLoader());
logger.info("Initializing EHCache ID Registry using cache " + cacheName);
if (cacheManager.cacheExists(cacheName)) {
logger.info("Cache already exists '" + cacheName + "', reusing it");
// This is probably a bundle restart, ignore it.
} else {
logger.info("Cache does not exists '" + cacheName + "', adding it");
cacheManager.addCache(cacheName);
}
cache = cacheManager.getCache(cacheName);
if (cache == null) {
logger.error("No chache definition found with name '" + cacheName + "'");
return;
} else {
if (logger.isTraceEnabled()) {
logger.trace("Initialized EHCache ID Registry using cache : " + cache);
logger.trace("Cache Bootstrap loader " + cache.getBootstrapCacheLoader());
logger.trace("Cache Bootstrap loader " + cache.getBootstrapCacheLoader());
logger.trace("Cache Event Notification service " + cache.getCacheEventNotificationService());
}
}
logger.info("Initialized EHCache ID Registry using cache " + cacheName + ". Size: " + cache.getSize());
init = true;
} finally {
Thread.currentThread().setContextClassLoader(orig);
}
}Example 86
| Project: BlinkCoder-master File: CacheKit.java View source code |
static Cache getOrAddCache(String cacheName) { Cache cache = cacheManager.getCache(cacheName); if (cache == null) { synchronized (cacheManager) { cache = cacheManager.getCache(cacheName); if (cache == null) { log.warn("Could not find cache config [" + cacheName + "], using default."); cacheManager.addCacheIfAbsent(cacheName); cache = cacheManager.getCache(cacheName); log.debug("Cache [" + cacheName + "] started."); } } } return cache; }
Example 87
| Project: cas-master File: LdaptiveResourceCRLFetcherTests.java View source code |
@Test
public void getCrlFromLdap() throws Exception {
CacheManager.getInstance().removeAllCaches();
final Cache cache = new Cache("crlCache-1", 100, false, false, 20, 10);
CacheManager.getInstance().addCache(cache);
for (int i = 0; i < 10; i++) {
final CRLDistributionPointRevocationChecker checker = new CRLDistributionPointRevocationChecker(false, new AllowRevocationPolicy(), null, cache, fetcher, true);
final X509Certificate cert = CertUtils.readCertificate(new ClassPathResource("ldap-crl.crt"));
checker.check(cert);
}
}Example 88
| Project: cayenne-master File: EhCacheQueryCache_WithConfigTest.java View source code |
@Test
public void testRemoveGroup_WithFactory_WithCacheGroups() {
EhCacheQueryCache cache = new EhCacheQueryCache(cacheManager);
ArrayList[] lists = new ArrayList[] { new ArrayList<>(), new ArrayList<>(), new ArrayList<>() };
QueryCacheEntryFactory factory = mock(QueryCacheEntryFactory.class);
when(factory.createObject()).thenReturn(lists[0], lists[1], lists[2]);
QueryMetadata md = mock(QueryMetadata.class);
when(md.getCacheKey()).thenReturn("k1");
when(md.getCacheGroups()).thenReturn(new String[] { "cg1" });
assertEquals(lists[0], cache.get(md, factory));
assertEquals(lists[0], cache.get(md, factory));
Cache c1 = cache.cacheManager.getCache("cg1");
assertEquals(201, c1.getCacheConfiguration().getTimeToLiveSeconds());
// remove non-existing
cache.removeGroup("cg0");
assertEquals(lists[0], cache.get(md, factory));
Cache c2 = cache.cacheManager.getCache("cg1");
assertSame(c1, c2);
assertEquals(201, c2.getCacheConfiguration().getTimeToLiveSeconds());
cache.removeGroup("cg1");
assertEquals(lists[1], cache.get(md, factory));
// make sure the cache still has all the configured settings after
// 'removeGroup'
Cache c3 = cache.cacheManager.getCache("cg1");
assertSame(c1, c3);
assertEquals(201, c3.getCacheConfiguration().getTimeToLiveSeconds());
}Example 89
| Project: com.idega.hibernate-master File: IWCacheProvider.java View source code |
public Cache buildCache(String name, Properties properties) throws CacheException { try { net.sf.ehcache.Cache cache = this.manager.getCache(name); if (cache == null) { LOG.warn("Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults."); this.manager.addCache(name); cache = this.manager.getCache(name); LOG.debug("started EHCache region: " + name); } return new net.sf.ehcache.hibernate.EhCache(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } }
Example 90
| Project: darks-orm-master File: EhCacheProvider.java View source code |
/**
* ³õʼ»¯EHCACHE
*/
public boolean initialize(CacheContext cacheContext) {
this.cacheContext = cacheContext;
if (!isClassLoaded())
return false;
Configuration cfg = SessionContext.getConfigure();
if (cfg == null)
return false;
CacheConfiguration cacheCfg = cfg.getCacheConfig();
if (cacheCfg == null)
return false;
ConcurrentMap<String, CacheConfigData> caches = cacheCfg.getCacheMap();
for (Entry<String, CacheConfigData> entry : caches.entrySet()) {
CacheConfigData data = entry.getValue();
if (data.getCacheEnumType() != CacheScopeType.EHCache)
continue;
if (data.getEhcacheConfigPath() != null && !"".equals(data.getEhcacheConfigPath())) {
manager = new CacheManager(data.getEhcacheConfigPath());
String[] names = manager.getCacheNames();
for (String name : names) {
Cache cache = manager.getCache(name);
if (cache == null)
continue;
CacheFactory cacheFactory = new EhCacheFactory(this, cache);
cacheContext.addCacheFactory(name, cacheFactory);
}
break;
}
}
if (manager == null) {
manager = new CacheManager();
for (Entry<String, CacheConfigData> entry : caches.entrySet()) {
String cacheId = entry.getKey();
CacheConfigData data = entry.getValue();
if (data.getCacheEnumType() != CacheScopeType.EHCache)
continue;
net.sf.ehcache.config.CacheConfiguration cacheConfig = new net.sf.ehcache.config.CacheConfiguration(cacheId, data.getMaxObject()).overflowToDisk(data.isOverflowToDisk()).eternal(data.isEternal()).timeToLiveSeconds(data.getLiveTime()).timeToIdleSeconds(data.getIdleTime()).diskPersistent(data.isDiskPersistent()).diskExpiryThreadIntervalSeconds(data.getDiskExpiryThreadIntervalSeconds()).maxElementsOnDisk(data.getMaxElementsOnDisk()).memoryStoreEvictionPolicy(data.getMemoryStoreEvictionPolicy());
Cache cache = new Cache(cacheConfig);
manager.addCache(cache);
CacheFactory cacheFactory = new EhCacheFactory(this, cache);
cacheContext.addCacheFactory(cacheId, cacheFactory);
}
}
if (manager != null)
vaild = true;
return vaild;
}Example 91
| Project: directory-server-master File: ReplayCacheImplTest.java View source code |
/**
* Test that the cache is working well. We will create a new entry
* every 500 ms, with 4 different serverPrincipals.
*
* After this period of time, we should only have 2 entries in the cache
*/
@Test
public void testCacheSetting() throws Exception {
CacheManager cacheManager = null;
try {
// 1 sec
long clockSkew = 1000;
cacheManager = new CacheManager();
cacheManager.addCache("kdcReplayCache");
Cache ehCache = cacheManager.getCache("kdcReplayCache");
ehCache.getCacheConfiguration().setMaxElementsInMemory(4);
ehCache.getCacheConfiguration().setTimeToLiveSeconds(1);
ehCache.getCacheConfiguration().setTimeToIdleSeconds(1);
ehCache.getCacheConfiguration().setDiskExpiryThreadIntervalSeconds(1);
ReplayCacheImpl cache = new ReplayCacheImpl(ehCache, clockSkew);
int i = 0;
// Inject 4 entries
while (i < 4) {
KerberosPrincipal serverPrincipal = new KerberosPrincipal("server" + i + "@APACHE.ORG", PrincipalNameType.KRB_NT_PRINCIPAL.getValue());
KerberosPrincipal clientPrincipal = new KerberosPrincipal("client" + i + "@APACHE.ORG", PrincipalNameType.KRB_NT_PRINCIPAL.getValue());
cache.save(serverPrincipal, clientPrincipal, new KerberosTime(System.currentTimeMillis()), 0);
i++;
}
List<?> keys = ehCache.getKeys();
// We should have 4 entries
assertTrue(keys.size() != 0);
// Wait till the timetolive time exceeds
Thread.sleep(1200);
// then access the cache so that the objects present in the cache will be expired
for (Object k : keys) {
assertNull(ehCache.get(k));
}
assertEquals(0, ehCache.getKeys().size());
} finally {
if (cacheManager != null) {
cacheManager.shutdown();
}
}
}Example 92
| Project: exchange-ws-client-master File: AutodiscoverIntegrationTest.java View source code |
@Test
public void getEndpointForEmailTwice() throws AutodiscoverException {
Cache cache = ehCacheManager.getCache("autodiscoverCache");
cache.clearStatistics();
cache.setStatisticsEnabled(true);
Cache autodiscoverCache = ehCacheManager.getCache("autodiscoverCache");
String endpointUri = compositeAutodiscoverService.getAutodiscoverEndpoint(upn);
log.info(endpointUri);
assertEquals(1, autodiscoverCache.getStatistics().getMemoryStoreObjectCount());
assertEquals(0, autodiscoverCache.getStatistics().getCacheHits());
assertEquals(1, autodiscoverCache.getStatistics().getCacheMisses());
endpointUri = compositeAutodiscoverService.getAutodiscoverEndpoint(upn);
log.info(endpointUri);
assertEquals(1, autodiscoverCache.getStatistics().getMemoryStoreObjectCount());
assertEquals(1, autodiscoverCache.getStatistics().getCacheHits());
assertEquals(1, autodiscoverCache.getStatistics().getCacheMisses());
}Example 93
| Project: guj.com.br-master File: EhCacheEngine.java View source code |
public void add(String fullyQualifiedName, String key, Object value) {
if (!manager.cacheExists(fullyQualifiedName)) {
try {
manager.addCache(fullyQualifiedName);
} catch (CacheException ce) {
log.error(ce, ce);
throw new RuntimeException(ce);
}
}
Cache cache = manager.getCache(fullyQualifiedName);
Element element = new Element(key, (Serializable) value);
cache.put(element);
}Example 94
| Project: imic-master File: CacheManager.java View source code |
private void initCacheManager(CacheConfiguration cacheConfiguration, String diskStorePath) {
DiskStoreConfiguration dsc = new DiskStoreConfiguration();
dsc.setPath(diskStorePath);
Configuration cacheConfig = new Configuration();
cacheConfig.addDiskStore(dsc);
cacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU);
cacheConfiguration.persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP));
cacheManager = new net.sf.ehcache.CacheManager(cacheConfig);
lockWriteCache();
imageCache = new Cache(cacheConfiguration);
cacheManager.addCache(imageCache);
cacheConfig.setDefaultCacheConfiguration(cacheConfiguration);
unlockWriteCache();
}Example 95
| Project: janrain-backplane-2-master File: CachedL1.java View source code |
@Override
public Object getObject(String key) {
if (!isEnabled) {
return null;
}
try {
Cache cache = CacheManager.getInstance().getCache("memory");
Element element = cache.get(key);
if (element != null) {
return element.getObjectValue();
} else {
return null;
}
} catch (Exception e) {
logger.warn("L1 cache failed to get", e);
return null;
}
}Example 96
| Project: jfinal-master File: CacheKit.java View source code |
static Cache getOrAddCache(String cacheName) { Cache cache = cacheManager.getCache(cacheName); if (cache == null) { synchronized (locker) { cache = cacheManager.getCache(cacheName); if (cache == null) { log.warn("Could not find cache config [" + cacheName + "], using default."); cacheManager.addCacheIfAbsent(cacheName); cache = cacheManager.getCache(cacheName); log.debug("Cache [" + cacheName + "] started."); } } } return cache; }
Example 97
| Project: jforum2-master File: EhCacheEngine.java View source code |
public void add(String fullyQualifiedName, String key, Object value) {
if (!manager.cacheExists(fullyQualifiedName)) {
try {
manager.addCache(fullyQualifiedName);
} catch (CacheException ce) {
log.error(ce, ce);
throw new RuntimeException(ce);
}
}
Cache cache = manager.getCache(fullyQualifiedName);
Element element = new Element(key, (Serializable) value);
cache.put(element);
}Example 98
| Project: Kylin-master File: LdapProvider.java View source code |
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Authentication authed = null;
Cache userCache = cacheManager.getCache("UserCache");
md.reset();
byte[] hashKey = md.digest((authentication.getName() + authentication.getCredentials()).getBytes());
String userKey = Arrays.toString(hashKey);
Element authedUser = userCache.get(userKey);
if (null != authedUser) {
authed = (Authentication) authedUser.getObjectValue();
SecurityContextHolder.getContext().setAuthentication(authed);
} else {
try {
authed = super.authenticate(authentication);
userCache.put(new Element(userKey, authed));
} catch (AuthenticationException e) {
logger.error("Failed to auth user: " + authentication.getName(), e);
throw e;
}
UserDetails user = new User(authentication.getName(), "skippped-ldap", authed.getAuthorities());
if (!userService.userExists(authentication.getName())) {
userService.createUser(user);
} else {
userService.updateUser(user);
}
}
return authed;
}Example 99
| Project: onebusaway-application-modules-master File: PreCacheTask.java View source code |
@Override
public void run() {
// Clear all existing cache elements
for (String cacheName : _cacheManager.getCacheNames()) {
Cache cache = _cacheManager.getCache(cacheName);
cache.removeAll();
}
try {
List<AgencyWithCoverageBean> agenciesWithCoverage = _service.getAgenciesWithCoverage();
for (AgencyWithCoverageBean agencyWithCoverage : agenciesWithCoverage) {
AgencyBean agency = agencyWithCoverage.getAgency();
System.out.println("agency=" + agency.getId());
ListBean<String> stopIds = _service.getStopIdsForAgencyId(agency.getId());
for (String stopId : stopIds.getList()) {
System.out.println(" stop=" + stopId);
_service.getStop(stopId);
}
ListBean<String> routeIds = _service.getRouteIdsForAgencyId(agency.getId());
for (String routeId : routeIds.getList()) {
System.out.println(" route=" + routeId);
_service.getStopsForRoute(routeId);
}
}
Set<AgencyAndId> shapeIds = new HashSet<AgencyAndId>();
for (TripEntry trip : _transitGraphDao.getAllTrips()) {
AgencyAndId shapeId = trip.getShapeId();
if (shapeId != null && shapeId.hasValues())
shapeIds.add(shapeId);
}
for (AgencyAndId shapeId : shapeIds) {
System.out.println("shape=" + shapeId);
_service.getShapeForId(AgencyAndIdLibrary.convertToString(shapeId));
}
} catch (ServiceException ex) {
_log.error("service exception", ex);
}
}Example 100
| Project: ORCID-Source-master File: OrcidEhCacheFactoryBean.java View source code |
@Override
public void afterPropertiesSet() throws Exception {
Ehcache existingCache = cacheManager.getEhcache(cacheName);
String diskStorePath = cacheManager.getConfiguration().getDiskStoreConfiguration().getPath();
LOGGER.debug("Cache manager disk store path = " + diskStorePath);
if (existingCache == null) {
CacheConfiguration config = createConfig();
if (cacheEntryFactory != null) {
this.cache = new SelfPopulatingCache(new Cache(config), cacheEntryFactory);
} else {
this.cache = new Cache(config);
}
cacheManager.addCache(this.cache);
} else {
this.cache = existingCache;
}
}Example 101
| Project: richfaces-master File: EhCacheCacheFactory.java View source code |
public Cache createCache(FacesContext facesContext, String cacheName, Map<?, ?> env) { LOG.info("Creating EhCache cache instance"); int maxCacheSize = getIntConfigurationValue(facesContext, CoreConfiguration.Items.resourcesCacheSize); boolean preconfiguredCache = false; Ehcache ehcache = cacheManager.getEhcache(cacheName); if (ehcache == null) { ehcache = new net.sf.ehcache.Cache(cacheName, maxCacheSize, false, true, 0, 0); } else { preconfiguredCache = true; if (ehcache.getCacheConfiguration().getMaxEntriesLocalHeap() <= 0) { LOG.info(MessageFormat.format("Maximum cache size hasn''t been set, resetting to {0} max items", maxCacheSize)); ehcache.getCacheConfiguration().setMaxEntriesLocalHeap(maxCacheSize); } } ehcache.setCacheManager(cacheManager); return new EhCacheCache(ehcache, preconfiguredCache); }