Java Code Examples for org.ehcache.config.builders.CacheManagerBuilder#newCacheManager()

The following examples show how to use org.ehcache.config.builders.CacheManagerBuilder#newCacheManager() . 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: EhCacheProvider3.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Properties props) {
    String sDefaultHeapSize = props.getProperty("defaultHeapSize");
    try {
        this.defaultHeapSize = Long.parseLong(sDefaultHeapSize);
    }catch(Exception e) {
        log.warn("Failed to read ehcache3.defaultHeapSize = {} , use default {}", sDefaultHeapSize, defaultHeapSize);
    }
    String configXml = props.getProperty("configXml");
    if(configXml == null || configXml.trim().length() == 0)
        configXml = "/ehcache3.xml";

    URL url = getClass().getResource(configXml);
    url = (url == null) ? getClass().getClassLoader().getResource(configXml) : url;

    Configuration xmlConfig = new XmlConfiguration(url);
    manager = CacheManagerBuilder.newCacheManager(xmlConfig);
    manager.init();
}
 
Example 2
Source File: ClusteredOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testXmlClusteredCache(OsgiTestUtils.Cluster cluster) throws Exception {
  File config = cluster.getWorkingArea().resolve("ehcache.xml").toFile();

  Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(TestMethods.class.getResourceAsStream("ehcache-clustered-osgi.xml"));
  XPath xpath = XPathFactory.newInstance().newXPath();
  Node clusterUriAttribute = (Node) xpath.evaluate("//config/service/cluster/connection/@url", doc, XPathConstants.NODE);
  clusterUriAttribute.setTextContent(cluster.getConnectionUri().toString() + "/cache-manager");
  Transformer xformer = TransformerFactory.newInstance().newTransformer();
  xformer.transform(new DOMSource(doc), new StreamResult(config));


  try (PersistentCacheManager cacheManager = (PersistentCacheManager) CacheManagerBuilder.newCacheManager(
    new XmlConfiguration(config.toURI().toURL(), TestMethods.class.getClassLoader())
  )) {
    cacheManager.init();

    final Cache<Long, Person> cache = cacheManager.getCache("clustered-cache", Long.class, Person.class);

    cache.put(1L, new Person("Brian"));
    assertThat(cache.get(1L).name, is("Brian"));
  }
}
 
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: EHCacheIdentityCache.java    From cxf with Apache License 2.0 6 votes vote down vote up
public EHCacheIdentityCache(
    IdentityMapper identityMapper, String key, Bus b, URL configFileURL
) {
    super(b, identityMapper);
    if (b != null) {
        b.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
        InstrumentationManager im = b.getExtension(InstrumentationManager.class);
        if (im != null) {
            try {
                im.register(this);
            } catch (JMException e) {
                LOG.log(Level.WARNING, "Registering EHCacheIdentityCache failed.", e);
            }
        }
    }

    URL xmlConfigURL = configFileURL != null ? configFileURL : getDefaultConfigFileURL();
    Configuration xmlConfig = new XmlConfiguration(xmlConfigURL);
    cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);

    cacheManager.init();
    cache = cacheManager.getCache(KEY, String.class, EHCacheIdentityValue.class);
}
 
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: EHCache3Manager.java    From javalite with Apache License 2.0 6 votes vote down vote up
public EHCache3Manager() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    URL url = getClass().getResource("/activejdbc-ehcache.xml");
    if(url == null){
        throw new InitException("You are using " + getClass().getName() + " but failed to provide a EHCache configuration file on classpath: activejdbc-ehcache.xml");
    }

    XmlConfiguration xmlConfiguration = new XmlConfiguration(url);

    cacheTemplate = xmlConfiguration.newCacheConfigurationBuilderFromTemplate("activejdbc", String.class, Object.class);

    if(cacheTemplate == null){
        throw new InitException("Please, provide a <cache-template name=\"activejdbc\"> element in  activejdbc-ehcache.xml file");
    }
    cacheManager = CacheManagerBuilder.newCacheManager(xmlConfiguration);
    cacheManager.init();
}
 
Example 9
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 10
Source File: EhCacheIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    URL url = EhCacheIntegrationTest.class.getResource("/cache-configuration.xml");
    Configuration xmlConfig = new XmlConfiguration(url);

    cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
    cacheManager.init();

    context.bind("cacheManager", cacheManager);
}
 
Example 11
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void xmlConfigSample() throws Exception {
  // tag::xmlConfig[]
  final URL myUrl = getClass().getResource("/configs/docs/getting-started.xml"); // <1>
  XmlConfiguration xmlConfig = new XmlConfiguration(myUrl); // <2>
  CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); // <3>
  myCacheManager.init();  // <4>
  // end::xmlConfig[]
}
 
Example 12
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 13
Source File: EhcacheShiroManager.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
private org.ehcache.CacheManager ensureCacheManager() throws MalformedURLException {
  if (manager == null) {
    manager = CacheManagerBuilder.newCacheManager(getConfiguration());
    manager.init();

    cacheManagerImplicitlyCreated = true;
  }

  return manager;
}
 
Example 14
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 15
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 16
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 17
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 18
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 19
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 20
Source File: EhCache3Manager.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
/** Create singleton instance for EhCache3Manager. */

private EhCache3Manager() {
	this.manager= CacheManagerBuilder.newCacheManager(xmlConf);
	this.manager.init();
}