org.ehcache.config.CacheConfiguration Java Examples

The following examples show how to use org.ehcache.config.CacheConfiguration. 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: BasicClusteredCacheOpsReplicationMultiThreadedTest.java    From ehcache3 with Apache License 2.0 7 votes vote down vote up
@Before
public void startServers() throws Exception {
  CLUSTER.getClusterControl().startAllServers();
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/crud-cm-replication"))
          .timeouts(TimeoutsBuilder.timeouts() // we need to give some time for the failover to occur
              .read(Duration.ofMinutes(1))
              .write(Duration.ofMinutes(1)))
          .autoCreate(server -> server.defaultServerResource("primary-server-resource")));
  cacheManager1 = clusteredCacheManagerBuilder.build(true);
  cacheManager2 = clusteredCacheManagerBuilder.build(true);
  CacheConfiguration<Long, BlobValue> config = CacheConfigurationBuilder
      .newCacheConfigurationBuilder(Long.class, BlobValue.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder().heap(500, EntryUnit.ENTRIES)
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB)))
      .withService(ClusteredStoreConfigurationBuilder.withConsistency(cacheConsistency))
      .build();

  cache1 = cacheManager1.createCache(testName.getMethodName(), config);
  cache2 = cacheManager2.createCache(testName.getMethodName(), config);

  caches = Arrays.asList(cache1, cache2);
}
 
Example #2
Source File: DefaultCacheStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration((CacheEventListener<Long, String>) expirations::add, EventType.EXPIRED)
    .unordered()
    .synchronous();

  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(cacheEventListenerConfiguration)
      .withService(new StoreStatisticsConfiguration(enableStoreStatistics))
      .build();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("aCache", cacheConfiguration)
    .using(new TimeSourceConfiguration(timeSource))
    .build(true);

  cache = (InternalCache<Long, String>) cacheManager.getCache("aCache", Long.class, String.class);

  cacheStatistics = new DefaultCacheStatistics(cache);
}
 
Example #3
Source File: TieringTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
  public void testPersistentDiskCache() throws Exception {
    CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).disk(10L, MemoryUnit.MB, true))
        .build();

    PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .with(new CacheManagerPersistenceConfiguration(new File(getClass().getClassLoader().getResource(".").toURI().getPath() + "/../../persistent-cache-data")))
        .withCache("persistent-cache", cacheConfiguration)
        .build(true);

    Cache<Long, String> cache = persistentCacheManager.getCache("persistent-cache", Long.class, String.class);

    // Comment the following line on subsequent run and see the test pass
    cache.put(42L, "That's the answer!");
    assertThat(cache.get(42L), is("That's the answer!"));

    // Uncomment the following line to nuke the disk store
//    persistentCacheManager.destroyCache("persistent-cache");

    persistentCacheManager.close();
  }
 
Example #4
Source File: JCacheCacheFactory.java    From cache2k-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
protected <K, V> BenchmarkCache<K, V> createSpecialized(
  final Class<K> _keyType, final Class<V> _valueType, final int _maxElements) {
  MyBenchmarkCacheAdapter c = new MyBenchmarkCacheAdapter();
  String _cacheName = constructCacheName(_maxElements);
  CacheManager mgr = resolveCacheManager();
  if (mgr.getClass().getName().toString().contains("Eh107")) {
     CacheConfiguration<K, V> _eh107Configuration =
       CacheConfigurationBuilder.newCacheConfigurationBuilder(_keyType, _valueType,
        ResourcePoolsBuilder.heap(_maxElements)).build();
      c.cache = mgr.createCache(_cacheName,
        Eh107Configuration.fromEhcacheCacheConfiguration(_eh107Configuration));
  } else if (mgr.getClass().getName().toString().contains("cache2k")) {
    c.cache = mgr.createCache(_cacheName,
      ExtendedMutableConfiguration.of(
        Cache2kBuilder.of(_keyType, _valueType)
          .entryCapacity(_maxElements)));
  } else {
    c.cache = mgr.getCache(_cacheName);
  }
  if (c.cache == null) {
    throw new NullPointerException("No cache returned for name: " + _cacheName);
  }
  return c;
}
 
Example #5
Source File: CacheCopierTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadWriteCopier() throws Exception {
  CacheConfiguration<Long, Person> cacheConfiguration = baseConfig
      .withService(new DefaultCopierConfiguration<>(PersonCopier.class, DefaultCopierConfiguration.Type.VALUE))
      .build();

  Cache<Long, Person> cache = cacheManager.createCache("cache", cacheConfiguration);

  Person original = new Person("Bar", 24);
  cache.put(1l, original);

  Person retrieved = cache.get(1l);
  assertNotSame(original, retrieved);
  assertThat(retrieved.name, equalTo("Bar"));
  assertThat(retrieved.age, equalTo(24));

  original.age = 56;
  retrieved = cache.get(1l);
  assertThat(retrieved.age, equalTo(24));

  assertNotSame(cache.get(1l), cache.get(1l));
}
 
Example #6
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicClusteredCacheLoaderWriter() {

  TestCacheLoaderWriter loaderWriter = new TestCacheLoaderWriter();
  CacheConfiguration<Long, String> cacheConfiguration = getCacheConfiguration(loaderWriter);

  try (CacheManager cacheManager = CacheManagerBuilder
          .newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("cache-1", cacheConfiguration)
          .build(true)) {

    Cache<Long, String> cache = cacheManager.getCache("cache-1", Long.class, String.class);

    cache.put(1L, "1");

    assertThat(cache.get(1L), is("1"));

    assertThat(loaderWriter.storeMap.get(1L), is("1"));
  }
}
 
Example #7
Source File: EhcacheRuntimeConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateFailureDoesNotUpdate() {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES).build()).build();

  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("cache", cacheConfiguration).build(true)) {

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

    ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
    poolsBuilder = poolsBuilder.heap(20L, EntryUnit.ENTRIES).disk(10, MemoryUnit.MB);
    ResourcePools pools = poolsBuilder.build();
    try {
      cache.getRuntimeConfiguration().updateResourcePools(pools);
      fail("We expect illegal arguments");
    } catch (IllegalArgumentException iae) {
      // expected
      assertThat(iae.getMessage(), is("Pools to be updated cannot contain previously undefined resources pools"));
    }
    assertThat(cache.getRuntimeConfiguration().getResourcePools()
      .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(10L));
  }
}
 
Example #8
Source File: DefaultCacheEventListenerConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void unparseServiceConfiguration() {
  DefaultCacheEventListenerConfiguration listenerConfig =
    new DefaultCacheEventListenerConfiguration(EnumSet.of(CREATED, REMOVED), TestCacheEventListener.class);
  listenerConfig.setEventFiringMode(SYNCHRONOUS);
  listenerConfig.setEventOrderingMode(UNORDERED);

  CacheConfiguration<?, ?> cacheConfig = newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withService(listenerConfig).build();
  CacheType cacheType = new CacheType();
  cacheType = new DefaultCacheEventListenerConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType);

  List<ListenersType.Listener> listeners = cacheType.getListeners().getListener();
  assertThat(listeners).hasSize(1);
  ListenersType.Listener listener = listeners.get(0);
  assertThat(listener.getEventFiringMode()).isEqualTo(EventFiringType.SYNCHRONOUS);
  assertThat(listener.getEventOrderingMode()).isEqualTo(EventOrderingType.UNORDERED);
  assertThat(listener.getEventsToFireOn()).contains(org.ehcache.xml.model.EventType.CREATED, org.ehcache.xml.model.EventType.REMOVED);
}
 
Example #9
Source File: TestEviction.java    From jframe with Apache License 2.0 6 votes vote down vote up
public void evictionTest() {
    CacheConfiguration<Long, String> cacheConfiguration =
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(2L)).build();
    // .withEvictionAdvisor(new OddKeysEvictionAdvisor<Long, String>()).build();

    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration).build(true);

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

    // Work with the cache
    cache.put(42L, "The Answer!");
    cache.put(41L, "The wrong Answer!");
    cache.put(39L, "The other wrong Answer!");

    cacheManager.close();
}
 
Example #10
Source File: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void byteSizedTieredCache() {
  // tag::byteSizedTieredCache[]
  CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, MemoryUnit.KB) // <1>
      .offheap(10, MemoryUnit.MB)) // <2>
    .withSizeOfMaxObjectGraph(1000)
    .withSizeOfMaxObjectSize(1000, MemoryUnit.B) // <3>
    .build();

  CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, MemoryUnit.KB))
    .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B)
    .withDefaultSizeOfMaxObjectGraph(2000) // <4>
    .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig)
    .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig)
    .build(true);
  // end::byteSizedTieredCache[]
}
 
Example #11
Source File: UnSupportedCombinationsWithClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredCacheWithSynchronousEventListeners() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(new TestEventListener(), EventType.CREATED, EventType.UPDATED)
      .unordered().synchronous();

  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application"))
          .autoCreate(c -> c));
  try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
            .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB)))
        .withService(cacheEventListenerConfiguration)
        .build();

    cacheManager.createCache("test", config);
    fail("IllegalStateException expected");
  } catch (IllegalStateException e){
    assertThat(e.getCause().getMessage(), is("Synchronous CacheEventListener is not supported with clustered tiers"));
  }
}
 
Example #12
Source File: JCacheCalculationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  CachingProvider cachingProvider = Caching.getCachingProvider();
  EhcacheCachingProvider ehcacheProvider = (EhcacheCachingProvider) cachingProvider;

  DefaultConfiguration configuration = new DefaultConfiguration(ehcacheProvider.getDefaultClassLoader(),
    new DefaultPersistenceConfiguration(diskPath.newFolder()));

  CacheConfiguration<Integer, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, resources).build();
  configuration.addCacheConfiguration("cache", cacheConfiguration);

  cacheManager = ehcacheProvider.getCacheManager(ehcacheProvider.getDefaultURI(), configuration);

  EhcacheManager ehcacheManager = cacheManager.unwrap(EhcacheManager.class);
  Field field = EhcacheManager.class.getDeclaredField("serviceLocator");
  field.setAccessible(true);
  @SuppressWarnings("unchecked")
  ServiceProvider<Service> serviceProvider = (ServiceProvider<Service>)field.get(ehcacheManager);
  StatisticsService statisticsService = serviceProvider.getService(StatisticsService.class);

  cache = cacheManager.getCache("cache", Integer.class, String.class);

  cacheStatistics = statisticsService.getCacheStatistics("cache");
}
 
Example #13
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void clusteredCacheManagerWithDynamicallyAddedCacheExample() throws Exception {
  // tag::clusteredCacheManagerWithDynamicallyAddedCacheExample[]
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
          = CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application"))
                  .autoCreateOnReconnect(server -> server.defaultServerResource("primary-server-resource")
                    .resourcePool("resource-pool-a", 8, MemoryUnit.MB)));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  try {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
            ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))).build();

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);

  } finally {
    cacheManager.close();
  }
  // end::clusteredCacheManagerWithDynamicallyAddedCacheExample[]
}
 
Example #14
Source File: DefaultCopierConfigurationParser.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public CacheType unparseServiceConfiguration(CacheConfiguration<?, ?> cacheConfiguration, CacheType cacheType) {
  Collection<DefaultCopierConfiguration> copierConfigs =
    findAmongst(DefaultCopierConfiguration.class, cacheConfiguration.getServiceConfigurations());
  for (DefaultCopierConfiguration copierConfig : copierConfigs) {
    if(copierConfig.getInstance() == null) {
      if (copierConfig.getType() == DefaultCopierConfiguration.Type.KEY) {
        cacheType.getKeyType().setCopier(copierConfig.getClazz().getName());
      } else {
        cacheType.getValueType().setCopier(copierConfig.getClazz().getName());
      }
    } else {
      throw new XmlConfigurationException("XML translation for instance based initialization for DefaultCopierConfiguration is not supported");
    }
  }
  return cacheType;
}
 
Example #15
Source File: DefaultSerializerConfigurationParser.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override @SuppressWarnings({"rawtypes", "unchecked"})
public CacheType unparseServiceConfiguration(CacheConfiguration<?, ?> cacheConfiguration, CacheType cacheType) {
  Collection<DefaultSerializerConfiguration> serializerConfigs =
    findAmongst(DefaultSerializerConfiguration.class, cacheConfiguration.getServiceConfigurations());
  for (DefaultSerializerConfiguration serializerConfig : serializerConfigs) {
    if(serializerConfig.getInstance() == null) {
      if (serializerConfig.getType() == DefaultSerializerConfiguration.Type.KEY) {
        cacheType.getKeyType().setSerializer(serializerConfig.getClazz().getName());
      } else {
        cacheType.getValueType().setSerializer(serializerConfig.getClazz().getName());
      }
    } else {
      throw new XmlConfigurationException("XML translation for instance based initialization for DefaultSerializerConfiguration is not supported");
    }
  }
  return cacheType;
}
 
Example #16
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheEvictionAdvisor() throws Exception {
  // tag::cacheEvictionAdvisor[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                                                                      ResourcePoolsBuilder.heap(2L)) // <1>
      .withEvictionAdvisor(new OddKeysEvictionAdvisor<>()) // <2>
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("cache", cacheConfiguration)
      .build(true);

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

  // Work with the cache
  cache.put(42L, "The Answer!");
  cache.put(41L, "The wrong Answer!");
  cache.put(39L, "The other wrong Answer!");

  cacheManager.close();
  // end::cacheEvictionAdvisor[]
}
 
Example #17
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 #18
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructionThrowsWhenNotBeingToResolveService() {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  final DefaultConfiguration config = new DefaultConfiguration(caches, null, (ServiceCreationConfiguration<NoSuchService, Void>) () -> NoSuchService.class);
  try {
    new EhcacheManager(config);
    fail("Should have thrown...");
  } catch (IllegalStateException e) {
    assertThat(e.getMessage(), containsString(NoSuchService.class.getName()));
  }
}
 
Example #19
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 #20
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 #21
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultInstanceReturned() {
  ResilienceStrategy<?, ?> resilienceStrategy = mock(ResilienceStrategy.class);

  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  configuration.setDefaultResilienceStrategy(resilienceStrategy);

  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  assertThat(provider.createResilienceStrategy("foo", mock(CacheConfiguration.class), mock(RecoveryStore.class)), sameInstance(resilienceStrategy));
}
 
Example #22
Source File: DefaultManagementRegistryServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void descriptorOnHeapTest_withoutStats() {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
    .build();

  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("aCache", cacheConfiguration)
      .using(managementRegistry)
      .build(true)) {

    List<Capability> capabilities = new ArrayList<>(managementRegistry.getCapabilities());
    assertThat(managementRegistry.getCapabilities()).hasSize(4);
    assertThat(capabilities.get(0).getName()).isEqualTo("ActionsCapability");
    assertThat(capabilities.get(1).getName()).isEqualTo("SettingsCapability");
    assertThat(capabilities.get(2).getName()).isEqualTo("StatisticCollectorCapability");
    assertThat(capabilities.get(3).getName()).isEqualTo("StatisticsCapability");

    assertThat(capabilities.get(0).getDescriptors()).hasSize(4);

    Collection<? extends Descriptor> descriptors = capabilities.get(3).getDescriptors();
    Collection<Descriptor> allDescriptors = new ArrayList<>();
    allDescriptors.addAll(ONHEAP_NO_STATS_DESCRIPTORS);
    allDescriptors.addAll(CACHE_DESCRIPTORS);

    assertThat(descriptors).containsOnlyElementsOf(allDescriptors);
  }
}
 
Example #23
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreconfiguredLoaderWriterInstanceReturned() {
  ResilienceStrategy<?, ?> resilienceStrategy = mock(ResilienceStrategy.class);

  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  configuration.addResilienceStrategyFor("foo", resilienceStrategy);

  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  assertThat(provider.createResilienceStrategy("foo", mock(CacheConfiguration.class), mock(RecoveryStore.class), mock(CacheLoaderWriter.class)), sameInstance(resilienceStrategy));
}
 
Example #24
Source File: DefaultCacheLoaderWriterConfigurationParserTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void parseServiceConfiguration() throws Exception {
  CacheConfiguration<?, ?> cacheConfiguration = new XmlConfiguration(getClass().getResource("/configs/writebehind-cache.xml")).getCacheConfigurations().get("bar");
  DefaultCacheLoaderWriterConfiguration loaderWriterConfig =
    findSingletonAmongst(DefaultCacheLoaderWriterConfiguration.class, cacheConfiguration.getServiceConfigurations());

  assertThat(loaderWriterConfig).isNotNull();
  assertThat(loaderWriterConfig.getClazz()).isEqualTo(TestCacheLoaderWriter.class);
}
 
Example #25
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testResilienceStrategy() throws Exception {
  final URL resource = XmlConfigurationTest.class.getResource("/configs/resilience-config.xml");
  XmlConfiguration xmlConfig = new XmlConfiguration(new XmlConfiguration(resource));
  CacheConfiguration<?, ?> cacheConfig = xmlConfig.getCacheConfigurations().get("ni");

  DefaultResilienceStrategyConfiguration resilienceStrategyConfiguration = findSingletonAmongst(DefaultResilienceStrategyConfiguration.class, cacheConfig.getServiceConfigurations());
  assertThat(resilienceStrategyConfiguration.getClazz(), sameInstance(NiResilience.class));
}
 
Example #26
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCachesAddedAtRuntimeGetReInited() {
  Store.Provider storeProvider = mock(Store.Provider.class);
  when(storeProvider.rank(any(Set.class), any(Collection.class))).thenReturn(1);
  Store store = mock(Store.class);
  CacheEventDispatcherFactory cacheEventNotificationListenerServiceProvider = mock(CacheEventDispatcherFactory.class);

  when(storeProvider.createStore(any(Store.Configuration.class), ArgumentMatchers.<ServiceConfiguration>any())).thenReturn(store);
  when(store.getConfigurationChangeListeners()).thenReturn(new ArrayList<>());
  when(cacheEventNotificationListenerServiceProvider.createCacheEventDispatcher(store)).thenReturn(mock(CacheEventDispatcher.class));

  CacheConfiguration<Long, String> cache1Configuration = new TestCacheConfig<>(Long.class, String.class);
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  caches.put("cache1", cache1Configuration);
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  CacheManager cacheManager = new EhcacheManager(config, Arrays.asList(
      storeProvider,
      mock(CacheLoaderWriterProvider.class),
      mock(WriteBehindProvider.class),
      cacheEventNotificationListenerServiceProvider,
      mock(CacheEventListenerProvider.class),
      mock(LocalPersistenceService.class),
      mock(ResilienceStrategyProvider.class)
  ));
  cacheManager.init();


  CacheConfiguration<Long, String> cache2Configuration = new TestCacheConfig<>(Long.class, String.class, ResourcePoolsHelper.createResourcePools(100L));
  cacheManager.createCache("cache2", cache2Configuration);
  cacheManager.removeCache("cache1");

  cacheManager.close();
  cacheManager.init();
  try {
    assertThat(cacheManager.getCache("cache1", Long.class, String.class), nullValue());
    assertThat(cacheManager.getCache("cache2", Long.class, String.class), notNullValue());
  } finally {
    cacheManager.close();
  }
}
 
Example #27
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvidedInstanceReturned() {
  ResilienceStrategy<?, ?> resilienceStrategy = mock(ResilienceStrategy.class);

  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  CacheConfiguration<?, ?> cacheConfiguration = mock(CacheConfiguration.class);
  when(cacheConfiguration.getServiceConfigurations()).thenReturn(Collections.singleton(new DefaultResilienceStrategyConfiguration(resilienceStrategy)));

  assertThat(provider.createResilienceStrategy("foo", cacheConfiguration, mock(RecoveryStore.class)), sameInstance(resilienceStrategy));
}
 
Example #28
Source File: DefaultManagementRegistryServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallOnInexistignContext() throws ExecutionException {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .build();

  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("aCache1", cacheConfiguration)
        .withCache("aCache2", cacheConfiguration)
        .using(managementRegistry)
        .build(true)) {

    Context inexisting = Context.empty()
        .with("cacheManagerName", "myCM2")
        .with("cacheName", "aCache2");

    ResultSet<? extends ContextualReturn<?>> results = managementRegistry.withCapability("ActionsCapability")
        .call("clear")
        .on(inexisting)
        .build()
        .execute();

    assertThat(results.size()).isEqualTo(1);
    assertThat(results.getSingleResult().hasExecuted()).isFalse();

    expectedException.expect(NoSuchElementException.class);
    results.getSingleResult().getValue();
  }
}
 
Example #29
Source File: DefaultCacheEventDispatcherConfigurationParserTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void unparseServiceConfiguration() {
  CacheConfiguration<?, ?> cacheConfig =
    newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withService(new DefaultCacheEventDispatcherConfiguration("foo")).build();
  CacheType cacheType = new CacheType();
  cacheType = new DefaultCacheEventDispatcherConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType);

  assertThat(cacheType.getListeners().getDispatcherThreadPool()).isEqualTo("foo");
}
 
Example #30
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiskStoreSettings() throws Exception {
  final URL resource = XmlConfigurationTest.class.getResource("/configs/resources-caches.xml");
  XmlConfiguration xmlConfig = new XmlConfiguration(new XmlConfiguration(resource));

  CacheConfiguration<?, ?> cacheConfig = xmlConfig.getCacheConfigurations().get("tiered");

  OffHeapDiskStoreConfiguration diskConfig = findSingletonAmongst(OffHeapDiskStoreConfiguration.class, cacheConfig.getServiceConfigurations());

  assertThat(diskConfig.getThreadPoolAlias(), is("some-pool"));
  assertThat(diskConfig.getWriterConcurrency(), is(2));
  assertThat(diskConfig.getDiskSegments(), is(4));
}