public synchronized PolicyCollection getDocument(final File file) throws PoliciesParseException { // cacheTotal++; CacheItem entry = cache.get(file); long checkTime = System.currentTimeMillis(); if (null == entry || ((checkTime - entry.cacheTime) > FILE_CHECK_DELAY)) { final long lastmod = file.lastModified(); if (null == entry || lastmod > entry.modTime) { if (!file.exists()) { CacheItem remove = cache.remove(file); entry = null; // cacheRemove++; } else { // cacheMiss++; PolicyCollection entry1 = createEntry(file); if (null != entry1) { entry = new CacheItem(entry1, lastmod); cache.put(file, entry); } else { cache.remove(file); entry = null; } } } else { // cacheUnmodifiedHit++; entry.touch(checkTime); } } else { // cacheHit++; } return null != entry ? entry.policyCollection : null; }
@Test public void testPutAndGetCacheItem() { CacheItem outItem = putAndGet(REQUEST); assertNotNull("OutItem was null", outItem); assertNotNull("OutItem response was null", outItem.getResponse()); outItem.getResponse().consume(); }
/** * get information for process * * @return true == success, false == failed */ public boolean getCacheInfo() { if (queryQueue.isEmpty()) return false; try { queryQueueLock.acquire(); } catch (InterruptedException e) { return false; } QueueJob processJob = queryQueue.remove(); queryQueueLock.release(); PackageInfo curPackageInfo = null; String curPackageName = null; if (processJob.process.contains(":")) curPackageName = processJob.process.substring(0, processJob.process.indexOf(":")); else curPackageName = processJob.process; // for system user if (processJob.owner.contains("system") && processJob.process.contains("system") && !processJob.process.contains(".")) curPackageName = "android"; try { curPackageInfo = packageMgr.getPackageInfo(curPackageName, 0); } catch (NameNotFoundException e) { } if (curPackageInfo == null && processJob.uid > 0) { String[] subPackageName = packageMgr.getPackagesForUid(processJob.uid); if (subPackageName != null) { for (int PackagePtr = 0; PackagePtr < subPackageName.length; PackagePtr++) { if (subPackageName[PackagePtr] == null) continue; try { curPackageInfo = packageMgr.getPackageInfo(subPackageName[PackagePtr], 0); PackagePtr = subPackageName.length; } catch (NameNotFoundException e) { } } } } CacheItem processItem = new CacheItem(); if (curPackageInfo != null) { processItem.name = curPackageInfo.applicationInfo.loadLabel(packageMgr).toString(); if (useDetail == true) processItem.icon = resizeImage(curPackageInfo.applicationInfo.loadIcon(packageMgr), iconSize); } else { processItem.name = curPackageName; processItem.icon = commonIcon; } cacheStorage.put(processJob.process, processItem); return true; }
@Test public void isTargetClassAndCurrentJvmTargetClassMatch_class_exist_but_Not_Serializable() throws Exception { CacheItem cacheItem = createCacheItem(NotSerializableFakeEntity.class.getName(), 1L); assertThat(cacheItem.isTargetClassAndCurrentJvmTargetClassMatch()).isFalse(); }
private CacheItem createCacheItem(String targetClassName, long targetClassSerialVersionUID) { CacheItem cacheItem = new CacheItem(); cacheItem.setTargetClassName(targetClassName); cacheItem.setTargetClassSerialVersionUID(targetClassSerialVersionUID); return cacheItem; }
@Test public void parseTargetClass_parse_serialVersionUID() throws Exception { givenCacheEntrySubclass(FakeEntity.class); CacheItem cacheItem = new CacheItem(cacheEntry, false); assertThat(cacheItem.getTargetClassSerialVersionUID()).isEqualTo(12345L); assertThat(cacheItem.getTargetClassName()).isEqualTo(FakeEntity.class.getName()); }
public CacheItem<K, V> deleteTail() { if (head.next == null) return null; CacheItem<K, V> ret = tail; tail = tail.prev; tail.next = null; ret.prev = null; ret.next = null; return ret; }
@Test public void isTargetClassAndCurrentJvmTargetClassMatch_class_exist_but_different_serialversionUID() throws Exception { CacheItem cacheItem = createCacheItem(FakeEntity.class.getName(), FakeEntity.serialVersionUID + 1L); assertThat(cacheItem.isTargetClassAndCurrentJvmTargetClassMatch()).isFalse(); }
@Test public void parseTargetClass_parse_serialVersionUid_of_FakeEntityWithoutSerialVersionUID() throws Exception { givenCacheEntrySubclass(FakeEntityWithoutSerialVersionUID.class); CacheItem cacheItem = new CacheItem(cacheEntry, false); assertThat(cacheItem.getTargetClassName()) .isEqualTo(FakeEntityWithoutSerialVersionUID.class.getName()); log.debug("targetClassSerialVersionUID : {}", cacheItem.getTargetClassSerialVersionUID()); }
@Override public Set<Reservation> getAll() { log.trace("ReservationCacheImpl.getAll()"); checkRunning(); Set<Reservation> reservations = newHashSet(); for (CacheItem<Reservation> item : reservationsBySrk.values()) { if (!item.isOutdated()) { reservations.add(item.get()); item.touch(); } } return reservations; }
public void delete(CacheItem<K, V> node) { if (head.next == null) return; if (node == head.next) { deleteHead(); } else if (node == tail) { deleteTail(); } else { node.prev.next = node.next; node.next.prev = node.prev; node.next = null; node.prev = null; } }
public V value(K key) { CacheItem<K, V> item = item(key); if (item != null) { if (item.isValid()) { return item.getValue(); } else { invalidate(key); return null; } } else { return null; } }
public CacheItem<K, V> deleteHead() { if (head.next == null) return null; if (head.next == tail) { tail = tail.prev; } CacheItem<K, V> ret = head.next; head.next = ret.next; if (ret.next != null) { ret.next.prev = head; } ret.next = null; ret.prev = null; return ret; }
@Override public Optional<Reservation> lookup(final Set<SecretReservationKey> srks) { log.trace("ReservationCacheImpl.lookup({})", srks); checkRunning(); CacheItem<Reservation> item = reservationsBySrk.get(srks); if (item != null) { if (item.isOutdated()) { return Optional.absent(); } Reservation reservation = item.get(); reservation.touch(); return Optional.of(reservation); } return Optional.absent(); }
/** * this item is accessed * * @param item <code>CacheItem</code> accessed * <p>Cache bucket is already synchronized by the caller */ protected void itemAccessed(CacheItem item) { int index = getIndex(item.hashCode()); int segment = (index / segmentSize); LruCacheItem[] list = lists[segment]; if (!(item instanceof LruCacheItem)) return; LruCacheItem lc = (LruCacheItem) item; // update the LRU list synchronized (list) { LruCacheItem prev = lc.lPrev; LruCacheItem next = lc.lNext; if (prev != null) { // put the item at the head of LRU list lc.lPrev = null; lc.lNext = list[LRU_HEAD]; list[LRU_HEAD].lPrev = lc; list[LRU_HEAD] = lc; // patch up the previous neighbors prev.lNext = next; if (next != null) next.lPrev = prev; else list[LRU_TAIL] = prev; } } }
/** * this item is just added to the cache * * @param item <code>CacheItem</code> that was created * @return a overflow item; may be null * <p>Cache bucket is already synchronized by the caller */ protected CacheItem itemAdded(CacheItem item) { CacheItem overflow = null; if (!(item instanceof LruCacheItem)) return null; LruCacheItem lc = (LruCacheItem) item; int index = getIndex(item.hashCode()); int segment = (index / segmentSize); LruCacheItem[] list = lists[segment]; // update the LRU synchronized (list) { if (list[LRU_HEAD] != null) { list[LRU_HEAD].lPrev = lc; lc.lNext = list[LRU_HEAD]; } else list[LRU_TAIL] = lc; list[LRU_HEAD] = lc; listsLength[segment]++; if (isThresholdReached()) { overflow = trimLru(trimIndex); // go round robin for the next trim incrementTrimIndex(); } } return overflow; }
/** * item value has been removed from the cache * * @param item <code>CacheItem</code> that was just removed * <p>Cache bucket is already synchronized by the caller */ protected void itemRemoved(CacheItem item) { if (!(item instanceof LruCacheItem)) return; LruCacheItem l = (LruCacheItem) item; int index = getIndex(item.hashCode()); int segment = (index / segmentSize); LruCacheItem[] list = lists[segment]; // remove the item from the LRU list synchronized (list) { // if the item is already trimmed from the LRU list, nothing to do. if (l.isTrimmed) return; LruCacheItem prev = l.lPrev; LruCacheItem next = l.lNext; // patch up the neighbors and make sure head/tail are correct if (prev != null) prev.lNext = next; else list[LRU_HEAD] = next; if (next != null) next.lPrev = prev; else list[LRU_TAIL] = prev; listsLength[segment]--; } }
public CacheItem getFromMemoryCache(final String url, boolean checkExpiration) { CacheItem result = null; if (null != mMemoryCache) { synchronized (mMemoryCache) { result = mMemoryCache.get(url); // If we get a value, that has expired if (null != result && result.getExpiresAt().isBeforeNow() && checkExpiration) { mMemoryCache.remove(url); result = null; } } } return result; }
public Object get(String url, boolean checkExpiration) { Timber.d(String.format("get(%s)", url)); CacheItem result; // First try Memory Cache result = getFromMemoryCache(url, checkExpiration); if (null == result) { // Memory Cache failed, so try Disk Cache result = getFromDiskCache(url, checkExpiration); } if (result != null) { return result.getValue(); } else { return null; } }
public void doCacheInfo(int uid, String owner, String process) { // add a job into work queue try { queryQueueLock.acquire(); } catch (InterruptedException e) { return; } queryQueue.add(new QueueJob(uid, owner, process)); queryQueueLock.release(); // create a skeleton object CacheItem skeletonItem = new CacheItem(); skeletonItem.name = process; skeletonItem.icon = commonIcon; cacheStorage.put(process, skeletonItem); return; }
@Override public Optional<Reservation> lookup(final NodeUrn nodeUrn, final DateTime timestamp) { log.trace("ReservationCacheImpl.lookup({}, {})", nodeUrn, timestamp); checkRunning(); synchronized (reservationsByNodeUrn) { final List<CacheItem<Reservation>> entry = reservationsByNodeUrn.get(nodeUrn); if (entry == null) { log.trace("ReservationManagerImpl.lookup() CACHE MISS"); return Optional.absent(); } for (CacheItem<Reservation> item : entry) { final Interval effectiveInterval; final Reservation reservation = item.get(); final DateTime reservationStart = reservation.getInterval().getStart(); final DateTime reservationCancellation = reservation.getCancelled(); if (reservationCancellation != null) { if (reservationCancellation.isBefore(reservationStart)) { continue; } else { effectiveInterval = new Interval(reservationStart, reservationCancellation); } } else { effectiveInterval = reservation.getInterval(); } if (effectiveInterval.contains(timestamp)) { if (!item.isOutdated()) { item.touch(); log.trace("ReservationManagerImpl.lookup() CACHE HIT"); return Optional.of(reservation); } } } } return Optional.absent(); }
@Override public void open() { ClasspathInfo ci = ClasspathInfo.create(cacheItem.getRoot()); FileObject file = VisageSourceUtils.getFile(handle, ci); try { ElementOpen.open(file, handle); } catch (Exception exception) { LOGGER.fine(exception.getMessage()); System.err.println("Exc: " + exception); } }
@Override public void remove(Reservation reservation) { log.trace("ReservationCacheImpl.remove({})", reservation); checkRunning(); reservationsCacheLock.lock(); try { int removedNodeCacheEntries = 0; for (Iterator<Map.Entry<NodeUrn, List<CacheItem<Reservation>>>> cacheIterator = reservationsByNodeUrn.entrySet().iterator(); cacheIterator.hasNext(); ) { final Map.Entry<NodeUrn, List<CacheItem<Reservation>>> entry = cacheIterator.next(); for (Iterator<CacheItem<Reservation>> itemIt = entry.getValue().iterator(); itemIt.hasNext(); ) { final CacheItem<Reservation> item = itemIt.next(); final Reservation res = item.get(); if (res == reservation) { itemIt.remove(); removedNodeCacheEntries++; } } if (entry.getValue().isEmpty()) { cacheIterator.remove(); } } log.trace("ReservationCacheImpl removed {} node cache entries", removedNodeCacheEntries); reservationsBySrk.remove(reservation.getSecretReservationKeys()); } finally { reservationsCacheLock.unlock(); } }
@Test public void testPutUpdatedCacheItem() { CacheItem item = putAndGet(REQUEST); item.getResponse().consume(); HTTPResponse response = new HTTPResponse(null, Status.OK, new Headers()); HTTPResponse res = storage.update(REQUEST, response); res.consume(); final CacheItem cacheItem = storage.get(REQUEST); assertNotSame("Items were the same", cacheItem.getCachedTime(), item.getCachedTime()); cacheItem.getResponse().consume(); }
/** * Cleans up the cache. All outdated items will be removed from both maps. * * @return the set of reservations that was removed from the two caches */ @VisibleForTesting protected Set<Reservation> cleanUpCache() { log.trace("ReservationManagerImpl.cleanUpCache()"); final Set<Reservation> removed = newHashSet(); reservationsCacheLock.lock(); try { for (Iterator<Map.Entry<NodeUrn, List<CacheItem<Reservation>>>> cacheIterator = reservationsByNodeUrn.entrySet().iterator(); cacheIterator.hasNext(); ) { final Map.Entry<NodeUrn, List<CacheItem<Reservation>>> entry = cacheIterator.next(); for (Iterator<CacheItem<Reservation>> itemIterator = entry.getValue().iterator(); itemIterator.hasNext(); ) { final CacheItem<Reservation> item = itemIterator.next(); if (item.isOutdated()) { removed.add(item.get()); itemIterator.remove(); } } if (entry.getValue().isEmpty()) { cacheIterator.remove(); } } for (Iterator<Map.Entry<Set<SecretReservationKey>, CacheItem<Reservation>>> iterator = reservationsBySrk.entrySet().iterator(); iterator.hasNext(); ) { final Map.Entry<Set<SecretReservationKey>, CacheItem<Reservation>> entry = iterator.next(); final CacheItem<Reservation> item = entry.getValue(); if (item.isOutdated()) { iterator.remove(); removed.add(item.get()); } } log.trace( "ReservationManagerImpl.cleanUpCache() removed {} entries: {}", removed.size(), removed); return removed; } finally { reservationsCacheLock.unlock(); } }
@Test public void checkIfClassVersionApplicable_useStructuredCache_true_no_Map() throws Exception { assertThat(CacheItem.checkIfClassVersionApplicable(cacheEntry, true)).isFalse(); }
@Override public FileObject getFileObject() { return cacheItem.getRoot(); }
@Override public Icon getProjectIcon() { return cacheItem.getProjectIcon(); }
@Override public String getProjectName() { String projectName = cacheItem.getProjectName(); return projectName == null ? "" : projectName; // NOI18N }
@Test public void isTargetClassAndCurrentJvmTargetClassMatch_match_true() throws Exception { CacheItem cacheItem = createCacheItem(FakeEntity.class.getName(), FakeEntity.serialVersionUID); assertThat(cacheItem.isTargetClassAndCurrentJvmTargetClassMatch()).isTrue(); }