Java Code Examples for org.ehcache.Cache#Entry

The following examples show how to use org.ehcache.Cache#Entry . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClusteredIterationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testIterationTerminatedWithException() {
  try (CacheManager cacheManager = createTestCacheManager()) {
    Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class);

    byte[] data = new byte[101 * 1024];
    cache.put(1L, data);
    cache.put(2L, data);

    Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator();

    assertThat(iterator.next(), notNullValue());
    assertThat(iterator.next(), notNullValue());

    try {
      iterator.next();
      fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
      //expected
    }
  }
}
 
Example 2
Source File: EvictionEhcacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimplePutIfAbsentWithEviction() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(2))
          .build());

  testCache.putIfAbsent(1, "one");
  testCache.putIfAbsent(2, "two");
  assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
  assertThat(testCache.get(2), Matchers.<CharSequence>equalTo("two"));

  testCache.putIfAbsent(3, "three");
  testCache.putIfAbsent(4, "four");

  int count = 0;
  for (@SuppressWarnings("unused") Cache.Entry<Number, CharSequence> entry : testCache) {
    count++;
  }
  assertThat(count, is(2));
}
 
Example 3
Source File: EvictionEhcacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimplePutAllWithEviction() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(2))
          .build());

  Map<Integer, String> values = new HashMap<>();
  values.put(1, "one");
  values.put(2, "two");
  values.put(3, "three");
  values.put(4, "four");

  testCache.putAll(values);

  int count = 0;
  for (@SuppressWarnings("unused") Cache.Entry<Number, CharSequence> entry : testCache) {
    count++;
  }
  assertThat(count, is(2));
}
 
Example 4
Source File: EventNotificationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiThreadedSyncNotifications() throws InterruptedException {
  CacheConfiguration<Number, Number> cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class,
      newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES))
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  Cache<Number, Number> cache = cacheManager.getCache("cache", Number.class, Number.class);
  cache.getRuntimeConfiguration()
      .registerCacheEventListener(listener1, EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet
          .of(EventType.CREATED, EventType.EVICTED));

  Thread[] operators = new Thread[10];
  for (int i = 0; i < 10; i++) {
    operators[i] = new Thread(new CachePutOperator(cache, i), "CACHE-PUT-OPERATOR_" + i);
    operators[i].start();
  }
  for (int i = 0; i < 10; i++) {
    operators[i].join();
  }

  int entryCount = 0;
  for (Cache.Entry<Number, Number> entry : cache) {
    entryCount++;
  }

  cacheManager.close();

  assertEquals(100, listener1.created.get());
  assertEquals(100 - entryCount, listener1.evicted.get());
}
 
Example 5
Source File: ClusteredIterationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private static <K, V> Matcher<Cache.Entry<K, V>> isEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher) {
  return new TypeSafeMatcher<Cache.Entry<K, V>>() {
    @Override
    public void describeTo(Description description) {
      description.appendText(" a cache entry { key ").appendDescriptionOf(keyMatcher).appendText(": value ").appendDescriptionOf(valueMatcher).appendText(" }");
    }

    @Override
    protected boolean matchesSafely(Cache.Entry<K, V> item) {
      return keyMatcher.matches(item.getKey()) && valueMatcher.matches(item.getValue());
    }
  };
}
 
Example 6
Source File: ClusteredStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleChains() throws StoreAccessException {

  store.put(1L, "foo");
  store.put(2L, "bar");

  Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();

  Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryOne = isEntry(1L, "foo");
  Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryTwo = isEntry(2L, "bar");

  assertThat(iterator.hasNext(), is(true));

  Cache.Entry<Long, Store.ValueHolder<String>> next = iterator.next();
  assertThat(next, either(entryOne).or(entryTwo));

  if (entryOne.matches(next)) {
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.next(), is(entryTwo));
    assertThat(iterator.hasNext(), is(false));
  } else {
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.next(), is(entryOne));
    assertThat(iterator.hasNext(), is(false));
  }

  try {
    iterator.next();
    fail("Expected NoSuchElementException");
  } catch (NoSuchElementException e) {
    //expected
  }
}
 
Example 7
Source File: EhcacheBasicIteratorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link java.util.Iterator#hasNext()} <b>after</b> exhausting the {@code Iterator} returned
 * from {@link Ehcache#iterator()} on a non-empty cache.
 */
@Test
public void testIteratorNonEmptyHasNextAfterLast() throws Exception {
  this.store = new FakeStore(this.getTestStoreEntries());
  final InternalCache<String, String> ehcache = this.getEhcache();

  final Iterator<Cache.Entry<String, String>> iterator = ehcache.iterator();
  while (iterator.hasNext()) {
    iterator.next();
  }

  assertThat(iterator.hasNext(), is(false));
}
 
Example 8
Source File: EhcacheBasicIteratorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link java.util.Iterator#remove()} from {@link Ehcache#iterator()} on an empty cache.
 */
@Test
public void testIteratorEmptyStoreRemoveBeforeNext() throws Exception {
  this.store = new FakeStore(Collections.emptyMap());
  final InternalCache<String, String> ehcache = this.getEhcache();
  final Iterator<Cache.Entry<String, String>> iterator = ehcache.iterator();
  try {
    iterator.remove();
    fail();
  } catch (IllegalStateException e) {
    // expected
  }
}
 
Example 9
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIteratorWithSingleExpiredEntry() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L)));

  offHeapStore.put("key1", "value1");

  timeSource.advanceTime(11L);

  Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator();
  assertTrue(iterator.hasNext());
  assertThat(iterator.next().getKey(), equalTo("key1"));
  assertFalse(iterator.hasNext());
}
 
Example 10
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L)));

  offHeapStore.put("key1", "value1");
  offHeapStore.put("key2", "value2");

  timeSource.advanceTime(11L);

  offHeapStore.put("key3", "value3");
  offHeapStore.put("key4", "value4");

  final List<String> expiredKeys = new ArrayList<>();
  offHeapStore.getStoreEventSource().addEventListener(event -> {
    if (event.getType() == EventType.EXPIRED) {
      expiredKeys.add(event.getKey());
    }
  });

  List<String> iteratedKeys = new ArrayList<>();
  Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator();
  while(iterator.hasNext()) {
    iteratedKeys.add(iterator.next().getKey());
  }

  assertThat(iteratedKeys, containsInAnyOrder("key1", "key2", "key3", "key4"));
  assertThat(expiredKeys.isEmpty(), is(true));
}
 
Example 11
Source File: ExpiryEhcacheTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private static int cacheSize(Cache<?, ?> cache) {
  int count = 0;
  for (@SuppressWarnings("unused") Cache.Entry<?, ?> entry : cache) {
    count++;
  }
  return count;
}
 
Example 12
Source File: NopStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Cache.Entry<K, ValueHolder<V>>> iterator() {
  return new Iterator<Cache.Entry<K, ValueHolder<V>>>() {
    @Override
    public boolean hasNext() {
      return false;
    }

    @Override
    public Cache.Entry<K, ValueHolder<V>> next() {
      throw new NoSuchElementException();
    }
  };
}
 
Example 13
Source File: ClusteredStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleChainMultipleValues() throws StoreAccessException {
  assertThat(Long.hashCode(1L), is(Long.hashCode(~1L)));

  store.put(1L, "foo");
  store.put(~1L, "bar");

  Store.Iterator<Cache.Entry<Long, Store.ValueHolder<String>>> iterator = store.iterator();

  Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryOne = isEntry(1L, "foo");
  Matcher<Cache.Entry<Long, Store.ValueHolder<String>>> entryTwo = isEntry(~1L, "bar");

  assertThat(iterator.hasNext(), is(true));

  Cache.Entry<Long, Store.ValueHolder<String>> next = iterator.next();
  assertThat(next, either(entryOne).or(entryTwo));

  if (entryOne.matches(next)) {
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.next(), is(entryTwo));
    assertThat(iterator.hasNext(), is(false));
  } else {
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.next(), is(entryOne));
    assertThat(iterator.hasNext(), is(false));
  }

  try {
    iterator.next();
    fail("Expected NoSuchElementException");
  } catch (NoSuchElementException e) {
    //expected
  }
}
 
Example 14
Source File: EhcacheIteratorTest.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
private Iterator<Long> getIterator() {
  return new EhcacheIterator<Long, String, Long>(basicCache.iterator()) {

    @Override
    protected Long getNext(Iterator<Cache.Entry<Long, String>> cacheIterator) {
      return cacheIterator.next().getKey();
    }
  };
}
 
Example 15
Source File: EHCacheTokenStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Collection<String> getTokenIdentifiers() {
    if (cache == null) {
        return null;
    }

    // Not very efficient, but we are only using this method for testing
    Set<String> keys = new HashSet<>();
    for (Cache.Entry<String, SecurityToken> entry : cache) {
        keys.add(entry.getKey());
    }

    return keys;
}
 
Example 16
Source File: EhcacheBasicIteratorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link java.util.Iterator#next()} from {@link Ehcache#iterator()} on a non-empty cache.
 */
@Test
public void testIteratorNonEmptyStoreNext() throws Exception {
  this.store = new FakeStore(this.getTestStoreEntries());
  final InternalCache<String, String> ehcache = this.getEhcache();
  final Iterator<Cache.Entry<String, String>> iterator = ehcache.iterator();
  assertThat(iterator.next(), is(notNullValue()));
}
 
Example 17
Source File: AbstractResilienceStrategy.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Cache.Entry<K, V> iteratorFailure(StoreAccessException e) {
  LOGGER.error("Ehcache iterator terminated early due to exception", e);
  throw new CacheIterationException(e);
}
 
Example 18
Source File: XAStore.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Cache.Entry<K, ValueHolder<V>>> iterator() {
  XATransactionContext<K, V> currentContext = getCurrentContext();
  Map<K, XAValueHolder<V>> valueHolderMap = transactionContextFactory.listPuts(currentContext.getTransactionId());
  return new XAIterator(valueHolderMap, underlyingStore.iterator(), currentContext.getTransactionId());
}
 
Example 19
Source File: LocalLoaderWriterStore.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Cache.Entry<K, ValueHolder<V>>> iterator() {
  return delegate.iterator();
}
 
Example 20
Source File: Store.java    From ehcache3 with Apache License 2.0 2 votes vote down vote up
/**
 * Returns an iterator over the elements in this store.
 * <p>
 * The elements are returned in no particular order.
 *
 * @return an iterator over the mappings in this Store
 */
Store.Iterator<Cache.Entry<K, ValueHolder<V>>> iterator();