org.ehcache.core.config.DefaultConfiguration Java Examples

The following examples show how to use org.ehcache.core.config.DefaultConfiguration. 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: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDestroyCacheFailsAndStopIfStartingServicesFails() throws CachePersistenceException, InterruptedException {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  List<Service> services = minimumCacheManagerServices();
  MaintainableService service = mock(MaintainableService.class);
  doThrow(new RuntimeException("failed")).when(service)
    .startForMaintenance(Mockito.<ServiceProvider<MaintainableService>>any(), eq(MaintainableService.MaintenanceScope.CACHE));
  services.add(service);

  EhcacheManager manager = new EhcacheManager(config, services);

  expectedException.expect(StateTransitionException.class);
  expectedException.expectMessage("failed");

  manager.destroyCache("test");

  assertThat(manager.getStatus(), equalTo(Status.UNINITIALIZED));
}
 
Example #2
Source File: CacheConfiguration.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
private CacheManager createInMemoryCacheManager() {
    long cacheSize = jHipsterProperties.getCache().getEhcache().getMaxEntries();
    long ttl = jHipsterProperties.getCache().getEhcache().getTimeToLiveSeconds();

    org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder
        .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder
            .heap(cacheSize))
        .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ttl)))
        .build();

    Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = createCacheConfigurations(cacheConfiguration);

    EhcacheCachingProvider provider = getCachingProvider();
    DefaultConfiguration configuration = new DefaultConfiguration(caches, getClassLoader());
    return getCacheManager(provider, configuration);
}
 
Example #3
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 #4
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotNotifyAboutCacheOnInitOrClose() {
  final CacheConfiguration<Object, Object> cacheConfiguration = new TestCacheConfig<>(Object.class, Object.class);
  final Store.Provider mock = mock(Store.Provider.class);
  when(mock.rank(any(Set.class), any(Collection.class))).thenReturn(1);

  final CacheEventDispatcherFactory cenlProvider = mock(CacheEventDispatcherFactory.class);
  final CacheEventDispatcher<Object, Object> cenlServiceMock = mock(CacheEventDispatcher.class);
  when(cenlProvider.createCacheEventDispatcher(any(Store.class))).thenReturn(cenlServiceMock);

  final Collection<Service> services = getServices(mock, cenlProvider);
  when(mock.createStore(ArgumentMatchers.<Store.Configuration>any())).thenReturn(mock(Store.class));
  final String cacheAlias = "bar";
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  caches.put(cacheAlias, cacheConfiguration);
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  EhcacheManager cacheManager = new EhcacheManager(config, services);
  final CacheManagerListener listener = mock(CacheManagerListener.class);
  cacheManager.registerListener(listener);
  cacheManager.init();
  final Cache<Object, Object> bar = cacheManager.getCache(cacheAlias, Object.class, Object.class);
  verify(listener, never()).cacheAdded(cacheAlias, bar);
  cacheManager.close();
  verify(listener, never()).cacheRemoved(cacheAlias, bar);
}
 
Example #5
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotifyAboutCache() {
  final CacheConfiguration<Object, Object> cacheConfiguration = new TestCacheConfig<>(Object.class, Object.class);
  final Store.Provider mock = mock(Store.Provider.class);
  when(mock.rank(any(Set.class), any(Collection.class))).thenReturn(1);

  final CacheEventDispatcherFactory cenlProvider = mock(CacheEventDispatcherFactory.class);
  final CacheEventDispatcher<Object, Object> cenlServiceMock = mock(CacheEventDispatcher.class);
  when(cenlProvider.createCacheEventDispatcher(any(Store.class))).thenReturn(cenlServiceMock);

  final Collection<Service> services = getServices(mock, cenlProvider);
  when(mock.createStore(ArgumentMatchers.<Store.Configuration>any())).thenReturn(mock(Store.class));
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  EhcacheManager cacheManager = new EhcacheManager(config, services);
  final CacheManagerListener listener = mock(CacheManagerListener.class);
  cacheManager.registerListener(listener);
  cacheManager.init();
  final String cacheAlias = "bar";
  cacheManager.createCache(cacheAlias, cacheConfiguration);
  final Cache<Object, Object> bar = cacheManager.getCache(cacheAlias, Object.class, Object.class);
  verify(listener).cacheAdded(cacheAlias, bar);
  cacheManager.removeCache(cacheAlias);
  verify(listener).cacheRemoved(cacheAlias, bar);
}
 
Example #6
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStopAllServicesWhenCacheInitializationFails() {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  caches.put("myCache", mock(CacheConfiguration.class));
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  List<Service> services = minimumCacheManagerServices();
  EhcacheManager cacheManager = new EhcacheManager(config, services);

  Store.Provider storeProvider = (Store.Provider) services.get(0); // because I know it's the first of the list

  try {
    cacheManager.init();
    fail("Should have thrown...");
  } catch (StateTransitionException ste) {
    verify(storeProvider).stop();
  }
}
 
Example #7
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 #8
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyCacheFailsIfAlreadyInMaintenanceMode() throws CachePersistenceException, InterruptedException {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  final EhcacheManager manager = new EhcacheManager(config, minimumCacheManagerServices());

  Thread thread = new Thread(() -> manager.getStatusTransitioner().maintenance().succeeded());
  thread.start();
  thread.join(1000);

  expectedException.expect(IllegalStateException.class);
  expectedException.expectMessage("State is MAINTENANCE, yet you don't own it!");

  manager.destroyCache("test");
}
 
Example #9
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000L)
public void testCloseWhenCacheCreationFailsDuringInitialization() throws Exception {
  Store.Provider storeProvider = mock(Store.Provider.class);
  when(storeProvider.rank(any(Set.class), any(Collection.class))).thenReturn(1);
  doThrow(new Error("Test EhcacheManager close.")).when(storeProvider).createStore(any(Store.Configuration.class), ArgumentMatchers.<ServiceConfiguration>any());

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

  final CountDownLatch countDownLatch = new CountDownLatch(1);

  Executors.newSingleThreadExecutor().submit(() -> {
    try {
      cacheManager.init();
    } catch (Error err) {
      assertThat(err.getMessage(), equalTo("Test EhcacheManager close."));
      countDownLatch.countDown();
    }
  });
  countDownLatch.await();
  try {
    cacheManager.close();
  } catch (IllegalStateException e) {
    assertThat(e.getMessage(), is("Close not supported from UNINITIALIZED"));
  }
  assertThat(cacheManager.getStatus(), is(Status.UNINITIALIZED));

}
 
Example #10
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseWhenRuntimeCacheCreationFails() throws Exception {
  Store.Provider storeProvider = mock(Store.Provider.class);
  when(storeProvider.rank(any(Set.class), any(Collection.class))).thenReturn(1);
  doThrow(new Error("Test EhcacheManager close.")).when(storeProvider).createStore(any(Store.Configuration.class), ArgumentMatchers.<ServiceConfiguration>any());

  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  final CacheManager cacheManager = new EhcacheManager(config, Arrays.asList(
      storeProvider,
      mock(CacheLoaderWriterProvider.class),
      mock(WriteBehindProvider.class),
      mock(CacheEventDispatcherFactory.class),
      mock(CacheEventListenerProvider.class),
      mock(LocalPersistenceService.class),
      mock(ResilienceStrategyProvider.class)
  ));

  cacheManager.init();

  CacheConfiguration<Long, String> cacheConfiguration = new TestCacheConfig<>(Long.class, String.class);

  try {
    cacheManager.createCache("cache", cacheConfiguration);
    fail();
  } catch (Error err) {
    assertThat(err.getMessage(), equalTo("Test EhcacheManager close."));
  }

  cacheManager.close();
  assertThat(cacheManager.getStatus(), is(Status.UNINITIALIZED));

}
 
Example #11
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 #12
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoesNotifyAboutLifecycle() {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  EhcacheManager cacheManager = new EhcacheManager(config, getServices(null, null));
  final CacheManagerListener listener = mock(CacheManagerListener.class);
  cacheManager.registerListener(listener);
  cacheManager.init();
  verify(listener).stateTransition(Status.UNINITIALIZED, Status.AVAILABLE);
  cacheManager.close();
  verify(listener).stateTransition(Status.AVAILABLE, Status.UNINITIALIZED);
}
 
Example #13
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testReturnsNullForNonExistCache() {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  EhcacheManager cacheManager = new EhcacheManager(config, getServices(null, null));
  cacheManager.init();
  assertThat(cacheManager.getCache("foo", Object.class, Object.class), nullValue());
}
 
Example #14
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreationFailsOnDuplicateServiceCreationConfiguration() {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null, (ServiceCreationConfiguration<NoSuchService, Void>) () -> NoSuchService.class, (ServiceCreationConfiguration<NoSuchService, Void>) () -> NoSuchService.class);
  try {
    new EhcacheManager(config);
    fail("Should have thrown ...");
  } catch (IllegalStateException e) {
    assertThat(e.getMessage(), containsString("NoSuchService"));
  }
}
 
Example #15
Source File: Application.java    From conciliator with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public CacheManager cacheManager(@Autowired Config config) {
    long ttl = Long.valueOf(config.getProperties().getProperty(Config.PROP_CACHE_TTL));

    config.getProperties().getProperty(Config.PROP_CACHE_SIZE);

    MemSize memSize = MemSize.valueOf(config.getProperties().getProperty(Config.PROP_CACHE_SIZE));

    LogFactory.getLog(getClass()).info(
            String.format("Initializing cache TTL=%d secs, size=%d %s",
                    ttl, memSize.getSize(), memSize.getUnit().toString()));

    org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Object.class, Object.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                            .heap(memSize.getSize(), memSize.getUnit()))
            .withExpiry(Expirations.timeToLiveExpiration(new org.ehcache.expiry.Duration(ttl, TimeUnit.SECONDS)))
            .build();

    Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
    caches.put(CACHE_DEFAULT, cacheConfiguration);

    EhcacheCachingProvider provider = (EhcacheCachingProvider) javax.cache.Caching.getCachingProvider();

    // when our cacheManager bean is re-created several times for
    // diff test configurations, this provider seems to hang on to state
    // causing cache settings to not be right. so we always close().
    provider.close();

    DefaultConfiguration configuration = new DefaultConfiguration(
            caches, provider.getDefaultClassLoader());

    return new JCacheCacheManager(
            provider.getCacheManager(provider.getDefaultURI(), configuration));
}
 
Example #16
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCanDestroyAndClose() throws Exception {
  CacheConfiguration<Long, String> cacheConfiguration = new TestCacheConfig<>(Long.class, String.class);

  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));

  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  caches.put("aCache", cacheConfiguration);
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  PersistentCacheManager 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();

  cacheManager.close();
  cacheManager.init();
  cacheManager.close();
  cacheManager.destroy();
  cacheManager.init();
  cacheManager.close();
}
 
Example #17
Source File: EhcacheManager.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public EhcacheManager(Configuration config, UnaryOperator<ServiceLocator.DependencySet> customization, boolean useLoaderInAtomics) {
  final String simpleName = this.getClass().getSimpleName();
  this.simpleName = (simpleName.isEmpty() ? this.getClass().getName() : simpleName);
  this.configuration = new DefaultConfiguration(config);
  this.cacheManagerClassLoader = config.getClassLoader() != null ? config.getClassLoader() : ClassLoading.getDefaultClassLoader();
  this.useLoaderInAtomics = useLoaderInAtomics;
  validateServicesConfigs();
  this.serviceLocator = resolveServices(customization);
}
 
Example #18
Source File: DefaultCacheLoaderWriterProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheConfigOverridesCacheManagerConfig() {
  final CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, heap(10))
      .withService(new DefaultCacheLoaderWriterConfiguration(MyOtherLoader.class))
      .build();

  final Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
  caches.put("foo", cacheConfiguration);
  final DefaultConfiguration configuration = new DefaultConfiguration(caches, null, new DefaultCacheLoaderWriterProviderConfiguration()
      .addLoaderFor("foo", MyLoader.class));
  final CacheManager manager = CacheManagerBuilder.newCacheManager(configuration);
  manager.init();
  final Object foo = manager.getCache("foo", Object.class, Object.class).get(new Object());
  assertThat(foo, is(MyOtherLoader.object));
}
 
Example #19
Source File: DefaultCacheLoaderWriterProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheManagerConfigUsage() {

  final CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, heap(10))
      .build();

  final Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
  caches.put("foo", cacheConfiguration);
  final DefaultConfiguration configuration = new DefaultConfiguration(caches, null, new DefaultCacheLoaderWriterProviderConfiguration()
      .addLoaderFor("foo", MyLoader.class));
  final CacheManager manager = CacheManagerBuilder.newCacheManager(configuration);
  manager.init();
  final Object foo = manager.getCache("foo", Object.class, Object.class).get(new Object());
  assertThat(foo, is(MyLoader.object));
}
 
Example #20
Source File: ResourceCombinationsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicCacheOperation() throws IOException, URISyntaxException {
  Configuration config = new DefaultConfiguration(ResourceCombinationsTest.class.getClassLoader(),
          new DefaultPersistenceConfiguration(diskPath.newFolder()));
  try (CacheManager cacheManager = new EhcacheCachingProvider().getCacheManager(URI.create("dummy"), config)) {
    Cache<String, String> cache = cacheManager.createCache("test", fromEhcacheCacheConfiguration(
      newCacheConfigurationBuilder(String.class, String.class, resources)));
    cache.put("foo", "bar");
    assertThat(cache.get("foo"), is("bar"));
  }
}
 
Example #21
Source File: IteratorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIterateExpiredIsSkipped() throws Exception {
  EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider();
  TestTimeSource testTimeSource = new TestTimeSource();
  TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(testTimeSource);
  CacheManager cacheManager = provider.getCacheManager(new URI("test://testIterateExpiredReturnsNull"), new DefaultConfiguration(getClass().getClassLoader(), timeSourceConfiguration));

  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", new MutableConfiguration<Number, CharSequence>()
      .setExpiryPolicyFactory(() -> new ExpiryPolicy() {
        @Override
        public Duration getExpiryForCreation() {
          return Duration.ETERNAL;
        }

        @Override
        public Duration getExpiryForAccess() {
          return new Duration(TimeUnit.SECONDS, 1L);
        }

        @Override
        public Duration getExpiryForUpdate() {
          return Duration.ZERO;
        }
      })
      .setTypes(Number.class, CharSequence.class));

  testCache.put(1, "one");
  testCache.get(1);

  testTimeSource.advanceTime(1000);

  Iterator<Cache.Entry<Number, CharSequence>> iterator = testCache.iterator();
  assertThat(iterator.hasNext(), is(false));

  cacheManager.close();
}
 
Example #22
Source File: EhCache107ConfigurationIntegrationDocTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheManagerLevelConfiguration() throws Exception {
  // tag::ehcacheCacheManagerConfigurationExample[]
  CachingProvider cachingProvider = Caching.getCachingProvider();
  EhcacheCachingProvider ehcacheProvider = (EhcacheCachingProvider) cachingProvider; // <1>

  DefaultConfiguration configuration = new DefaultConfiguration(ehcacheProvider.getDefaultClassLoader(),
    new DefaultPersistenceConfiguration(getPersistenceDirectory())); // <2>

  CacheManager cacheManager = ehcacheProvider.getCacheManager(ehcacheProvider.getDefaultURI(), configuration); // <3>
  // end::ehcacheCacheManagerConfigurationExample[]

  assertThat(cacheManager, notNullValue());
}
 
Example #23
Source File: CacheConfiguration.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
private CacheManager createClusteredCacheManager() {
    ApplicationProperties.Cluster clusterProperties = applicationProperties.getCluster();
    URI clusterUri = clusterProperties.getUri();
    boolean autoCreate = clusterProperties.isAutoCreate();
    long clusteredCacheSize = clusterProperties.getSizeInMb();
    String offheapResourceName = clusterProperties.getOffheapResourceName();
    Consistency consistency = clusterProperties.getConsistency();

    long heapCacheSize = jHipsterProperties.getCache().getEhcache().getMaxEntries();
    long ttl = jHipsterProperties.getCache().getEhcache().getTimeToLiveSeconds();

    ClusteringServiceConfigurationBuilder clusteringServiceConfigurationBuilder = ClusteringServiceConfigurationBuilder.cluster(clusterUri);
    ServerSideConfigurationBuilder serverSideConfigurationBuilder = (autoCreate ? clusteringServiceConfigurationBuilder.autoCreate() : clusteringServiceConfigurationBuilder.expecting())
        .defaultServerResource(offheapResourceName);

    org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder
        .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder
            .heap(heapCacheSize)
            .with(ClusteredResourcePoolBuilder.clusteredDedicated(clusteredCacheSize, MemoryUnit.MB)))
        .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ttl)))
        .add(new ClusteredStoreConfiguration(consistency)).build();

    Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = createCacheConfigurations(cacheConfiguration);

    EhcacheCachingProvider provider = getCachingProvider();
    DefaultConfiguration configuration = new DefaultConfiguration(caches, getClassLoader(), serverSideConfigurationBuilder.build());
    return getCacheManager(provider, configuration);
}
 
Example #24
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testChangesToManagerAreReflectedInConfig() {
  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();

  try {
    final CacheConfiguration<Long, String> cache2Configuration = new TestCacheConfig<>(Long.class, String.class, ResourcePoolsHelper
      .createResourcePools(100L));
    final Cache<Long, String> cache = cacheManager.createCache("cache2", cache2Configuration);
    final CacheConfiguration<?, ?> cacheConfiguration = cacheManager.getRuntimeConfiguration()
        .getCacheConfigurations()
        .get("cache2");

    assertThat(cacheConfiguration, notNullValue());
    final CacheConfiguration<?, ?> runtimeConfiguration = cache.getRuntimeConfiguration();
    assertThat(cacheConfiguration == runtimeConfiguration, is(true));
    assertThat(cacheManager.getRuntimeConfiguration().getCacheConfigurations().get("cache1")
               == cacheManager.getCache("cache1", Long.class, String.class).getRuntimeConfiguration(), is(true));

    cacheManager.removeCache("cache1");
    assertThat(cacheManager.getRuntimeConfiguration().getCacheConfigurations().containsKey("cache1"), is(false));
  } finally {
    cacheManager.close();
  }
}
 
Example #25
Source File: CacheConfiguration.java    From ehcache3-samples with Apache License 2.0 4 votes vote down vote up
private CacheManager getCacheManager(EhcacheCachingProvider provider, DefaultConfiguration configuration) {
    return provider.getCacheManager(provider.getDefaultURI(), configuration);
}