/** * See {@link #testCacheEntryFactoryReturningElementMake} this test ensures the Refresh * functionality works */ @Test public void testCacheEntryFactoryReturningElementRefresh() throws Exception { final long specialVersionNumber = 54321L; final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Element e = new Element(key, "V_" + key); e.setVersion(specialVersionNumber); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); Element e = null; e = selfPopulatingCache.get("key1"); assertEquals("V_key1", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); e = selfPopulatingCache.get("key2"); assertEquals("V_key2", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); assertEquals(2, selfPopulatingCache.getSize()); selfPopulatingCache.refresh(); e = selfPopulatingCache.get("key1"); assertEquals("V_key1", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); e = selfPopulatingCache.get("key2"); assertEquals("V_key2", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); assertEquals(2, selfPopulatingCache.getSize()); }
@Test public void testSupportsCopyOnRead() { Element element = new Element(KEY, "Some String", 1); xaStore.put(element); Element copy = xaStore.get(KEY); assertNotNull(copy); assertNotSame(copy, xaStore.get(KEY)); assertEquals("Some String", copy.getValue()); assertEquals(copy.getValue(), xaStore.get(KEY).getValue()); assertNotSame(copy.getValue(), xaStore.get(KEY).getValue()); }
@Override public synchronized void updateEntry(final String key, final HttpCacheUpdateCallback callback) throws IOException, HttpCacheUpdateException { int numRetries = 0; do { final Element oldElement = cache.get(key); HttpCacheEntry existingEntry = null; if (oldElement != null) { final byte[] data = (byte[]) oldElement.getValue(); existingEntry = serializer.readFrom(new ByteArrayInputStream(data)); } final HttpCacheEntry updatedEntry = callback.update(existingEntry); if (existingEntry == null) { putEntry(key, updatedEntry); return; } else { // Attempt to do a CAS replace, if we fail then retry // While this operation should work fine within this instance, multiple instances // could trample each others' data final ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializer.writeTo(updatedEntry, bos); final Element newElement = new Element(key, bos.toByteArray()); if (cache.replace(oldElement, newElement)) { return; } else { numRetries++; } } } while (numRetries <= maxUpdateRetries); throw new HttpCacheUpdateException("Failed to update"); }
/** Tests the expiry notifier. Check a reported scenario */ @Test public void testExpiryNotifications() throws InterruptedException { Serializable key = "1"; Element element = new Element(key, new Date()); TestCacheEventListener cacheEventListener = new TestCacheEventListener(); cache.getCacheEventNotificationService().registerListener(cacheEventListener); // Put cache.put(element); // expire Thread.sleep(15000); for (int i = 0; i < cache.getCacheConfiguration().getMaxEntriesLocalHeap(); i++) { cache.put(new Element(i, i)); cache.get(i); // makes sure the entry is flushed } assertThat(cacheEventListener.counter.get(), equalTo(1)); // the TestCacheEventListener does a put of a new Element with the same key on expiry assertNotNull(cache.get(key)); Element newElement = cache.get(key); assertNotNull(newElement); assertEquals("set on notify", newElement.getValue()); // Check counting listener CountingCacheEventListener listener = getCountingCacheEventListener(cache); List<CacheEvent> notifications = listener.getCacheElementsExpired(); assertThat(notifications, hasSize(1)); assertEquals(element, notifications.get(0).getElement()); // check for NPE cache.remove(null); }
/** 主方法 如果某方法可被缓存就缓存其结果 方法结果必须是可序列化的(serializable) */ public Object invoke(MethodInvocation invocation) throws Throwable { String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); Object result; logger.info("在缓存中查找方法返回的对象!"); String cacheKey = getCacheKey(targetName, methodName, arguments); Element element = cache.get(cacheKey); if (element == null) { logger.info("正在拦截方法!"); result = invocation.proceed(); logger.info("正在缓存对象!"); element = new Element(cacheKey, (Serializable) result); cache.put(element); } return element.getValue(); }
/** * Retrieve the missed cache item from the specified cache. * * @param key the unique key for the cache item * @param cacheName the name of the cache - this is the cache region name from ehcache config * @param <T> the type of the cache item * @return the cache item instance */ protected <T> T getObjectFromCache(String key, String cacheName) { Element cacheElement = getCache(cacheName).get(key); if (cacheElement != null) { return (T) cacheElement.getValue(); } return null; }
@Override public <T extends GeneralMessage> boolean isNewMessage(String userId, T message, Class<T> T) { Cache cache = cm.getCache("Messages"); String key = message.getUniqueFieldValue() + userId; Element element = cache.get(key); if (element != null) { return (Boolean) element.getValue(); } Query<UnreaddenMessage> isUnread = ds.createQuery(UnreaddenMessage.class) .field("userId") .equal(userId) .field("message") .equal(new Key<T>(T, message.getId())); Query<ReaddenMessage> isRead = ds.createQuery(ReaddenMessage.class) .field("userId") .equal(userId) .field("messageUniqueId") .equal(message.getUniqueFieldValue().toString()); Boolean newMessage = isUnread.countAll() <= 0 && isRead.countAll() <= 0; element = new Element(key, new Boolean(false)); cache.put(element); return newMessage; }
public V get(final K key) { Element element = this.cache.get(key); if (element != null) { return (V) element.getValue(); } return null; }
@Override public void doResponse() { // TODO Auto-generated method stub try { String platform = request.getParameter("p"); platform = platform == null ? "android" : platform; String cacheIndex = REQUEST_TYPE + ",p:" + platform; UtilFunctions.serverLog("cacheIndex:" + cacheIndex); String responseData = null; Element element = null; if ((element = cache.get(cacheIndex)) != null /*cache.isKeyInCache(cacheIndex)*/) { responseData = (String) element.getValue(); // System.out.println(REQUEST_TYPE+":缓存数据"); UtilFunctions.serverLog(REQUEST_TYPE + CACHE_DATA); } else { VersionService versionService = (VersionService) context.getBean("versionService"); Version version = versionService.getLatestVersion( platform == null ? VersionService.PLATFORM_ANDROID : platform); if (version == null) { UtilFunctions.serverLog(REQUEST_TYPE + "version is null"); return; } responseData = version.getJSONObject().toString(); cache.put(new Element(cacheIndex, responseData)); // System.out.println(REQUEST_TYPE+":非缓存数据"); UtilFunctions.serverLog(REQUEST_TYPE + NOT_CACHE_DATA); } PrintWriter pw = response.getWriter(); pw.write(responseData); pw.close(); } catch (IOException e) { e.printStackTrace(); } }
public <T extends ISocioObject> void saveObject(T object) throws DuplicateMySocioObjectException { if (object instanceof IUniqueObject) { IUniqueObject uniqueObject = (IUniqueObject) object; Cache cache = cm.getCache("Objects"); String key = uniqueObject.getUniqueFieldName() + uniqueObject.getUniqueFieldValue(); Element element = cache.get(key); if (element != null) { ((SocioObject) object).setId((ObjectId) element.getValue()); return; } @SuppressWarnings("unchecked") Query<T> q = (Query<T>) ds.createQuery(object.getClass()) .field(uniqueObject.getUniqueFieldName()) .equal(uniqueObject.getUniqueFieldValue()); T objectT = (T) q.get(); if (objectT != null) { ((SocioObject) object).setId(objectT.getId()); element = new Element(key, objectT.getId()); cache.put(element); logger.info( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); throw new DuplicateMySocioObjectException( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); } } ds.save(object); }
@Around("findTurmaEfetiva()") public Object findTurmaEfetivaMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-efetivas-cache"); Object[] args = joinPoint.getArgs(); Long turmaId = (Long) args[0]; Element element = cache.get(turmaId); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(turmaId, result)); } else { Logger.getLogger(this.getClass().getName()) .log( Level.INFO, "Dados presentes no cache de turmas, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
@Around("findAllComPendendias()") public Object findAllTurmasComPendenciasMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-pendencias-cache"); Object[] args = joinPoint.getArgs(); if (args[0] == null || args[1] == null) { result = joinPoint.proceed(); return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy"); String exercicio = df.format((Date) args[0]); String organizacao = ((Long) args[1]).toString(); String key = exercicio + "-" + organizacao; Element element = cache.get(key); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(key, result)); } else { Logger.getLogger(this.getClass().getName()) .log(Level.INFO, "Dados presentes no cache, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
/** {@inheritDoc} */ @Override public Integer getNewPmCountFor(String username) { Element cacheElementForUser = userDataCache.get(username); if (cacheElementForUser == null) { return null; } return (Integer) cacheElementForUser.getValue(); }
/** Tests fetching an entry. */ @Test public void testFetch() throws Exception { LOG.error("."); // Lookup final Element element = selfPopulatingCache.get("key"); assertEquals("value", element.getValue()); }
@Override @SuppressWarnings("unchecked") public Map<String, Product> getCachedProductList() { Element cachedCodeList = this.codeCache.get("productList"); if (cachedCodeList == null) { cacheCodeList(); } return (Map<String, Product>) cachedCodeList.getValue(); }
/** {@inheritDoc} */ @Override public void decrementNewMessageCountFor(String username) { Element cacheElementForUser = userDataCache.get(username); if (cacheElementForUser != null) { int count = (Integer) cacheElementForUser.getValue(); count--; userDataCache.put(new Element(username, count)); } }
public void notifyElementExpired(Ehcache cache, Element element) { JRadiusSession session = (JRadiusSession) element.getValue(); RadiusLog.debug("Expired session: " + session.getSessionKey()); if (JRadiusServer.getEventDispatcher() != null) { SessionExpiredEvent evt = new SessionExpiredEvent(session); evt.setApplicationContext(applicationContext); JRadiusServer.getEventDispatcher().post(evt); } }
protected Dashboard getDashboardFromCache(DashboardCacheKey key) { Dashboard dashboard; RepositoryAccess repository = RepositoryAccess.getRepository(); try { Cache cache = getCache(); Element cacheElement = cache.get(key); if (cacheElement == null) { return null; } else { dashboard = (Dashboard) cacheElement.getValue(); } logger.info("Got dashboard from cache"); ISolutionFile dash = repository.getSolutionFile(key.getCdfde(), FileAccess.READ); // was NO_PERM=0; if (dash == null) { logger.error(key.getCdfde() + " not found."); return null; } ISolutionFile templ; if (key.getTemplate() == null) { templ = null; } else { templ = repository.getSolutionFile(key.getTemplate(), FileAccess.READ); } /* Cache is invalidated if the dashboard or template have changed since * the cache was loaded, or at midnight every day, because of dynamic * generation of date parameters. */ Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 00); cal.set(Calendar.MINUTE, 00); cal.set(Calendar.SECOND, 1); boolean cacheInvalid = dash.getLastModified() > dashboard.getLoaded().getTime() || (templ != null && templ.getLastModified() > dashboard.getLoaded().getTime()), cacheExpired = cal.getTime().after(dashboard.getLoaded()); if (cacheExpired) { logger.info("Dashboard expired, re-rendering"); return null; } else if (cacheInvalid) { logger.info("Dashboard cache invalidated, re-rendering"); return null; } else { return dashboard; } } catch (CacheException ce) { logger.info("Dashboard cache invalidated, re-rendering"); return null; } }
@Override public synchronized HttpCacheEntry getEntry(final String key) throws IOException { final Element e = cache.get(key); if (e == null) { return null; } final byte[] data = (byte[]) e.getValue(); return serializer.readFrom(new ByteArrayInputStream(data)); }
public synchronized long incr(String key, int by) { Element e = cache.get(key); if (e == null) { return -1; } long newValue = ((Number) e.getValue()).longValue() + by; Element newE = new Element(key, newValue); newE.setTimeToLive(e.getTimeToLive()); cache.put(newE); return newValue; }
@Around("simplePointcut()") public Object aroundLogCalls(ProceedingJoinPoint joinPoint) throws Throwable { String targetName = joinPoint.getTarget().getClass().toString(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); // 试图得到标注的Ehcache类 @SuppressWarnings("unused") Method[] methods = joinPoint.getTarget().getClass().getMethods(); Ehcache flag = null; for (Method m : methods) { if (m.getName().equals(methodName)) { Class[] tmpCs = m.getParameterTypes(); if (tmpCs.length == arguments.length) { flag = m.getAnnotation(Ehcache.class); break; } } } if (flag == null) { return null; } // Ehcache flag // =joinPoint.getTarget().getClass().getMethod(methodName).getAnnotation(Ehcache.class); Object result; String cacheKey = getCacheKey(targetName, methodName, arguments); Element element = null; if (flag.eternal()) { // 永久缓存 element = dictCache.get(cacheKey); } else { // 临时缓存 element = eternalCache.get(cacheKey); } if (element == null) { if ((arguments != null) && (arguments.length != 0)) { result = joinPoint.proceed(arguments); } else { result = joinPoint.proceed(); } element = new Element(cacheKey, (Serializable) result); if (flag.eternal()) { // 永久缓存 dictCache.put(element); } else { // 临时缓存 eternalCache.put(element); } } return element.getValue(); }
@Override public ManageableSecurity loadSecurityDetail(ManageableSecurity base) { ManageableSecurity cached; Element e = _detailsCache.get(base.getUniqueId()); if (e != null) { cached = (ManageableSecurity) e.getValue(); } else { cached = _underlying.loadSecurityDetail(base); e = new Element(base.getUniqueId(), cached); _detailsCache.put(e); } return JodaBeanUtils.clone(cached); }
@Override public SellingContext getByGuid(final String sellingContextGuid) { Element element = getCache().get(sellingContextGuid); if (element != null && !element.isExpired()) { LOG.debug("get objecct from cache... guid: " + sellingContextGuid); return (SellingContext) element.getValue(); } LOG.debug("get objecct from database... guid: " + sellingContextGuid); SellingContext sellingContext = sellingContextService.getByGuid(sellingContextGuid); cache.put(new Element(sellingContextGuid, sellingContext)); return sellingContext; }
public Serializable get(Serializable key) { if (getEhcache().getStatus() == Status.STATUS_ALIVE) { try { Element element = getEhcache().get(key); if (element == null) { return null; } else { return element.getValue(); } } catch (Error ignore) { return null; } } return null; }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void removeCache(String cacheName, LookupCode lookupCode) { Cache cache = cacheManager.getCache("codeCache"); Element element = cache.get("codeList"); Map<String, List<LookupCode>> map = (Map<String, List<LookupCode>>) element.getValue(); List<LookupCode> lookupCodes = codeService.getCodeList(lookupCode); if (lookupCodes.size() == 0) { map.remove(lookupCode.getCodeGroup()); } else { map.put(lookupCode.getCodeGroup(), lookupCodes); } this.codeCache.put(new Element("codeList", map)); }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public List<LookupCode> appendCache(String cacheName, LookupCode lookupCode) { String lang = lookupCode.getLanguage(); lookupCode.setLanguage("ALL"); Cache cache = cacheManager.getCache("codeCache"); Element element = cache.get(cacheName); Map<String, List<LookupCode>> map = (Map<String, List<LookupCode>>) element.getValue(); List<LookupCode> lookupCodes = codeService.getCodeList(lookupCode); map.put(lookupCode.getCodeGroup(), lookupCodes); this.codeCache.put(new Element("codeList", map)); lookupCode.setLanguage(lang); return lookupCodes; }
private CnATreeElement getFromCache(CnATreeElement element) { final Element cachedElement = getCache().get(element.getUuid()); if (cachedElement != null) { element = (CnATreeElement) cachedElement.getValue(); if (getLog().isDebugEnabled()) { getLog() .debug("Element from cache: " + element.getTitle() + ", UUID: " + element.getUuid()); } } else { element = getDao().retrieve(element.getDbId(), RetrieveInfo.getPropertyInstance()); if (element != null) { getCache().put(new Element(element.getUuid(), element)); } } return element; }
private void oturumSayisiArtir() { GregorianCalendar gcal = new GregorianCalendar(); int minute = gcal.get(GregorianCalendar.MINUTE); int hour = gcal.get(GregorianCalendar.HOUR_OF_DAY); String statisticKey = "" + ((hour * 6) + (minute / 10)); Element element = getStatisticCache().get(statisticUUID + statisticKey); OturumStatistic oturumSayisi = null; if (element == null) { oturumSayisi = new OturumStatistic(statisticKey); } else { oturumSayisi = (OturumStatistic) element.getValue(); } oturumSayisi.oturumSayisiArtir(); Element element2 = new Element(statisticUUID + statisticKey, oturumSayisi); getStatisticCache().put(element2); }
public CasAuthentication get(String serviceTicket) { Element element = null; try { element = cache.get(serviceTicket); } catch (CacheException cacheException) { throw new CacheException("Cache failure: " + cacheException.getMessage()); } if (logger.isDebugEnabled()) { logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket); } if (element == null) { return null; } else { return (CasAuthentication) element.getValue(); } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Product appendProductCache(String cacheName, String prodCd) { Cache cache = cacheManager.getCache("codeCache"); Element element = cache.get(cacheName); Map<String, Product> map = (Map<String, Product>) element.getValue(); Product pdhProduct = new Product(); pdhProduct.setProdCd(prodCd); List<Product> products = pdhService.getAllProductList(pdhProduct); if (products != null && products.size() > 0) { map.put(prodCd, products.get(0)); return products.get(0); } else { // 할인상품이 있는 지 한번더 조회 한다. return pdhService.getDiscountProduct(pdhProduct); } }