/** * Called immediately after an element has been put into the cache and the element already existed * in the cache. This is thus an update. * * <p>The {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method will block until this * method returns. * * <p>Implementers may wish to have access to the Element's fields, including value, so the * element is provided. Implementers should be careful not to modify the element. The effect of * any modifications is undefined. * * @param cache the cache emitting the notification * @param element the element which was just put into the cache. */ public final void notifyElementUpdated(final Ehcache cache, final Element element) throws CacheException { if (notAlive()) { return; } if (!replicateUpdates) { return; } if (replicateUpdatesViaCopy) { if (!element.isSerializable()) { if (LOG.isWarnEnabled()) { LOG.warn( "Object with key " + element.getObjectKey() + " is not Serializable and cannot be updated via copy."); } return; } addToReplicationQueue(new CacheEventMessage(EventMessage.PUT, cache, element, null)); } else { if (!element.isKeySerializable()) { if (LOG.isWarnEnabled()) { LOG.warn( "Object with key " + element.getObjectKey() + " does not have a Serializable key and cannot be replicated via invalidate."); } return; } addToReplicationQueue( new CacheEventMessage(EventMessage.REMOVE, cache, null, element.getKey())); } }
private PagsGroup initGroupDef(IPersonAttributesGroupDefinition group) { Element element = this.pagsGroupCache.get(group.getName()); if (element != null) { return (PagsGroup) element.getObjectValue(); } PagsGroup groupDef = new PagsGroup(); groupDef.setKey(group.getName()); groupDef.setName(group.getName()); groupDef.setDescription(group.getDescription()); addMemberKeys(groupDef, group.getMembers()); Set<IPersonAttributesGroupTestGroupDefinition> testGroups = group.getTestGroups(); for (IPersonAttributesGroupTestGroupDefinition testGroup : testGroups) { TestGroup tg = new TestGroup(); Set<IPersonAttributesGroupTestDefinition> tests = testGroup.getTests(); for (IPersonAttributesGroupTestDefinition test : tests) { IPersonTester testerInst = initializeTester(test); if (testerInst == null) { /* * A tester was intended that we cannot now recreate. This * is a potentially dangerous situation, since tests in PAGS * are "or-ed" together; a functioning group with a missing * test would have a wider membership, not narrower. (And * remember -- permissions are tied to groups.) We need to * play it safe and keep this group out of the mix. */ return null; } tg.addTest(testerInst); } groupDef.addTestGroup(tg); } element = new Element(group.getName(), groupDef); this.pagsGroupCache.put(element); return groupDef; }
@Override public Task getTask(TaskID taskID, boolean loadCompletely, boolean forceAPICall) { if (taskID == null) { throw new NullPointerException(); } Task task; if (cacheActivated) { if (!forceAPICall) { Element element = cache.get(taskID); if (element != null) { task = (Task) element.getObjectValue(); if (loadCompletely && !((Cachable) task).isCompletelyLoaded()) { task = getDataFactory().getTask(taskID, loadCompletely); } } else { task = getDataFactory().getTask(taskID, loadCompletely); } } else { task = getDataFactory().getTask(taskID, loadCompletely); } if (task != null) { cache.put(new Element(task.getID(), task)); } } else { task = getDataFactory().getTask(taskID, loadCompletely); } return task; }
public void testSimultaneousPutRemove() throws InterruptedException { cacheName = SAMPLE_CACHE2; // Synced one Ehcache cache1 = manager1.getEhcache(cacheName); Ehcache cache2 = manager2.getEhcache(cacheName); Serializable key = "1"; Serializable value = new Date(); Element element = new Element(key, value); // Put cache1.put(element); Thread.currentThread().sleep(1000); cache2.remove(element.getKey()); Thread.currentThread().sleep(1000); assertNull(cache1.get(element.getKey())); manager1.clearAll(); Thread.currentThread().sleep(1000); cache2.put(element); cache2.remove(element.getKey()); Thread.currentThread().sleep(1000); cache1.put(element); Thread.currentThread().sleep(1000); assertNotNull(cache2.get(element.getKey())); manager1.clearAll(); Thread.currentThread().sleep(1000); }
@Override public boolean contains(Object o) { if (!(o instanceof Entry)) return false; Entry<?, ?> e = (Entry<?, ?>) o; Element v = SelectableConcurrentHashMap.this.get(e.getKey()); return v != null && v.equals(e.getValue()); }
@Override @Transactional public Parameter getParameter(String key) { Element element = getParameterElement(key); if (element == null) return null; return (Parameter) element.getObjectValue(); }
/** * Gets an {@link Element} from the Disk Store. * * @return The element */ public final synchronized Element get(final Object key) { try { checkActive(); // Check in the spool. Remove if present Element element; synchronized (spoolLock) { element = (Element) spool.remove(key); } if (element != null) { element.updateAccessStatistics(); return element; } // Check if the element is on disk final DiskElement diskElement = (DiskElement) diskElements.get(key); if (diskElement == null) { // Not on disk return null; } element = loadElementFromDiskElement(diskElement); element.updateAccessStatistics(); return element; } catch (Exception exception) { LOG.error( name + "Cache: Could not read disk store element for key " + key + ". Error was " + exception.getMessage(), exception); } 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; }
/** 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); }
public V get(final K key) { Element element = this.cache.get(key); if (element != null) { return (V) element.getValue(); } return null; }
/* * Instantiate MediaFile by path name. Only to be used by file based browser. */ public MediaFile getNonIndexedMediaFile(File file) { int fileId = -Math.abs(file.getAbsolutePath().hashCode()); LOG.debug( "request for non indexed media file " + file.getAbsolutePath() + ", cache as " + fileId); Element element = mediaFileCache.get(fileId); if (element != null) { // Check if cache is up-to-date. MediaFile cachedMediaFile = (MediaFile) element.getObjectValue(); if (cachedMediaFile.lastModified() >= file.lastModified()) { return cachedMediaFile; } } if (!securityService.isReadAllowed(file)) { throw new SecurityException("Access denied to file " + file); } MediaFile mediaFile = new MediaFile(fileId, file); mediaFileCache.put(new Element(fileId, mediaFile)); return mediaFile; }
/** * Retrieve the content of a topic from the cache, or if it is not yet in the cache then add it to * the cache. * * @param context The servlet context for the topic being retrieved. May be <code>null</code> if * the <code>cook</code> parameter is set to <code>false</code>. * @param locale The locale for the topic being retrieved. May be <code>null</code> if the <code> * cook</code> parameter is set to <code>false</code>. * @param virtualWiki The virtual wiki for the topic being retrieved. * @param topicName The name of the topic being retrieved. * @param cook A parameter indicating whether or not the content should be parsed before it is * added to the cache. Stylesheet content (CSS) is not parsed, but most other content is * parsed. * @return The parsed or unparsed (depending on the <code>cook</code> parameter) topic content. */ protected static String cachedContent( String context, Locale locale, String virtualWiki, String topicName, boolean cook) { String content = null; String key = WikiCache.key(virtualWiki, topicName); Element cacheElement = WikiCache.retrieveFromCache(WikiBase.CACHE_PARSED_TOPIC_CONTENT, key); if (cacheElement != null) { content = (String) cacheElement.getObjectValue(); return (content == null) ? null : new String(content); } try { Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null); content = topic.getTopicContent(); if (cook) { ParserInput parserInput = new ParserInput(); parserInput.setContext(context); parserInput.setLocale(locale); parserInput.setVirtualWiki(virtualWiki); parserInput.setTopicName(topicName); content = Utilities.parse(parserInput, null, content); } WikiCache.addToCache(WikiBase.CACHE_PARSED_TOPIC_CONTENT, key, content); } catch (Exception e) { logger.warning("error getting cached page " + virtualWiki + " / " + topicName, e); return null; } return content; }
/** {@inheritDoc} */ @Override public boolean validateToken(TokenKey tokenKey, String token) throws TokenException { for (Object key : tokenCache.getKeys()) { logger.debug("KEY = " + key.toString()); Element element = tokenCache.get(key); if (element != null) { logger.debug("Value = " + element.getObjectValue().toString()); } else { logger.debug("No value found for key: {}", key.toString()); } } boolean foundMatch = false; Element element = tokenCache.get(tokenKey); if (element != null) { logger.debug("Cache hit for {} : {}", tokenKey); String value = (String) element.getObjectValue(); if (value != null && value.equals(token)) { logger.debug("Cached token = {}", token); foundMatch = true; } } else { logger.debug("No Cache hit for {} : {}", tokenKey); } return foundMatch; }
/** * Gets a parsed query for the passed in parameters. If the ParsedQuery requested has already been * created on this app node, it will retrieve it from a cache instead of recreating it. Use this * method instead of parseQuery if a cached copy is acceptable (almost always). * * @param db Database that the query will run against * @param toParse Query to be parsed. * @param session Database session. * @return a PreparedStatement to use. */ public static ParsedQuery getParsedQuery(String db, Query toParse, Session session) throws FieldNotIndexedException { if (db == null || db.trim().equals("")) { throw new IllegalArgumentException("Query must be populated."); } if (toParse == null) { throw new IllegalArgumentException("Query cannot be null."); } final String key = db + ":" + toParse.getTable() + ":" + toParse.getWhere(); // StopWatch pull = new StopWatch(); // pull.start(); Cache c = CacheFactory.getCache("parsedQuery"); // synchronized (CacheSynchronizer.getLockingObject(key, ParsedQuery.class)) // { Element e = c.get(key); // pull.stop(); // logger.debug("Time to pull a parsed query from cache: " + pull.getTime()); if (e == null) { logger.debug("Creating new ParsedQuery for: " + key); // StopWatch sw = new StopWatch(); // sw.start(); e = new Element(key, parseQuery(db, toParse, session)); c.put(e); // sw.stop(); // logger.debug("Time to create a new parsed query: " + sw.getTime()); } else { logger.trace("Pulling ParsedQuery from Cache: " + e.getObjectValue().toString()); } return (ParsedQuery) e.getObjectValue(); // } }
/** * Tests expiry notification is hooked up to searchInDiskStore. This test is not exact, because * the expiry thread may also expire some. * * @throws InterruptedException * @throws CacheException */ @Test public void testExpiryViaDiskStoreCheckingOnGet() throws InterruptedException, CacheException, IOException { // Overflow 10 elements to disk store for (int i = 0; i < 20; i++) { Element element = new Element("" + i, new Date()); cache.put(element); } // Wait for expiry Thread.sleep(5999); // Trigger expiry for (int i = 0; i < 20; i++) { cache.get("" + i); } CountingCacheEventListener listener = getCountingCacheEventListener(cache); List<CacheEvent> notifications = listener.getCacheElementsExpired(); for (int i = 0; i < notifications.size(); i++) { Element element = notifications.get(i).getElement(); element.getObjectKey(); } assertThat(notifications, hasSize(greaterThanOrEqualTo(10))); }
/** * 获取系统设置 * * @return 系统设置 */ public static Setting get() { Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); net.sf.ehcache.Element cacheElement = cache.get(Setting.CACHE_KEY); Setting setting; if (cacheElement != null) { setting = (Setting) cacheElement.getObjectValue(); } else { setting = new Setting(); try { File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile(); Document document = new SAXReader().read(shopxxXmlFile); List<Element> elements = document.selectNodes("/shopxx/setting"); for (Element element : elements) { String name = element.attributeValue("name"); String value = element.attributeValue("value"); try { beanUtils.setProperty(setting, name, value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } return setting; }
/** * 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; }
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); }
@Override public Ticket getTicket(final String ticketIdToGet) { final String ticketId = encodeTicketId(ticketIdToGet); if (ticketId == null) { return null; } final Element element = this.ehcacheTicketsCache.get(ticketId); if (element == null) { logger.debug("No ticket by id [{}] is found in the registry", ticketId); return null; } final Ticket ticket = decodeTicket((Ticket) element.getObjectValue()); final CacheConfiguration config = new CacheConfiguration(); config.setTimeToIdleSeconds(ticket.getExpirationPolicy().getTimeToIdle()); config.setTimeToLiveSeconds(ticket.getExpirationPolicy().getTimeToIdle()); if (element.isExpired(config) || ticket.isExpired()) { logger.debug("Ticket {} has expired", ticket.getId()); this.ehcacheTicketsCache.evictExpiredElements(); this.ehcacheTicketsCache.flush(); return null; } return ticket; }
/** * Puts an element into the disk store. * * <p>This method is not synchronized. It is however threadsafe. It uses fine-grained * synchronization on the spool. */ public final void put(final Element element) { try { checkActive(); // Spool the element if (spoolAndExpiryThread.isAlive()) { synchronized (spoolLock) { spool.put(element.getObjectKey(), element); } } else { LOG.error( name + "Cache: Elements cannot be written to disk store because the" + " spool thread has died."); synchronized (spoolLock) { spool.clear(); } } } catch (Exception e) { LOG.error( name + "Cache: Could not write disk store element for " + element.getObjectKey() + ". Initial cause was " + e.getMessage(), e); } }
/** * Refresh a single element. * * @param element the Element to refresh * @param backingCache the underlying {@link Ehcache}. * @param quiet whether to use putQuiet or not, if true replication will not occur * @return the refreshed Element * @throws Exception * @since 1.6.1 */ protected Element refreshElement(final Element element, Ehcache backingCache, boolean quiet) throws Exception { Object key = element.getObjectKey(); if (LOG.isLoggable(Level.FINE)) { LOG.fine(getName() + ": refreshing element with key " + key); } final Element replacementElement; if (factory instanceof UpdatingCacheEntryFactory) { // update the value of the cloned Element in place replacementElement = element; ((UpdatingCacheEntryFactory) factory) .updateEntryValue(key, replacementElement.getObjectValue()); // put the updated element back into the backingCache, without updating stats // It is not usually necessary to do this. We do this in case the element expired // or idles out of the backingCache. In that case we hold a reference to it but the // backingCache no longer does. } else { final Object value = factory.createEntry(key); replacementElement = makeAndCheckElement(key, value); } if (quiet) { backingCache.putQuiet(replacementElement); } else { backingCache.put(replacementElement); } return replacementElement; }
protected Image getImage(Object element) { if (!(element instanceof Attachment)) { return null; } Attachment attachment = (Attachment) element; Image thumb = null; if (Arrays.asList(Attachment.getImageMimeTypes()).contains(attachment.getMimeType())) { Element cacheElement = getCache().get(attachment.getDbId()); if (cacheElement != null) { // != is correct here if (cacheElement.getObjectValue() != EMPTY_CACHE_ELEMENT) { ImageData imageData = (ImageData) cacheElement.getObjectValue(); thumb = new Image(FileView.getDisplay(), imageData); } } else { byte[] fileData = loadFileData(attachment); thumb = createImage(fileData); if (thumb != null) { getCache().put(new Element(attachment.getDbId(), thumb.getImageData())); } else { getCache().put(new Element(attachment.getDbId(), EMPTY_CACHE_ELEMENT)); } } } return thumb; }
/** * Both CacheEntryFactory can return an Element rather than just a regular value this method test * this, making a fresh Element otherwise. It also enforces the rule that the CacheEntryFactory * must provide the same key (via equals() not necessarily same object) if it is returning an * Element. * * @param key * @param value * @return the Element to be put back in the cache * @throws CacheException for various illegal states which could be harmful */ protected static Element makeAndCheckElement(Object key, Object value) throws CacheException { // check if null if (value == null) { return new Element(key, value); } // simply build a new element using the supplied key if (!(value instanceof Element)) { return new Element(key, value); } // It is already an element - perform sanity checks Element element = (Element) value; if ((element.getObjectKey() == null) && (key == null)) { return element; } else if (element.getObjectKey() == null) { throw new CacheException("CacheEntryFactory returned an Element with a null key"); } else if (!element.getObjectKey().equals(key)) { throw new CacheException( "CacheEntryFactory returned an Element with a different key: " + element.getObjectKey() + " compared to the key that was requested: " + key); } else { return element; } }
@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(); } }
/** 拦截 Service/DAO 的方法,并查找该结果是否存在,如果存在就返回 cache 中的值, 否则,返回数据库查询结果,并将查询结果放入 cache */ @Override public Object invoke(MethodInvocation invocation) throws Throwable { String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); Object result; String cacheKey = getCacheKey(targetName, methodName, arguments); logger.info("从[" + cache.getName() + "]查询key:[" + cacheKey + "]的缓存]"); // System.out.println("从["+cache.getName()+"]查询key:["+cacheKey+"]的缓存]"); Element element = cache.get(cacheKey); if (element == null) { result = invocation.proceed(); logger.info("key:[" + cacheKey + "]无缓存,创建缓存为[" + result + "]"); // System.out.println("key:["+cacheKey+"]无缓存,创建缓存为["+result+"]"); element = new Element(cacheKey, (Serializable) result); cache.put(element); } return element.getObjectValue(); }
/** 主方法 如果某方法可被缓存就缓存其结果 方法结果必须是可序列化的(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(); }
/** {@inheritDoc} */ public Set<Object> getKeysInvisibleInContext( LocalTransactionContext currentTransactionContext, Store underlyingStore) { Set<Object> invisibleKeys = new HashSet<Object>(); // all new keys added into the store are invisible invisibleKeys.addAll(getNewKeys()); List<SoftLock> currentTransactionContextSoftLocks = currentTransactionContext.getSoftLocksForCache(cacheName); for (SoftLock softLock : currentTransactionContextSoftLocks) { Element e = underlyingStore.getQuiet(softLock.getKey()); if (e.getObjectValue() instanceof SoftLockID) { SoftLockID softLockId = (SoftLockID) e.getObjectValue(); if (softLock.getElement(currentTransactionContext.getTransactionId(), softLockId) == null) { // if the soft lock's element is null in the current transaction then the key is invisible invisibleKeys.add(softLock.getKey()); } else { // if the soft lock's element is not null in the current transaction then the key is // visible invisibleKeys.remove(softLock.getKey()); } } } return invisibleKeys; }
@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; }
/** * Performance and capacity tests. * * <p> */ @Test public void testBootstrap() throws CacheException, InterruptedException, RemoteException { // load up some data StopWatch stopWatch = new StopWatch(); Integer index = null; for (int i = 0; i < 2; i++) { for (int j = 0; j < 1000; j++) { index = Integer.valueOf(((1000 * i) + j)); cache1.put( new Element( index, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); } } long elapsed = stopWatch.getElapsedTime(); long putTime = ((elapsed / 1000)); LOG.info("Put Elapsed time: " + putTime); assertEquals(2000, cache1.getSize()); Thread.sleep(7000); assertEquals(2000, manager2.getCache("sampleCache1").getSize()); assertEquals(2000, manager3.getCache("sampleCache1").getSize()); assertEquals(2000, manager4.getCache("sampleCache1").getSize()); assertEquals(2000, manager5.getCache("sampleCache1").getSize()); // now test bootstrap manager1.addCache("bootStrapResults"); Cache cache = manager1.getCache("bootStrapResults"); List cachePeers = manager1.getCacheManagerPeerProvider("RMI").listRemoteCachePeers(cache1); CachePeer cachePeer = (CachePeer) cachePeers.get(0); List keys = cachePeer.getKeys(); assertEquals(2000, keys.size()); Element firstElement = cachePeer.getQuiet((Serializable) keys.get(0)); long size = firstElement.getSerializedSize(); assertEquals(504, size); int chunkSize = (int) (5000000 / size); List requestChunk = new ArrayList(); for (int i = 0; i < keys.size(); i++) { Serializable serializable = (Serializable) keys.get(i); requestChunk.add(serializable); if (requestChunk.size() == chunkSize) { fetchAndPutElements(cache, requestChunk, cachePeer); requestChunk.clear(); } } // get leftovers fetchAndPutElements(cache, requestChunk, cachePeer); assertEquals(keys.size(), cache.getSize()); }