/** * 获取name下所有缓存值 */ public <E> List<E> values(String name) { try { Set<String> elements = this.getElements(name); if (null != elements && !elements.isEmpty()) { List<String> keys = Lists.newArrayList(); for (String field : elements) { keys.add(this.getRedisKeyOfElement(name, field)); } return this.jedisTemplate.mget(keys); } else { return Collections.emptyList(); } } catch (Throwable t) { throw new CacheException(t); } }
/** * @return system property by name or default value if not * found. */ public String getSystemPropertyValue(final String propertyName, final String defaultValue) { try { final Cache cache = getSystemPropertyCache(); final Element element = cache.get(propertyName); if (element == null) { final String value = getSystemPropertyValueFromDB(propertyName, defaultValue); cache.put(new Element(propertyName, value)); return value; } else { return (String) element.getValue(); } } catch (final CacheException ignored) { return getSystemPropertyValueFromDB(propertyName, defaultValue); } }
public static void limpiarCache(String idDominio) throws CacheException{ log.debug("Queremos borrarCache: " + idDominio); String cacheName = PluginDominio.class.getName(); CacheManager cacheManager = CacheManager.getInstance(); Cache cache; if (cacheManager.cacheExists(cacheName)) { cache = cacheManager.getCache(cacheName); List keys = cache.getKeys(); log.debug("Queremos borrarCache: " + idDominio + " que tiene " + keys.size() + " elementos."); for (Iterator it=keys.iterator();it.hasNext();){ String key = (String) it.next(); int idx = key.indexOf(SEPARATOR); if(idx != -1) cache.remove(key); } } }
public static void limpiarCache(String idDominio) throws CacheException{ log.debug("Queremos borrarCache: " + idDominio); String cacheName = PluginAudita.class.getName(); CacheManager cacheManager = CacheManager.getInstance(); Cache cache; if (cacheManager.cacheExists(cacheName)) { cache = cacheManager.getCache(cacheName); List keys = cache.getKeys(); log.debug("Queremos borrarCache: " + idDominio + " que tiene " + keys.size() + " elementos."); for (Iterator it=keys.iterator();it.hasNext();){ String key = (String) it.next(); int idx = key.indexOf(SEPARATOR); if(idx != -1) cache.remove(key); } } }
@Test public void testCacheManagerConflict() throws Exception { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.setCacheManagerName("myCacheManager"); assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); assertTrue("Singleton property", cacheManagerFb.isSingleton()); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0); Cache myCache1 = cm.getCache("myCache1"); assertTrue("No myCache1 defined", myCache1 == null); EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean(); cacheManagerFb2.setCacheManagerName("myCacheManager"); cacheManagerFb2.afterPropertiesSet(); fail("Should have thrown CacheException because of naming conflict"); } catch (CacheException ex) { // expected } finally { cacheManagerFb.destroy(); } }
private Object getCacheAddress(String cacheKey) { Object cacheObject = null; try { myLog.debug("Try to get Cache Object for the key:" + cacheKey); Cache cache = cacheManager.getCache(CACHE_NAME); if (cache != null && cache.isElementInMemory(cacheKey) && cache.get(cacheKey) != null) { cacheObject = cache.get(cacheKey).getObjectValue(); } else { myLog.debug("Cache Object, key:" + cacheKey + " not found"); } } catch (CacheException ex) { myLog.error("Failed to get cached address: " + cacheKey, ex); } return cacheObject; }
/** * Loads the object with the provided key into the cache (called for instance * by getWithLoader if element not found in the cache. * * <p>If this loader is in preloading mode (as indicated by the <code>preload</code> * field, then this method looks for the object in the preload Map. If not * in preload mode, it will look for the object in the database directly. If * it is found in either of these, it will be loaded into the cache and * returned. If not found in either, nothing is added to the cache and null * is returned. * * <p>Notice that the returned null is never returned by a direct query to a * {@link C2monCache}, in which case a {@link CacheElementNotFoundException} is * thrown. */ @Override public Object load(Object key) throws CacheException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Fetching cache object with Id " + key + " from database."); } Object result = fetchFromDB(key); //put in cache if found something if (result != null) { cache.putQuiet(new Element(key, result)); } return result; }
/** * Actual creation of the singleton. * * @param config * the parsed EhCache configuration * @return the cache manager * @throws CacheException * in case the creation failed */ private static synchronized CacheManager internalCreateCacheManager(Configuration config) throws CacheException { if (SINGLETON != null) { extendEhCacheWithCustomConfig(SINGLETON, config); } else { // for better control over the files created by the application override the diskstore // path // for flushing cached data to disk overrideDiskStorePath(config); // disable the update check config.setUpdateCheck(false); SINGLETON = new CacheManager(config); } return SINGLETON; }
public void process(Exchange exchange) throws Exception { LOG.trace("Cache Name: {}", config.getCacheName()); Map<String, Object> headers = exchange.getIn().getHeaders(); String key = (headers.containsKey(CacheConstants.CACHE_KEY)) ? exchange.getIn().getHeader(CacheConstants.CACHE_KEY, String.class) : getEndpoint().getKey(); String operation = (headers.containsKey(CacheConstants.CACHE_OPERATION)) ? (String)headers .get(CacheConstants.CACHE_OPERATION) : getEndpoint().getOperation(); if (operation == null) { throw new CacheException(CacheConstants.CACHE_OPERATION + " header not specified in message"); } if ((key == null) && (!checkIsEqual(operation, CacheConstants.CACHE_OPERATION_DELETEALL))) { throw new CacheException(CacheConstants.CACHE_KEY + " is not specified in message header or endpoint URL."); } performCacheOperation(exchange, operation, key); //cleanup the cache headers exchange.getIn().removeHeader(CacheConstants.CACHE_KEY); exchange.getIn().removeHeader(CacheConstants.CACHE_OPERATION); }
private void dispatchExchange(Ehcache cache, Element element, String operation) { Exchange exchange; LOG.debug("Consumer Dispatching the Exchange containing the Element {} in cache {}", element, cache.getName()); if (element == null) { exchange = cacheConsumer.getEndpoint().createCacheExchange(operation, "", ""); } else { exchange = cacheConsumer.getEndpoint().createCacheExchange(operation, (String) element.getObjectKey(), element.getObjectValue()); } try { cacheConsumer.getProcessor().process(exchange); } catch (Exception e) { throw new CacheException("Error in consumer while dispatching exchange containing key " + (element != null ? element.getObjectKey() : null) + " for further processing", e); } }
@Test public void testAddingDataToCacheDoesFailOnEmptyBody() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { onException(CacheException.class). handled(true). to("log:LOGGER"). to("mock:CacheProducerTest.cacheException"); from("direct:a"). setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD)). setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")). to("cache://TestCache1"); } }); resultEndpoint.expectedMessageCount(0); cacheExceptionEndpoint.expectedMessageCount(1); context.start(); log.debug("------------Beginning CacheProducer Add Does Fail On Empty Body Test---------------"); sendEmptyBody(); resultEndpoint.assertIsSatisfied(); cacheExceptionEndpoint.assertIsSatisfied(); }
@Test public void testUpdatingDataInCacheDoesFailOnEmptyBody() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { onException(CacheException.class). handled(true). to("log:LOGGER"). to("mock:CacheProducerTest.cacheException"); from("direct:a"). setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_UPDATE)). setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")). to("cache://TestCache1"); } }); cacheExceptionEndpoint.expectedMessageCount(1); context.start(); log.debug("------------Beginning CacheProducer Update Does Fail On Empty Body Test---------------"); sendEmptyBody(); cacheExceptionEndpoint.assertIsSatisfied(); }
@Test public void testDeletingDataFromCacheDoesNotFailOnEmptyBody() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { onException(CacheException.class). handled(true). to("log:LOGGER"). to("mock:CacheProducerTest.cacheException"); from("direct:a"). setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_DELETE)). setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")). to("cache://TestCache1"); } }); cacheExceptionEndpoint.expectedMessageCount(0); context.start(); log.debug("------------Beginning CacheProducer Delete Does Not Fail On Empty Body Test---------------"); sendEmptyBody(); cacheExceptionEndpoint.assertIsSatisfied(); }
@Test public void testDeletingAllDataFromCacheDoesNotFailOnEmptyBody() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { onException(CacheException.class). handled(true). to("log:LOGGER"). to("mock:CacheProducerTest.cacheException"); from("direct:a"). setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_DELETEALL)). to("cache://TestCache1"); } }); cacheExceptionEndpoint.expectedMessageCount(0); context.start(); log.debug("------------Beginning CacheProducer Delete All Elements Does Not Fail On Empty Body Test---------------"); sendEmptyBody(); cacheExceptionEndpoint.assertIsSatisfied(); }
@Test public void testUnknownOperation() throws Exception { context.addRoutes(new RouteBuilder() { public void configure() { onException(CacheException.class). handled(true). to("log:LOGGER"). to("mock:CacheProducerTest.cacheException"); from("direct:a"). setHeader(CacheConstants.CACHE_OPERATION, constant("UNKNOWN")). setHeader(CacheConstants.CACHE_KEY, constant("Ralph_Waldo_Emerson")). to("cache://TestCache1"). to("mock:CacheProducerTest.result"); } }); resultEndpoint.expectedMessageCount(0); cacheExceptionEndpoint.expectedMessageCount(1); context.start(); log.debug("------------Beginning CacheProducer Query An Elements Test---------------"); sendUpdatedFile(); resultEndpoint.assertIsSatisfied(); cacheExceptionEndpoint.assertIsSatisfied(); }
public void afterPropertiesSet() throws IOException, CacheException { log.info("Initializing EHCache CacheManager"); Configuration config = null; if (this.configLocation != null) { config = ConfigurationFactory .parseConfiguration(this.configLocation.getInputStream()); if (this.diskStoreLocation != null) { DiskStoreConfiguration dc = new DiskStoreConfiguration(); dc.setPath(this.diskStoreLocation.getFile().getAbsolutePath()); try { config.addDiskStore(dc); } catch (ObjectExistsException e) { log.warn("if you want to config distStore in spring," + " please remove diskStore in config file!", e); } } } if (config != null) { this.cacheManager = new CacheManager(config); } else { this.cacheManager = new CacheManager(); } if (this.cacheManagerName != null) { this.cacheManager.setName(this.cacheManagerName); } }
/** * Creates a unique cache manager. * * @param uniqueName the unique name, typically a test case class name * @return the unique cache manager, not null */ public static CacheManager createTestCacheManager(String uniqueName) { ArgumentChecker.notNull(uniqueName, "uniqueName"); if (UNIQUE_TEST_NAMES.putIfAbsent(uniqueName, uniqueName) != null) { throw new OpenGammaRuntimeException("CacheManager has already been created with unique name: " + uniqueName); } try { InputStream configStream = getTestEhCacheConfig(); Configuration config = ConfigurationFactory.parseConfiguration(configStream); config.setName(uniqueName); config.setUpdateCheck(false); return CacheManager.newInstance(config); } catch (CacheException ex) { throw new OpenGammaRuntimeException("Unable to create CacheManager", ex); } }
private static void logEvent(Ehcache cache, Element elem, CacheEventType eventType) { int cacheApproxSize = -1; if (cache.getStatus() == Status.STATUS_ALIVE) { try { cacheApproxSize = cache.getSize(); } catch (CacheException | IllegalStateException ignored) { } } LoggingEvent loggingEvent = new LoggingEvent(Logger.FQCN, LOGGER, Level.TRACE, String.format(MSG_FORMAT, cache.getName(), cache.getStatus(), cacheApproxSize, elem.getObjectKey(), eventType.getId()), null, null); StackTraceElement[] stackFrames = new Throwable().getStackTrace(); for (int a = 1; a < stackFrames.length; a++) { if (!STACK_SKIP_CLASS_NAMES.contains(stackFrames[a].getClassName())) { stackFrames = ArrayUtils.subarray(stackFrames, a, stackFrames.length); break; } } loggingEvent.setCallerData(stackFrames); LOGGER.callAppenders(loggingEvent); }
/** * Gets a value of an element which matches the given key. * * @param key the key of the element to return. * @return The value placed into the cache with an earlier put, or null if not found or expired * @throws org.jpublish.JPublishCacheException * */ public Object get(Object key) throws JPublishCacheException { try { if (key == null) throw new JPublishCacheException("Invalid key specification: null"); else { Element element = cache.get((Serializable) key); if (element == null) { if (log.isDebugEnabled()) log.debug("null Element for key: [" + key + "]; (re)loading."); return null; } else { return element.getValue(); } } } catch (CacheException e) { throw new JPublishCacheException(e); } }
private static CacheManager getCacheManager() { if (cacheManager == null) { if (System.getProperty("red5.root") != null) { // we're running Red5 as a server. try { cacheManager = new CacheManager(System.getProperty("red5.root") + File.separator + "conf" + File.separator + "ehcache.xml"); } catch (CacheException e) { cacheManager = constructDefault(); } } else { // not a server, maybe running tests? cacheManager = constructDefault(); } } return cacheManager; }
protected void init() { super.init(); if(!initialized) { synchronized (this) { if(!initialized){ if(delegatedCache == null) throw new CacheException("Delegated cache does not exist..."); final Attribute<Integer> partitionSearchAttribute = delegatedCache.getSearchAttribute(PROPNAME_PARTITIONID); if(null == partitionSearchAttribute) throw new CacheException("Delegated cache should have a searchable attribute named " + PROPNAME_PARTITIONID); //schedule the timer pool to execute a cache search every 5 seconds...which in turn will execute the cache sync operations cacheTimerService.scheduleAtFixedRate(new TimedRefreshSyncOp(partitionSearchAttribute, this.partitionId), 0L, refreshInterval, refreshIntervalUnit); initialized = true; } } } }
@Override public Map<Object, Element> getAll(Collection<?> keys) throws IllegalStateException, CacheException, NullPointerException { init(); Map<Object, Element> result = new HashMap<Object, Element>(); Iterator<?> it = keys.iterator(); Future<Element> futs[] = new Future[keys.size()]; int count = 0; while(it.hasNext()) { futs[count++] = cacheSyncService.submit(new GetOp(it.next())); } for(int i = 0; i < count; i++) { Element el = null; try { el = futs[i].get(); }catch(Exception e) { log.warn("Error while getting the data from cache", e); } if(el != null && el.getValue() != null) { result.put(el.getObjectKey(), el); } } return result; }
public Object getCache(final Cache cache, final String cahceName) { Element element = null; try { element = cache.get(cahceName); } catch (CacheException cacheException) { throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage()); } if (logger.isTraceEnabled()) { logger.trace("Cache hit: " + (element != null) + "; Cache name: " + cahceName + " Name: " + cache.getName() + " ,size: " + cache.getSize()); } if (element == null) { return null; } else { return element.getValue(); } }
public void addCache(String cacheName) throws JPublishCacheException { try { CacheManager manager = CacheManager.getInstance(); cache = manager.getCache(cacheName); if (cache == null) { log.warn("Could not find a valid configuration for: " + cacheName + ", using the 'defaultCache' definition."); manager.addCache(cacheName); cache = manager.getCache(cacheName); } } catch (CacheException e) { throw new JPublishCacheException(e); } }
/** * 创建本地缓存 */ private Ehcache getEhcache(final String name) { Future<Ehcache> future = this.ehcaches.get(name); if (future == null) { Callable<Ehcache> callable = new Callable<Ehcache>() { @Override public Ehcache call() throws Exception { Ehcache cache = cacheManager.getEhcache(name); if (cache == null) { cacheManager.addCache(name); cache = cacheManager.getEhcache(name); } return cache; } }; FutureTask<Ehcache> task = new FutureTask<>(callable); future = this.ehcaches.putIfAbsent(name, task); if (future == null) { future = task; task.run(); } } try { return future.get(); } catch (Exception e) { this.ehcaches.remove(name); throw new CacheException(e); } }
public void monitor(Cache cache) { MetricRegistry registry = RegistryService.getMetricRegistry(); cache.registerCacheExtension(new CacheLifecycleListener(cache, registry) { @Override public void dispose() throws CacheException { getTimers.remove(cache.getName()); putTimers.remove(cache.getName()); super.dispose(); } }); }
private BuildRights cacheBuildRightSet(final int activeBuildID, final int userID, final BuildRights buildRights) { try { final Cache cache = getBuildRightSetCache(activeBuildID); if (cache != null) { cache.put(new Element(new Integer(userID), buildRights)); } } catch (CacheException e) { if (log.isDebugEnabled()) { log.debug("e: " + e); } } return buildRights; }
private ResultGroupRights cacheResultGroupRightSet(final int activeResultGroupID, final int userID, final ResultGroupRights buildRights) { try { final Cache cache = getResultGroupRightSetCache(activeResultGroupID); if (cache != null) { cache.put(new Element(new Integer(userID), buildRights)); } } catch (CacheException e) { if (log.isDebugEnabled()) { log.debug("e: " + e); } } return buildRights; }
/** * Returns true if error was reported withing retention period */ private boolean isErrorReported(final Error error) { boolean result; try { // calculate error hash final RetentionCache cache = getRetentionCache(); final Element elem = cache.get(error.getRetentionKey()); result = elem != null; } catch (CacheException e) { logHard("Error while checking error retention, will return false", e); result = false; } return result; }
/** * Marks error as reported */ private void markErrorReported(final Error error) { final Integer retentionCode = error.getRetentionKey(); try { final RetentionCache cache = getRetentionCache(); cache.put(new Element(retentionCode, retentionCode)); } catch (CacheException e) { logHard("Error while marking error as reported", e); } }
/** * Returns reference to retention cache */ private RetentionCache getRetentionCache() throws CacheException { final CacheManager manager = CacheManager.getInstance(); final Cache cache = manager.getCache("retention_cache"); if (cache == null) { return DUMMY_STATELESS_RETENTION_CACHE; } else { return new DelegatingRetentionCache(cache); } }
/** * Deletes all merge related data. * * @param activeMergeConfigurationID */ public void resetMerge(final int activeMergeConfigurationID) throws IOException { ConfigurationManager.runInHibernate(new TransactionCallback() { public Object runInTransaction() throws Exception { session.delete("from BranchMergeConfiguration bmc where bmc.activeMergeID = ?", new Integer(activeMergeConfigurationID), Hibernate.INTEGER); return null; } }); try { CacheUtils.resetAllCaches(); } catch (CacheException e) { throw IoUtils.createIOException("Error while resetting caches", e); } }
public static void resetAllCaches() throws CacheException, IOException { final CacheManager cacheManager = CacheManager.getInstance(); final String[] cacheNames = cacheManager.getCacheNames(); for (int i = 0; i < cacheNames.length; i++) { final String cacheName = cacheNames[i]; if (cacheName.equals("retention_cache")) continue; //if (log.isDebugEnabled()) log.debug("cache hits before setup: " + cacheName + "/" + cache.getHitCount()); cacheManager.getCache(cacheName).removeAll(); } }
@Override @Transactional public void load(Ehcache ehcache) throws CacheException { int i = 1, total = 12; log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", false, false), kmlService.getAllStagesKml("track", false, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", false, true), kmlService.getAllStagesKml("track", false, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", true, false), kmlService.getAllStagesKml("track", true, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("track", true, true), kmlService.getAllStagesKml("track", true, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", false, false), kmlService.getAllStagesKml("marcadores", false, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", false, true), kmlService.getAllStagesKml("marcadores", false, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", true, false), kmlService.getAllStagesKml("marcadores", true, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("marcadores", true, true), kmlService.getAllStagesKml("marcadores", true, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", false, false), kmlService.getAllStagesKml("servicios", false, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", false, true), kmlService.getAllStagesKml("servicios", false, true), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", true, false), kmlService.getAllStagesKml("servicios", true, false), true)); log.info("Caching KML {}/{}...", i++, total); ehcache.put(new Element(new SimpleKey("servicios", true, true), kmlService.getAllStagesKml("servicios", true, true), true)); log.info("Caching done!"); }
/** * @ejb.interface-method * @ejb.permission role-name="${role.operador}" */ public Long grabarDominio(Dominio obj, Long idOrg) { Session session = getSession(); try { if(obj.getCacheable() == 'N') { PluginDominio.limpiarCache(obj.getIdentificador()); } if ( obj.getCodigo() == null ) { OrganoResponsable org = (OrganoResponsable) session.load(OrganoResponsable.class,idOrg); org.addDominio( obj ); session.flush(); } else { //if ( !obj.getOrganoResponsable().getCodigo().equals( idOrg ) ) session.update( obj ); } //session.saveOrUpdate(obj); return obj.getCodigo(); } catch (HibernateException he) { throw new EJBException(he); } catch (CacheException e) { throw new EJBException(e); } finally { close(session); } }
private static Cache getCache() throws CacheException { String cacheName = PluginDominio.class.getName(); CacheManager cacheManager = CacheManager.getInstance(); Cache cache; if (cacheManager.cacheExists(cacheName)) { cache = cacheManager.getCache(cacheName); } else { // Cache(String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds) // cache = new Cache(cacheName, 1000, false, false, 3000, 300); cache = new Cache(cacheName, 1000, false, false, ConstantesSTR.TIEMPO_EN_CACHE, 300); cacheManager.addCache(cache); } return cache; }
protected Serializable getFromCache(Serializable key) throws CacheException { Cache cache = getCache(); Element element = cache.get(key); if (element != null && !cache.isExpired(element)) { return element.getValue(); } else { return null; } }
private static Cache getCache() throws CacheException { String cacheName = PluginAudita.class.getName(); CacheManager cacheManager = CacheManager.getInstance(); Cache cache; if (cacheManager.cacheExists(cacheName)) { cache = cacheManager.getCache(cacheName); } else { // Cache(String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds) // cache = new Cache(cacheName, 1000, false, false, 3000, 300); cache = new Cache(cacheName, 1000, false, false, Constants.TIEMPO_EN_CACHE, 300); cacheManager.addCache(cache); } return cache; }