Java Code Examples for org.ehcache.config.builders.CacheConfigurationBuilder#newCacheConfigurationBuilder()

The following examples show how to use org.ehcache.config.builders.CacheConfigurationBuilder#newCacheConfigurationBuilder() . 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: CacheManagerListenerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheConfigurationBuilder<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .heap(1, MB).disk(2, MB));

  cacheManagerListener = mock(CacheManagerListener.class);

  cacheManager = (EhcacheManager) CacheManagerBuilder.newCacheManagerBuilder()
    .with(new CacheManagerPersistenceConfiguration(folder.getRoot()))
    .withCache(CACHE, cacheConfiguration)
    .build();
  cacheManager.registerListener(cacheManagerListener);
  cacheManager.init();
}
 
Example 2
Source File: DefaultClusteringServiceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreate() throws Exception {
  CacheConfigurationBuilder<Long, String> configBuilder =
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .with(ClusteredResourcePoolBuilder.clusteredShared("primary")));
  ClusteringServiceConfiguration configuration =
      ClusteringServiceConfigurationBuilder.cluster(URI.create(CLUSTER_URI_BASE + "my-application"))
          .autoCreate(c -> c)
          .build();
  DefaultClusteringService service = new DefaultClusteringService(configuration);

  PersistableResourceService.PersistenceSpaceIdentifier<?> spaceIdentifier = service.getPersistenceSpaceIdentifier("cacheAlias", configBuilder
      .build());
  assertThat(spaceIdentifier, instanceOf(ClusteredCacheIdentifier.class));
  assertThat(((ClusteredCacheIdentifier) spaceIdentifier).getId(), is("cacheAlias"));
}
 
Example 3
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAll_without_cache_writer() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };
  // the call to removeAll
  myCache.removeAll(fewKeysSet);

  for (int i = 0; i < 3; i++) {
    if (i == 0 || i == 2) {
      assertThat(myCache.get("key" + i), is(nullValue()));
    } else {
      assertThat(myCache.get("key" + i), is("value" + i));
    }
  }

}
 
Example 4
Source File: DefaultStatisticsServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  CacheConfigurationBuilder<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .heap(1, MB));

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .using(service)
    .withCache(CACHE, cacheConfiguration)
    .build();
}
 
Example 5
Source File: Tiering.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleTier() {
  // tag::clusteredOnly[]
  CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, // <1>
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .with(ClusteredResourcePoolBuilder.clusteredDedicated(2, MemoryUnit.GB))); // <2>
  // end::clusteredOnly[]
}
 
Example 6
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoveryWithInflightTx() throws Exception {
  CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
              .heap(10, EntryUnit.ENTRIES)
              .offheap(10, MemoryUnit.MB));

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("txCache1", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache1")).build())
      .withCache("txCache2", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache2")).build())
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
      .build(true);

  Cache<Long, String> txCache1 = cacheManager.getCache("txCache1", Long.class, String.class);
  Cache<Long, String> txCache2 = cacheManager.getCache("txCache2", Long.class, String.class);

  transactionManager.begin();
  {
    txCache1.put(1L, "one");
    txCache2.put(1L, "un");
  }
  transactionManager.commit();


  transactionManager.begin();
  {
    txCache1.remove(1L);
    txCache2.remove(1L);
  }
  transactionManager.getCurrentTransaction().addTransactionStatusChangeListener((oldStatus, newStatus) -> {
    if (newStatus == Status.STATUS_PREPARED) {
      Recoverer recoverer = TransactionManagerServices.getRecoverer();
      recoverer.run();
      assertThat(recoverer.getCommittedCount(), is(0));
      assertThat(recoverer.getRolledbackCount(), is(0));
    }
  });
  transactionManager.commit();
}
 
Example 7
Source File: EhCacheBuilder.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Cache<K, V> build(CacheManager manager) {
  checkNotNull(manager);
  checkNotNull(keyType);
  checkNotNull(valueType);
  checkNotNull(name);
  checkNotNull(expiryFactory);

  CacheConfigurationBuilder<K, V> builder = CacheConfigurationBuilder.newCacheConfigurationBuilder(
      keyType,
      valueType,
      ResourcePoolsBuilder.heap(cacheSize));

  builder.withExpiry(mapToEhCacheExpiry(expiryFactory.create()));

  Cache<K, V> cache = manager.createCache(name,  Eh107Configuration.fromEhcacheCacheConfiguration(builder));

  manager.enableStatistics(name, statisticsEnabled);
  manager.enableManagement(name, managementEnabled);

  if (persister != null) {
    CacheEventListener listener = (final CacheEvent cacheEvent) ->
        persister.accept((K) cacheEvent.getKey(), (V) cacheEvent.getOldValue());

    Eh107Configuration<K, V> configuration = cache.getConfiguration(Eh107Configuration.class);
    configuration.unwrap(CacheRuntimeConfiguration.class)
        .registerCacheEventListener(listener, EventOrdering.UNORDERED, EventFiring.ASYNCHRONOUS,
            EventType.EVICTED, EventType.REMOVED, EventType.EXPIRED);
  }

  return cache;
}
 
Example 8
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll_store_throws_cache_exception() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriter.load(ArgumentMatchers.any())).thenThrow(new RuntimeException("We should not have called .load() but .loadAll()"));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);
  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider).using(new CustomStoreProvider());
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  when(cacheLoaderWriter.loadAll(argThat(hasItems("key0", "key2")))).thenReturn( new HashMap(){{put("key0","value0");  put("key2","value2");}});

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };

  // the call to getAll
  Map<String, String> fewEntries = myCache.getAll(fewKeysSet);

  assertThat(fewEntries.size(), is(2));
  assertThat(fewEntries.get("key0"), is("value0"));
  assertThat(fewEntries.get("key2"), is("value2"));

}
 
Example 9
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll_cache_loader_throws_exception() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriter.load(ArgumentMatchers.any())).thenThrow(new RuntimeException("We should not have called .load() but .loadAll()"));
  when(cacheLoaderWriter.loadAll(ArgumentMatchers.any(Iterable.class))).thenThrow(new Exception("Simulating an exception from the cache loader"));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);
  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriter).build();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };


  // the call to getAll
  try {
    myCache.getAll(fewKeysSet);
    fail();
  } catch (BulkCacheLoadingException bcwe) {
    // since onHeapStore.bulkComputeIfAbsent sends batches of 1 element,
    assertThat(bcwe.getFailures().size(), is(2));
    assertThat(bcwe.getSuccesses().size(), is(0));
  }

}
 
Example 10
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll_with_cache_loader() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriter.load(ArgumentMatchers.any())).thenThrow(new RuntimeException("We should not have called .load() but .loadAll()"));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);
  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriter).build();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  when(cacheLoaderWriter.loadAll(argThat(IsCollectionContaining.<String>hasItem("key0")))).thenReturn(new HashMap(){{put("key0","value0");}});
  when(cacheLoaderWriter.loadAll(argThat(IsCollectionContaining.<String>hasItem("key2")))).thenReturn(new HashMap(){{put("key2","value2");}});

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };
  // the call to getAll
  Map<String, String> fewEntries = myCache.getAll(fewKeysSet);

  assertThat(fewEntries.size(), is(2));
  assertThat(fewEntries.get("key0"), is("value0"));
  assertThat(fewEntries.get("key2"), is("value2"));

}
 
Example 11
Source File: CacheManagerListenerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheAdded() throws Exception {
  CacheConfigurationBuilder<Long, String> otherCacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .heap(1, MB).disk(2, MB));

  Cache<Long, String> otherCache = cacheManager.createCache("otherCache", otherCacheConfiguration);
  verify(cacheManagerListener).cacheAdded("otherCache", otherCache);

}
 
Example 12
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
  public void testPutAll_store_throws_cache_exception() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
        heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder
        .build();


    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriter).write(ArgumentMatchers.any(), ArgumentMatchers.any());
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);

    CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider).using(new CustomStoreProvider());
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

    Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

    Map<String, String> stringStringHashMap = new HashMap<>();
    for (int i = 0; i < 3; i++) {
      stringStringHashMap.put("key" + i, "value" + i);
    }

    // the call to putAll
    myCache.putAll(stringStringHashMap);

    for (int i = 0; i < 3; i++) {
      // the store threw an exception when we call bulkCompute
      assertThat(myCache.get("key" + i), is(nullValue()));
      // but still, the cache writer could writeAll the values !
//      assertThat(cacheWriterToHashMapMap.get("key" + i), is("value" + i));
    }
    // but still, the cache writer could writeAll the values at once !
    verify(cacheLoaderWriter, times(1)).writeAll(ArgumentMatchers.any(Iterable.class));
    Set set = new HashSet() {{add(entry("key0", "value0")); add(entry("key1", "value1")); add(entry("key2", "value2"));}};
    verify(cacheLoaderWriter).writeAll(set);
  }
 
Example 13
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAll_with_cache_writer_that_throws_exception() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriterThatThrows = mock(CacheLoaderWriter.class);
  doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriterThatThrows).write(ArgumentMatchers
      .any(), ArgumentMatchers.any());
  doThrow(new Exception("Simulating an exception from the cache writer")).when(cacheLoaderWriterThatThrows).writeAll(ArgumentMatchers.any(Iterable.class));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriterThatThrows);

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriterThatThrows).build();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  HashMap<String, String> stringStringHashMap = new HashMap<>();
  for (int i = 0; i < 3; i++) {
    stringStringHashMap.put("key" + i, "value" + i);
  }

  // the call to putAll
  try {
    myCache.putAll(stringStringHashMap);
    fail();
  } catch (BulkCacheWritingException bcwe) {
    assertThat(bcwe.getFailures().size(), is(3));
    assertThat(bcwe.getSuccesses().size(), is(0));
  }

}
 
Example 14
Source File: CacheManagerProvider.java    From TweetwallFX with MIT License 5 votes vote down vote up
private static org.ehcache.CacheManager createCacheManager() {
    final CacheSettings cacheSettings = Configuration.getInstance().getConfigTyped(CacheSettings.CONFIG_KEY, CacheSettings.class);
    CacheManagerBuilder<? extends org.ehcache.CacheManager> cacheManagerBuilder = CacheManagerBuilder
            .newCacheManagerBuilder()
            .with(new CacheManagerPersistenceConfiguration(new File(
                    System.getProperty("user.home"),
                    cacheSettings.getPersistenceDirectoryName())));

    for (final Map.Entry<String, CacheSettings.CacheSetting> entry : cacheSettings.getCaches().entrySet()) {
        final String alias = entry.getKey();
        final CacheSettings.CacheSetting cacheSetting = entry.getValue();

        CacheConfigurationBuilder<?, ?> builder = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(
                        loadClass(cacheSetting.getKeyType()),
                        loadClass(cacheSetting.getValueType()),
                        createResourcePoolsBuilder(cacheSetting.getCacheResources()));

        if (null != cacheSetting.getExpiry()) {
            builder = builder.withExpiry(createExpiryPolicy(cacheSetting.getExpiry()));
        }

        cacheManagerBuilder = cacheManagerBuilder.withCache(alias, builder);
    }

    final org.ehcache.CacheManager cacheManager = cacheManagerBuilder.build(true);

    LOG.info("EHCaches: " + cacheManager.getRuntimeConfiguration().getCacheConfigurations().keySet());
    cacheManager.getRuntimeConfiguration().getCacheConfigurations().keySet().forEach(s -> LOG.info("EHCache: " + s));
    Runtime.getRuntime().addShutdownHook(new Thread(cacheManager::close, "cache-shutdown"));

    return cacheManager;
}
 
Example 15
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveAll_cache_writer_throws_exception() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriterThatThrows = mock(CacheLoaderWriter.class);
  doThrow(new Exception("Simulating an exception from the cache writer")).when(cacheLoaderWriterThatThrows).deleteAll(ArgumentMatchers.any(Iterable.class));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriterThatThrows);

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriterThatThrows)
          .build();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriterThatThrows).write(ArgumentMatchers
      .any(), ArgumentMatchers.any());

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };

  // the call to removeAll
  try {
    myCache.removeAll(fewKeysSet);
    fail();
  } catch (BulkCacheWritingException bcwe) {
    assertThat(bcwe.getFailures().size(), is(2));
    assertThat(bcwe.getSuccesses().size(), is(0));
  }

}
 
Example 16
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveAll_with_store_that_throws() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder
      .build();

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider).using(new CustomStoreProvider());
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriter).write(ArgumentMatchers
      .any(), ArgumentMatchers.any());

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };

  // the call to removeAll
  myCache.removeAll(fewKeysSet);
  for (int i = 0; i < 3; i++) {
    if (i == 0 || i == 2) {
      assertThat(myCache.get("key" + i), is(nullValue()));

    } else {
      assertThat(myCache.get("key" + i), is("value" + i));
    }
  }

  Set set = new HashSet(){{add("key0"); add("key2");}};
  verify(cacheLoaderWriter).deleteAll(set);

}
 
Example 17
Source File: EhcacheBaseTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
private CacheConfigurationBuilder<Integer, String> baseConfig() {
  return CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, resources);
}
 
Example 18
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testEndToEnd() throws Exception {
  CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
              .heap(10, EntryUnit.ENTRIES)
              .offheap(10, MemoryUnit.MB));

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
      .withCache("txCache1", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache1")).build())
      .withCache("txCache2", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache2")).build())
      .withCache("nonTxCache", cacheConfigurationBuilder.build())
      .build(true);

  Cache<Long, String> txCache1 = cacheManager.getCache("txCache1", Long.class, String.class);
  Cache<Long, String> txCache2 = cacheManager.getCache("txCache2", Long.class, String.class);
  Cache<Long, String> nonTxCache = cacheManager.getCache("nonTxCache", Long.class, String.class);

  nonTxCache.put(1L, "eins");
  assertThat(nonTxCache.get(1L), equalTo("eins"));

  try {
    txCache1.put(1L, "one");
    fail("expected XACacheException");
  } catch (XACacheException e) {
    // expected
  }

  transactionManager.begin();
  {
    txCache1.put(1L, "one");
  }
  transactionManager.commit();

  transactionManager.begin();
  {
    txCache1.get(1L);
    txCache2.get(1L);
  }
  transactionManager.commit();

  transactionManager.begin();
  {
    String s = txCache1.get(1L);
    assertThat(s, equalTo("one"));
    txCache1.remove(1L);

    Transaction suspended = transactionManager.suspend();
    transactionManager.begin();
    {
      txCache2.put(1L, "uno");
      String s2 = txCache1.get(1L);
      assertThat(s2, equalTo("one"));
    }
    transactionManager.commit();
    transactionManager.resume(suspended);

    String s1 = txCache2.get(1L);
    assertThat(s1, equalTo("uno"));

  }
  transactionManager.commit();
}
 
Example 19
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRecoveryAfterCrash() throws Exception {
  CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
              .heap(10, EntryUnit.ENTRIES)
              .offheap(10, MemoryUnit.MB)
              .disk(20, MemoryUnit.MB, true));

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(getStoragePath()))
      .withCache("txCache1", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache1")).build())
      .withCache("txCache2", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache2")).build())
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
      .build(true);

  Cache<Long, String> txCache1 = cacheManager.getCache("txCache1", Long.class, String.class);
  Cache<Long, String> txCache2 = cacheManager.getCache("txCache2", Long.class, String.class);

  transactionManager.begin();
  {
    txCache1.put(1L, "one");
    txCache2.put(1L, "un");
  }
  transactionManager.getCurrentTransaction().addTransactionStatusChangeListener((oldStatus, newStatus) -> {
    if (newStatus == Status.STATUS_COMMITTING) {
      throw new AbortError();
    }
  });
  try {
    transactionManager.commit();
    fail("expected AbortError");
  } catch (AbortError e) {
    // expected
  }

  cacheManager.close();
  txCache1 = null;
  txCache2 = null;
  transactionManager.shutdown();

  initTransactionManagerServices();
  transactionManager = TransactionManagerServices.getTransactionManager();
  cacheManager.init();

  txCache1 = cacheManager.getCache("txCache1", Long.class, String.class);
  txCache2 = cacheManager.getCache("txCache2", Long.class, String.class);

  transactionManager.begin();
  {
    assertThat(txCache1.get(1L), equalTo("one"));
    assertThat(txCache2.get(1L), equalTo("un"));
  }
  transactionManager.commit();
}
 
Example 20
Source File: EhCachePoolMixin.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
private <T> EhCacheImpl<T> createNewCache( String cacheId, Class<T> valueType )
{
    configuration.refresh();
    EhCacheConfiguration config = configuration.get();

    ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();

    poolsBuilder = poolsBuilder.heap( config.heapSize().get(), MemoryUnit.valueOf( config.heapUnit().get() ) );

    if( config.offHeapSize().get() != null )
    {
        poolsBuilder = poolsBuilder.offheap( config.offHeapSize().get(),
                                             MemoryUnit.valueOf( config.offHeapUnit().get() ) );
    }
    if( config.diskSize().get() != null )
    {
        poolsBuilder = poolsBuilder.disk( config.diskSize().get(),
                                          MemoryUnit.valueOf( config.diskUnit().get() ),
                                          config.diskPersistent().get() );
    }

    CacheConfigurationBuilder<String, T> configBuilder = CacheConfigurationBuilder
        .newCacheConfigurationBuilder( String.class, valueType, poolsBuilder );
    if( config.maxObjectSize().get() != null )
    {
        configBuilder = configBuilder.withSizeOfMaxObjectSize( config.maxObjectSize().get(),
                                                               MemoryUnit.valueOf( config.maxObjectSizeUnit().get() ) );
    }
    if( config.maxObjectGraphDepth().get() != null )
    {
        configBuilder = configBuilder.withSizeOfMaxObjectGraph( config.maxObjectGraphDepth().get() );
    }
    switch( config.expiry().get() )
    {
        case "TIME_TO_IDLE":
            configBuilder = configBuilder.withExpiry( timeToIdleExpiration( Duration.of(
                config.expiryLength().get() == null ? - 1L : config.expiryLength().get(),
                TimeUnit.valueOf( config.expiryTimeUnit().get() ) ) ) );
            break;
        case "TIME_TO_LIVE":
            configBuilder = configBuilder.withExpiry( timeToLiveExpiration( Duration.of(
                config.expiryLength().get() == null ? - 1L : config.expiryLength().get(),
                TimeUnit.valueOf( config.expiryTimeUnit().get() ) ) ) );
            break;
        case "NONE":
        default:
            configBuilder = configBuilder.withExpiry( noExpiration() );
            break;
    }
    CacheConfiguration<String, T> cacheConfig = configBuilder.build();
    org.ehcache.Cache<String, T> cache = cacheManager.createCache( cacheId, cacheConfig );
    return new EhCacheImpl<>( cacheId, cache, valueType );
}