/** Tests the loading of classes */ @Test public void testClassloading() throws Exception { final Store diskStore = createDiskStore(); Long value = Long.valueOf(123L); diskStore.put(new Element("key1", value)); diskStore.put(new Element("key2", value)); Thread.sleep(1000); Element element1 = diskStore.get("key1"); Element element2 = diskStore.get("key2"); assertEquals(value, element1.getObjectValue()); assertEquals(value, element2.getObjectValue()); Primitive primitive = new Primitive(); primitive.integerPrimitive = 123; primitive.longPrimitive = 456L; primitive.bytePrimitive = "a".getBytes()[0]; primitive.charPrimitive = 'B'; primitive.booleanPrimitive = false; // test Serializability ByteArrayOutputStream outstr = new ByteArrayOutputStream(); ObjectOutputStream objstr = new ObjectOutputStream(outstr); objstr.writeObject(new Element("key", value)); objstr.close(); diskStore.put(new Element("primitive1", primitive)); diskStore.put(new Element("primitive2", primitive)); Thread.sleep(1000); Element primitive1 = diskStore.get("primitive1"); Element primitive2 = diskStore.get("primitive2"); assertEquals(primitive, primitive1.getObjectValue()); assertEquals(primitive, primitive2.getObjectValue()); }
/** {@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; }
/** {@inheritDoc} */ public SoftLockID createSoftLockID( TransactionID transactionID, Object key, Element newElement, Element oldElement) { if (newElement != null && newElement.getObjectValue() instanceof SoftLockID) { throw new AssertionError("newElement must not contain a soft lock ID"); } if (oldElement != null && oldElement.getObjectValue() instanceof SoftLockID) { throw new AssertionError("oldElement must not contain a soft lock ID"); } SoftLockID lockId = new SoftLockID(transactionID, key, newElement, oldElement); if (getAllLocks().containsKey(lockId)) { return lockId; } else { SoftLock lock = lockFactory.newSoftLock(this, key); if (getAllLocks().putIfAbsent(lockId, lock) != null) { throw new AssertionError(); } else { if (oldElement == null) { getNewKeyLocks().put(lockId, Boolean.TRUE); } return lockId; } } }
/** * 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(); // } }
/** {@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; }
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; }
@RequestMapping("{cacheName}/{key}/details") @ResponseBody public Object keyDetail( @PathVariable("cacheName") String cacheName, @PathVariable("key") String key, Model model) { Element element = cacheManager.getCache(cacheName).get(key); String dataPattern = "yyyy-MM-dd hh:mm:ss"; Map<String, Object> data = Maps.newHashMap(); data.put("objectValue", element.getObjectValue().toString()); data.put("size", PrettyMemoryUtils.prettyByteSize(element.getSerializedSize())); data.put("hitCount", element.getHitCount()); Date latestOfCreationAndUpdateTime = new Date(element.getLatestOfCreationAndUpdateTime()); data.put( "latestOfCreationAndUpdateTime", DateFormatUtils.format(latestOfCreationAndUpdateTime, dataPattern)); Date lastAccessTime = new Date(element.getLastAccessTime()); data.put("lastAccessTime", DateFormatUtils.format(lastAccessTime, dataPattern)); if (element.getExpirationTime() == Long.MAX_VALUE) { data.put("expirationTime", "不过期"); } else { Date expirationTime = new Date(element.getExpirationTime()); data.put("expirationTime", DateFormatUtils.format(expirationTime, dataPattern)); } data.put("timeToIdle", element.getTimeToIdle()); data.put("timeToLive", element.getTimeToLive()); data.put("version", element.getVersion()); return data; }
/** * 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; }
/* * 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; }
@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; }
/** * 获取系统设置 * * @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; }
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; }
/** 拦截 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(); }
@Override @Transactional public Parameter getParameter(String key) { Element element = getParameterElement(key); if (element == null) return null; return (Parameter) element.getObjectValue(); }
private Element getFromUnderlyingStore(final Object key) { while (true) { long timeLeft = assertNotTimedOut(); LOG.debug( "cache {} underlying.get key {} not timed out, time left: " + timeLeft, cache.getName(), key); Element element = underlyingStore.get(key); if (element == null) { return null; } Object value = element.getObjectValue(); if (value instanceof SoftLockID) { SoftLockID softLockId = (SoftLockID) value; SoftLock softLock = softLockManager.findSoftLockById(softLockId); if (softLock == null) { LOG.debug( "cache {} underlying.get key {} soft lock died, retrying...", cache.getName(), key); continue; } else { try { LOG.debug("cache {} key {} soft locked, awaiting unlock...", cache.getName(), key); if (softLock.tryLock(timeLeft)) { softLock.clearTryLock(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } else { return element; } } }
@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; }
/** * 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; }
public static void main(String args[]) { Map<Object, Element> map = new HashMap<Object, Element>(); List<String> list = new ArrayList<String>(); // Create a cache manager CacheManager cacheManager = CacheManager.getInstance(); // Creates a cache called newCache cacheManager.addCache("newCache"); // Get cache called newCache Cache cache = cacheManager.getCache("newCache"); StatisticsGateway stats = cache.getStatistics(); // put into cache cache.put(new Element("1", "Monday")); list.add("1"); cache.put(new Element("2", "Tuesday")); list.add("2"); cache.put(new Element("3", "Wednesday")); list.add("3"); cache.put(new Element("4", "Thursday")); list.add("4"); // Displaying all elements System.out.println("All elements"); map = cache.getAll(list); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); } // Displaying elements and size of cache Element element = cache.get("1"); System.out.println("Value of key 1 :" + element.getObjectValue().toString()); System.out.println("Cache Size " + cache.getSize()); element = cache.get("2"); System.out.println("Value of key 2 :" + element.getObjectValue().toString()); System.out.println("Cache Size " + cache.getSize()); cache.removeElement(element); System.out.println("Cache Size after removing an element : " + cache.getSize()); cache.flush(); System.out.println("Removed Cache with key 3 :" + cache.remove("3")); System.out.println("Size after remove : " + cache.getSize()); }
public Object attributeFor(Element element, String attributeName) { if (!attributeName.equals("age")) { throw new AssertionError(attributeName); } Person person = (Person) element.getObjectValue(); return person.getAge(); }
/** * Determine if diff information is available in the cache. If so return it, otherwise return * <code>null</code>. */ private static List<WikiDiff> retrieveFromCache(String newVersion, String oldVersion) throws DataAccessException { String key = generateCacheKey(newVersion, oldVersion); Element cachedDiffInformation = WikiCache.retrieveFromCache(CACHE_DIFF_INFORMATION, key); return (cachedDiffInformation != null) ? (List<WikiDiff>) cachedDiffInformation.getObjectValue() : null; }
/* * (non-Javadoc) * * @see net.jawr.web.cache.AbstractCacheManager#get(java.lang.String) */ public Object get(String key) { Element element = cache.get(key); if (element != null) { return element.getObjectValue(); } return null; }
@Override public Object get(final Object key) { final Element value = impl.get(key); if (null == value) return null; return value.getObjectValue(); }
/* * (non-Javadoc) * * @see * net.sf.ehcache.constructs.web.filter.CachingFilter#buildPageInfo(javax * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, * javax.servlet.FilterChain) */ @Override protected PageInfo buildPageInfo( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws Exception { String key = calculateKey(request); PageInfo pageInfo = null; String originalThreadName = Thread.currentThread().getName(); try { // checkNoReentry(request); Element element = null; if (!StringUtils.isBlank(key)) { element = this.blockingCache.get(key); } if ((element == null) || (element.getObjectValue() == null)) try { pageInfo = buildPage(request, response, chain); if (pageInfo.isOk()) { log.debug( "PageInfo ok. Adding to cache " + this.blockingCache.getName() + " with key " + key); this.blockingCache.put(new Element(key, pageInfo)); } else { log.warn( "PageInfo was not ok(200). Putting null into cache " + this.blockingCache.getName() + " with key " + key); this.blockingCache.put(new Element(key, null)); } } catch (Throwable throwable) { this.blockingCache.put(new Element(key, null)); throw new Exception(throwable); } else { pageInfo = (PageInfo) element.getObjectValue(); } } catch (LockTimeoutException e) { throw e; } finally { Thread.currentThread().setName(originalThreadName); } return pageInfo; }
@Override public int getLBServerOffset(PageLetConfig pageLetConfig) { int offset = -1; Element element = this.cchm.getCache("lb").get(pageLetConfig.getURI()); if (null != element) { offset = (int) element.getObjectValue(); } return offset; }
@Override public List<Cache> getAllCache() { List<Cache> list = new ArrayList<>(); Map<Object, Element> map = userCache.getAll(userCache.getKeys()); for (Element e : map.values()) { list.add((Cache) e.getObjectValue()); } return list; }
@SuppressWarnings("unchecked") @Override public V getValue(K key) { Element element = cache.get(key); if (element != null) { return (V) element.getObjectValue(); } return null; }
@Override public CachedPageLet get(PageLetConfig pageLetConfig) { Element element = this.cchm.getCache("esi").get(pageLetConfig.getURI()); CachedPageLet cachedPageLet = null; if (null != element) { cachedPageLet = new CachedPageLet(pageLetConfig, (String) element.getObjectValue()); } return cachedPageLet; }
@Override public Client get(String ref) { // TODO Auto-generated method stub Client client = null; if (cache.isKeyInCache(ref)) { Element elem = cache.get(ref); client = (Client) elem.getObjectValue(); } return client; }
private Entity getFromCache(Integer id) { if (id == null) { return null; } Element element = entityDefinitionCache.get(id); if (element == null) { return null; } return (Entity) element.getObjectValue(); }
public Object get(Object key) { if (key == null) { return null; } Element elem = ehcache.get(key); if (elem == null) { return null; } return elem.getObjectValue(); }