Java Code Examples for org.ehcache.CacheManager#init()

The following examples show how to use org.ehcache.CacheManager#init() . 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: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListener() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/ehcache-cacheEventListener.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  cache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED));
  cache.put(10, "cat");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
  cache.remove(10);
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED));
  cache.put(10, "dog");
  resetValues();
  assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
  final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class);
  templateCache.put(10,"cat");
  assertThat(TestCacheEventListener.FIRED_EVENT, nullValue());
  templateCache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
}
 
Example 2
Source File: OnHeapStoreByValueTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStoreByValue() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(false);
  cacheManager.init();

  DefaultCopierConfiguration<String> copierConfiguration = new DefaultCopierConfiguration<>(
    SerializingCopier.<String>asCopierClass(), DefaultCopierConfiguration.Type.VALUE);
  final Cache<Long, String> cache1 = cacheManager.createCache("cache1",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(1))
          .build());
  performAssertions(cache1, true);

  final Cache<Long, String> cache2 = cacheManager.createCache("cache2",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(1))
          .withService(copierConfiguration)
          .build());
  performAssertions(cache2, false);

  final Cache<Long, String> cache3 = cacheManager.createCache("cache3",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(1))
          .build());
  performAssertions(cache3, true);

  cacheManager.close();
}
 
Example 3
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadPoolsUsingDefaultPool() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/thread-pools.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  try {
    Cache<String, String> cache = cacheManager.createCache("testThreadPools", newCacheConfigurationBuilder(String.class, String.class, heap(10))
            .withService(new DefaultCacheLoaderWriterConfiguration(ThreadRememberingLoaderWriter.class))
            .withService(newUnBatchedWriteBehindConfiguration())
            .build());

    cache.put("foo", "bar");

    ThreadRememberingLoaderWriter.USED.acquireUninterruptibly();

    assertThat(ThreadRememberingLoaderWriter.LAST_SEEN_THREAD.getName(), containsString("[big]"));
  } finally {
    cacheManager.close();
  }
}
 
Example 4
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadPools() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/thread-pools.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  try {
    Cache<String, String> cache = cacheManager.createCache("testThreadPools", newCacheConfigurationBuilder(String.class, String.class, heap(10))
            .withService(new DefaultCacheLoaderWriterConfiguration(ThreadRememberingLoaderWriter.class))
            .withService(newUnBatchedWriteBehindConfiguration().useThreadPool("small"))
            .build());

    cache.put("foo", "bar");

    ThreadRememberingLoaderWriter.USED.acquireUninterruptibly();

    assertThat(ThreadRememberingLoaderWriter.LAST_SEEN_THREAD.getName(), containsString("[small]"));
  } finally {
    cacheManager.close();
  }
}
 
Example 5
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListenerWithMultipleListener() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/ehcache-multipleCacheEventListener.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  resetValues();
  cache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED));
  assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT, is(nullValue()));
  resetValues();
  cache.put(10, "cat");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
  assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT.getType(), is(EventType.UPDATED));
  resetValues();
  cache.remove(10);
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED));
  assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT.getType(), is(EventType.REMOVED));
}
 
Example 6
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoaderWriter() throws ClassNotFoundException, SAXException, InstantiationException,
    IOException, IllegalAccessException {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/cache-integration.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  assertThat(cache, notNullValue());
  assertThat(cache.get(1), notNullValue());
  final Number key = new Long(42);
  cache.put(key, "Bye y'all!");
  assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key));

  assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
  final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class);
  assertThat(templateCache, notNullValue());
  assertThat(templateCache.get(1), notNullValue());
  final Number key1 = new Long(100);
  templateCache.put(key1, "Bye y'all!");
  assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1));
}
 
Example 7
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopiers() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/cache-copiers.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();

  Cache<Description, Person> bar = cacheManager.getCache("bar", Description.class, Person.class);
  Description desc = new Description(1234, "foo");
  Person person = new Person("Bar", 24);
  bar.put(desc, person);
  assertEquals(person, bar.get(desc));
  assertNotSame(person, bar.get(desc));

  Cache<Long, Person> baz = cacheManager.getCache("baz", Long.class, Person.class);
  baz.put(1L, person);
  assertEquals(person, baz.get(1L));
  assertNotSame(person, baz.get(1L));

  Employee empl = new Employee(1234, "foo", 23);
  Cache<Long, Employee> bak = cacheManager.getCache("bak", Long.class, Employee.class);
  bak.put(1L, empl);
  assertSame(empl, bak.get(1L));
  cacheManager.close();
}
 
Example 8
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializers() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/default-serializer.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();

  Cache<Long, Double> bar = cacheManager.getCache("bar", Long.class, Double.class);
  bar.put(1L, 1.0);
  assertThat(bar.get(1L), equalTo(1.0));

  Cache<String, String> baz = cacheManager.getCache("baz", String.class, String.class);
  baz.put("1", "one");
  assertThat(baz.get("1"), equalTo("one"));

  Cache<String, Object> bam = cacheManager.createCache("bam", newCacheConfigurationBuilder(String.class, Object.class, heap(10)).build());
  bam.put("1", "one");
  assertThat(bam.get("1"), equalTo((Object)"one"));

  cacheManager.close();
}
 
Example 9
Source File: TestEhcache.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
@Test
public void testTem() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("preConfigured",
       CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

    cacheManager.init();

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

    Cache<Long, String> myCache = cacheManager.createCache("myCache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)));

    myCache.put(1L, "da one!");
    myCache.putIfAbsent(0L, "ee");
    String value = myCache.get(1L);

    System.out.println("Value is " + value);
    cacheManager.removeCache("preConfigured");
    cacheManager.close();
}
 
Example 10
Source File: SimpleClusteredCacheByXmlTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testViaXml() throws Exception {
  final Configuration configuration = new XmlConfiguration(this.getClass().getResource(SIMPLE_CLUSTER_XML));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);

  assertThat(cacheManager, is(instanceOf(PersistentCacheManager.class)));

  cacheManager.init();

  final Cache<Long, String> cache = cacheManager.getCache("simple-cache", Long.class, String.class);
  assertThat(cache, is(not(nullValue())));

  cacheManager.close();
}
 
Example 11
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBehind() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SAXException, IOException, InterruptedException {

  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/writebehind-cache.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  assertThat(cache, notNullValue());
  assertThat(cache.get(1), notNullValue());
  final Number key = 42L;
  TestCacheLoaderWriter.latch = new CountDownLatch(1);
  cache.put(key, "Bye y'all!");
  TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS);
  assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key));

  assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
  final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class);
  assertThat(templateCache, notNullValue());
  assertThat(templateCache.get(1), notNullValue());
  final Number key1 = 100L;
  TestCacheLoaderWriter.latch = new CountDownLatch(2);
  templateCache.put(42L, "Howdy!");
  templateCache.put(key1, "Bye y'all!");
  TestCacheLoaderWriter.latch.await(2, TimeUnit.SECONDS);
  assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1));

}
 
Example 12
Source File: EhcacheFactory.java    From pippo with Apache License 2.0 5 votes vote down vote up
public static CacheManager create(String path) {
    URL url = ClassLoader.getSystemResource(path);
    Configuration xmlConfig = new XmlConfiguration(url);
    CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
    cacheManager.init();
    return cacheManager;
}
 
Example 13
Source File: XmlConfigTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_config_loaded() throws Exception {
  CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(new XmlConfiguration(getClass().getClassLoader().getResource(xml)));
  myCacheManager.init();
  try {
    DefaultManagementRegistryConfiguration registryConfiguration = null;

    for (ServiceCreationConfiguration<?, ?> configuration : myCacheManager.getRuntimeConfiguration().getServiceCreationConfigurations()) {
      if (configuration instanceof DefaultManagementRegistryConfiguration) {
        registryConfiguration = (DefaultManagementRegistryConfiguration) configuration;
        break;
      }
    }

    assertThat(registryConfiguration, is(not(nullValue())));

    // 1st test: CM alia not set, so generated
    if (xml.endsWith("-1.xml")) {
      expectedConfiguration.setCacheManagerAlias(registryConfiguration.getContext().get("cacheManagerName"));
    }

    assertThat(registryConfiguration.getCacheManagerAlias(), equalTo(expectedConfiguration.getCacheManagerAlias()));
    assertThat(registryConfiguration.getCollectorExecutorAlias(), equalTo(expectedConfiguration.getCollectorExecutorAlias()));
    assertThat(registryConfiguration.getContext(), equalTo(expectedConfiguration.getContext()));
    assertThat(registryConfiguration.getTags(), equalTo(expectedConfiguration.getTags()));

  } finally {
    myCacheManager.close();
  }
}
 
Example 14
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 15
Source File: FieldCache.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
public FieldCache(){
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("fields",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(DEFAULT_CACHE_SIZE_ENTRIES)))
            .build();
    cacheManager.init();
    fieldCache = cacheManager.getCache("fields", String.class, String.class);
}
 
Example 16
Source File: XAGettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testXACacheWithXMLConfig() throws Exception {
  // tag::testXACacheWithXMLConfig[]
  BitronixTransactionManager transactionManager =
      TransactionManagerServices.getTransactionManager(); // <1>

  URL myUrl = this.getClass().getResource("/docs/configs/xa-getting-started.xml"); // <2>
  Configuration xmlConfig = new XmlConfiguration(myUrl); // <3>
  CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); // <4>
  myCacheManager.init();

  myCacheManager.close();
  transactionManager.shutdown();
  // end::testXACacheWithXMLConfig[]
}
 
Example 17
Source File: XmlConfigTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleConfig() throws Exception {
  TransactionManagerServices.getConfiguration().setJournal("null").setServerId("XmlConfigTest");
  BitronixTransactionManager transactionManager = TransactionManagerServices.getTransactionManager();

  final URL myUrl = this.getClass().getResource("/configs/simple-xa.xml");
  Configuration xmlConfig = new XmlConfiguration(myUrl);
  CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
  myCacheManager.init();

  myCacheManager.close();
  transactionManager.shutdown();
}
 
Example 18
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 19
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 20
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();
  }
}