org.ehcache.config.Configuration Java Examples

The following examples show how to use org.ehcache.config.Configuration. 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 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 #2
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 #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: XmlMultiConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleConfigurationBuiltFromEmpty() {
  Configuration config = emptyConfiguration();

  XmlMultiConfiguration xmlMultiConfiguration = XmlMultiConfiguration.fromNothing().withManager("foo", config).build();

  assertThat(xmlMultiConfiguration.configuration("foo"), sameInstance(config));
  assertThat(xmlMultiConfiguration.configuration("foo", "prod"), sameInstance(config));

  assertThat(xmlMultiConfiguration.identities(), containsInAnyOrder("foo"));
  assertThat(xmlMultiConfiguration.variants("foo"), empty());

  assertThat(xmlMultiConfiguration.toString(),
    isSimilarTo(
      "<configurations xmlns='http://www.ehcache.org/v3/multi'>" +
        "<configuration identity='foo'><config xmlns='http://www.ehcache.org/v3'/></configuration>" +
      "</configurations>").ignoreWhitespace().ignoreComments());
}
 
Example #5
Source File: XmlMultiConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testVariantConfigurationBuiltFromEmpty() {
  Configuration barVariant = emptyConfiguration();
  Configuration bazVariant = emptyConfiguration();
  XmlMultiConfiguration xmlMultiConfiguration = XmlMultiConfiguration.fromNothing()
    .withManager("foo").variant("bar", barVariant).variant("baz", bazVariant).build();

  assertThrows(() -> xmlMultiConfiguration.configuration("foo"), IllegalStateException.class);

  assertThat(xmlMultiConfiguration.configuration("foo", "bar"), sameInstance(barVariant));
  assertThat(xmlMultiConfiguration.configuration("foo", "baz"), sameInstance(bazVariant));

  assertThat(xmlMultiConfiguration.identities(), containsInAnyOrder("foo"));
  assertThat(xmlMultiConfiguration.variants("foo"), containsInAnyOrder("bar", "baz"));

  assertThat(xmlMultiConfiguration.toString(), isSimilarTo(
    "<configurations xmlns='http://www.ehcache.org/v3/multi'>" +
      "<configuration identity='foo'>" +
        "<variant type='bar'><config xmlns='http://www.ehcache.org/v3'/></variant>" +
        "<variant type='baz'><config xmlns='http://www.ehcache.org/v3'/></variant>" +
      "</configuration>" +
    "</configurations>").ignoreWhitespace().ignoreComments());
}
 
Example #6
Source File: EhcacheCachingProvider.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private Eh107CacheManager createCacheManager(URI uri, Configuration config, Properties properties) {
  Collection<ServiceCreationConfiguration<?, ?>> serviceCreationConfigurations = config.getServiceCreationConfigurations();

  Jsr107Service jsr107Service = new DefaultJsr107Service(ServiceUtils.findSingletonAmongst(Jsr107Configuration.class, serviceCreationConfigurations));
  Eh107CacheLoaderWriterProvider cacheLoaderWriterFactory = new Eh107CacheLoaderWriterProvider();
  @SuppressWarnings("unchecked")
  DefaultSerializationProviderConfiguration serializerConfiguration = new DefaultSerializationProviderConfiguration().addSerializerFor(Object.class, (Class) PlainJavaSerializer.class);

  UnaryOperator<ServiceLocator.DependencySet> customization = dependencies -> {
    ServiceLocator.DependencySet d = dependencies.with(jsr107Service).with(cacheLoaderWriterFactory);
    if (ServiceUtils.findSingletonAmongst(DefaultSerializationProviderConfiguration.class, serviceCreationConfigurations) == null) {
      d = d.with(serializerConfiguration);
    }
    return d;
  };

  org.ehcache.CacheManager ehcacheManager = new EhcacheManager(config, customization, !jsr107Service.jsr107CompliantAtomics());
  ehcacheManager.init();

  return new Eh107CacheManager(this, ehcacheManager, jsr107Service, properties, config.getClassLoader(), uri,
          new ConfigurationMerger(config, jsr107Service, cacheLoaderWriterFactory));
}
 
Example #7
Source File: BasicXML.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  LOGGER.info("Creating cache manager via XML resource");
  Configuration xmlConfig = new XmlConfiguration(BasicXML.class.getResource("/ehcache.xml"));
  try (CacheManager cacheManager = newCacheManager(xmlConfig)) {
    cacheManager.init();

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

    LOGGER.info("Putting to cache");
    basicCache.put(1L, "da one!");
    String value = basicCache.get(1L);
    LOGGER.info("Retrieved '{}'", value);

    LOGGER.info("Closing cache manager");
  }

  LOGGER.info("Exiting");
}
 
Example #8
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void withCustomClassLoader() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  ClassLoader classLoader = MockitoUtil.mock(ClassLoader.class);

  // tag::customClassLoader[]
  Configuration withClassLoader = configuration.derive()
    .withClassLoader(classLoader)
    .build();
  // end::customClassLoader[]

  Assert.assertThat(configuration.getClassLoader(), Is.is(IsSame.sameInstance(ClassLoading.getDefaultClassLoader())));
  Assert.assertThat(withClassLoader.getClassLoader(), Is.is(IsSame.sameInstance(classLoader)));
}
 
Example #9
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateCache() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::updateCache[]
  Configuration withOffHeap = configuration.derive()
    .updateCache("cache", cache -> cache.updateResourcePools(
      resources -> ResourcePoolsBuilder.newResourcePoolsBuilder(resources)
        .offheap(100, MemoryUnit.MB)
        .build()))
    .build();
  //end::updateCache[]

  Assert.assertThat(configuration.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP));
  Assert.assertThat(withOffHeap.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP));
}
 
Example #10
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void withService() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::withService[]
  Configuration withThrowingStrategy = configuration.derive()
    .updateCache("cache", existing -> existing.withService(
      new DefaultResilienceStrategyConfiguration(new ThrowingResilienceStrategy<>())
    ))
    .build();
  //end::withService[]


  Assert.assertThat(configuration.getServiceCreationConfigurations(), IsNot.not(IsCollectionContaining.hasItem(
    IsInstanceOf.instanceOf(DefaultResilienceStrategyConfiguration.class))));

  DefaultResilienceStrategyConfiguration resilienceStrategyConfiguration =
    ServiceUtils.findSingletonAmongst(DefaultResilienceStrategyConfiguration.class,
      withThrowingStrategy.getCacheConfigurations().get("cache").getServiceConfigurations());
  Assert.assertThat(resilienceStrategyConfiguration.getInstance(), IsInstanceOf.instanceOf(ThrowingResilienceStrategy.class));
}
 
Example #11
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 #12
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void withServiceCreation() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::withServiceCreation[]
  Configuration withBoundedThreads = configuration.derive()
    .withService(new PooledExecutionServiceConfiguration()
      .addDefaultPool("default", 1, 16))
    .build();
  //end::withServiceCreation[]

  Assert.assertThat(configuration.getServiceCreationConfigurations(), IsNot.not(IsCollectionContaining.hasItem(IsInstanceOf.instanceOf(PooledExecutionServiceConfiguration.class))));
  PooledExecutionServiceConfiguration serviceCreationConfiguration = ServiceUtils.findSingletonAmongst(PooledExecutionServiceConfiguration.class, withBoundedThreads.getServiceCreationConfigurations());
  Assert.assertThat(serviceCreationConfiguration.getDefaultPoolAlias(), Is.is("default"));
  Assert.assertThat(serviceCreationConfiguration.getPoolConfigurations().keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder("default"));
  PooledExecutionServiceConfiguration.PoolConfiguration pool = serviceCreationConfiguration.getPoolConfigurations().get("default");
  Assert.assertThat(pool.minSize(), Is.is(1));
  Assert.assertThat(pool.maxSize(), Is.is(16));
}
 
Example #13
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleConfigurations() {
  //tag::multipleManagers[]
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml")) // <1>
    .build(); // <2>

  Configuration fooConfiguration = multipleConfiguration.configuration("foo-manager"); // <3>
  //end::multipleManagers[]

  Assert.assertThat(resourceMap(multipleConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), multipleConfiguration::configuration)
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));
}
 
Example #14
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateService() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
      .withService(new ClusteredStoreConfiguration(Consistency.STRONG)))
    .build();

  //tag::updateService[]
  Configuration changedConsistency = configuration.derive()
    .updateCache("cache", cache -> cache.updateServices(
      ClusteredStoreConfiguration.class,
      existing -> Consistency.EVENTUAL)
    )
    .build();
  //end::updateService[]

  Assert.assertThat(ServiceUtils.findSingletonAmongst(ClusteredStoreConfiguration.class,
    configuration.getCacheConfigurations().get("cache").getServiceConfigurations()).getConsistency(), Is.is(Consistency.STRONG));

  Assert.assertThat(ServiceUtils.findSingletonAmongst(ClusteredStoreConfiguration.class,
    changedConsistency.getCacheConfigurations().get("cache").getServiceConfigurations()).getConsistency(), Is.is(Consistency.EVENTUAL));
}
 
Example #15
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 #16
Source File: PooledExecutionServiceConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException {
  Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/thread-pools.xml"));

  assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1);

  ServiceCreationConfiguration<?, ?> configuration = xmlConfig.getServiceCreationConfigurations().iterator().next();
  assertThat(configuration).isExactlyInstanceOf(PooledExecutionServiceConfiguration.class);

  PooledExecutionServiceConfiguration providerConfiguration = (PooledExecutionServiceConfiguration) configuration;
  assertThat(providerConfiguration.getPoolConfigurations()).containsKeys("big", "small");

  PooledExecutionServiceConfiguration.PoolConfiguration small = providerConfiguration.getPoolConfigurations().get("small");
  assertThat(small.minSize()).isEqualTo(1);
  assertThat(small.maxSize()).isEqualTo(1);

  PooledExecutionServiceConfiguration.PoolConfiguration big = providerConfiguration.getPoolConfigurations().get("big");
  assertThat(big.minSize()).isEqualTo(4);
  assertThat(big.maxSize()).isEqualTo(32);

  assertThat(providerConfiguration.getDefaultPoolAlias()).isEqualTo("big");
}
 
Example #17
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrettyTypeNames() {
  URL resource = XmlConfigurationTest.class.getResource("/configs/pretty-typed-caches.xml");
  Configuration config = new XmlConfiguration(new XmlConfiguration(resource));

  CacheConfiguration<?, ?> byteArray = config.getCacheConfigurations().get("byte-array");
  assertThat(byteArray.getValueType(), equalTo(byte[].class));

  CacheConfiguration<?, ?> stringArray = config.getCacheConfigurations().get("string-array");
  assertThat(stringArray.getValueType(), equalTo(String[].class));

  CacheConfiguration<?, ?> string2dArray = config.getCacheConfigurations().get("string-2d-array");
  assertThat(string2dArray.getValueType(), equalTo(String[][].class));

  CacheConfiguration<?, ?> mapEntry = config.getCacheConfigurations().get("map-entry");
  assertThat(mapEntry.getValueType(), equalTo(Map.Entry.class));
}
 
Example #18
Source File: PooledExecutionServiceConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void unparseServiceCreationConfiguration() {
  PooledExecutionServiceConfiguration providerConfig = new PooledExecutionServiceConfiguration();
  providerConfig.addDefaultPool("foo", 5, 9);
  providerConfig.addPool("bar", 2, 6);

  Configuration config = ConfigurationBuilder.newConfigurationBuilder().withService(providerConfig).build();
  ConfigType configType = new ConfigType();
  configType = new PooledExecutionServiceConfigurationParser().unparseServiceCreationConfiguration(config, configType);

  List<ThreadPoolsType.ThreadPool> threadPools = configType.getThreadPools().getThreadPool();
  assertThat(threadPools).hasSize(2);
  threadPools.forEach(pool -> {
    if (pool.getAlias().equals("foo")) {
      assertThat(pool.getMinSize()).isEqualTo(5);
      assertThat(pool.getMaxSize()).isEqualTo(9);
      assertThat(pool.isDefault()).isEqualTo(true);
    } else if (pool.getAlias().equals("bar")) {
      assertThat(pool.getMinSize()).isEqualTo(2);
      assertThat(pool.getMaxSize()).isEqualTo(6);
      assertThat(pool.isDefault()).isEqualTo(false);
    } else {
      throw new AssertionError("Not expected");
    }
  });
}
 
Example #19
Source File: DefaultSerializationProviderConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test @SuppressWarnings("unchecked")
public void unparseServiceCreationConfiguration() {
  DefaultSerializationProviderConfiguration providerConfig = new DefaultSerializationProviderConfiguration();
  providerConfig.addSerializerFor(Description.class, (Class) TestSerializer3.class);
  providerConfig.addSerializerFor(Person.class, (Class) TestSerializer4.class);

  Configuration config = ConfigurationBuilder.newConfigurationBuilder().withService(providerConfig).build();
  ConfigType configType = new DefaultSerializationProviderConfigurationParser().unparseServiceCreationConfiguration(config, new ConfigType());

  List<SerializerType.Serializer> serializers = configType.getDefaultSerializers().getSerializer();
  assertThat(serializers).hasSize(2);
  serializers.forEach(serializer -> {
    if (serializer.getType().equals(Description.class.getName())) {
      assertThat(serializer.getValue()).isEqualTo(TestSerializer3.class.getName());
    } else if (serializer.getType().equals(Person.class.getName())) {
      assertThat(serializer.getValue()).isEqualTo(TestSerializer4.class.getName());
    } else {
      throw new AssertionError("Not expected");
    }
  });
}
 
Example #20
Source File: DefaultCopyProviderConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException {
  Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/cache-copiers.xml"));

  assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1);

  ServiceCreationConfiguration<?, ?> configuration = xmlConfig.getServiceCreationConfigurations().iterator().next();

  assertThat(configuration).isExactlyInstanceOf(DefaultCopyProviderConfiguration.class);

  DefaultCopyProviderConfiguration factoryConfiguration = (DefaultCopyProviderConfiguration) configuration;
  Map<Class<?>, DefaultCopierConfiguration<?>> defaults = factoryConfiguration.getDefaults();
  assertThat(defaults).hasSize(2);
  assertThat(defaults.get(Description.class).getClazz()).isEqualTo(DescriptionCopier.class);
  assertThat(defaults.get(Person.class).getClazz()).isEqualTo((PersonCopier.class));
}
 
Example #21
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleRetrieval() {
  XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-managers.xml"))
    .build();
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  //tag::multipleRetrieval[]
  Map<String, Configuration> allConfigurations = multipleConfiguration.identities().stream() // <1>
    .collect(Collectors.toMap(i -> i, i -> multipleConfiguration.configuration(i))); // <2>
  Map<String, Configuration> offheapConfigurations = variantConfiguration.identities().stream()
    .collect(Collectors.toMap(i -> i, i -> variantConfiguration.configuration(i, "offheap"))); // <3>
  //end::multipleRetrieval[]

  Assert.assertThat(resourceMap(allConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP)))
  ));

  Assert.assertThat(resourceMap(offheapConfigurations), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #22
Source File: MultiGettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleVariants() {
  //tag::multipleVariants[]
  XmlMultiConfiguration variantConfiguration = XmlMultiConfiguration
    .from(getClass().getResource("/configs/docs/multi/multiple-variants.xml"))
    .build();

  Configuration fooConfiguration = variantConfiguration.configuration("foo-manager", "offheap"); // <1>
  //end::multipleVariants[]

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "offheap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));

  Assert.assertThat(resourceMap(variantConfiguration.identities().stream().collect(
    Collectors.toMap(Function.identity(), i -> variantConfiguration.configuration(i, "heap"))
  )), AllOf.allOf(
    IsMapContaining.hasEntry(Is.is("foo-manager"), IsMapContaining.hasEntry(Is.is("foo"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP))),
    IsMapContaining.hasEntry(Is.is("bar-manager"), IsMapContaining.hasEntry(Is.is("bar"), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP)))
  ));
}
 
Example #23
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testXmlToString() throws IOException {
  // tag::xmlTranslation[]
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(CacheManagerBuilder.persistence(tmpDir.newFile("myData")))
    .withCache("threeTieredCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(20, MemoryUnit.MB, true))
        .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(20)))
    ).build(false);

  Configuration configuration = cacheManager.getRuntimeConfiguration();
  XmlConfiguration xmlConfiguration = new XmlConfiguration(configuration);  // <1>
  String xml = xmlConfiguration.toString(); // <2>
  // end::xmlTranslation[]
}
 
Example #24
Source File: CacheEventDispatcherFactoryConfigurationParserTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException {
  Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/ehcache-cacheEventListener.xml"));

  assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1);

  ServiceCreationConfiguration<?, ?> configuration = xmlConfig.getServiceCreationConfigurations().iterator().next();
  assertThat(configuration).isInstanceOf(CacheEventDispatcherFactoryConfiguration.class);

  CacheEventDispatcherFactoryConfiguration providerConfiguration = (CacheEventDispatcherFactoryConfiguration) configuration;
  assertThat(providerConfiguration.getThreadPoolAlias()).isEqualTo("events-pool");
}
 
Example #25
Source File: CacheEventDispatcherFactoryConfigurationParserTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void unparseServiceCreationConfiguration() {
  Configuration config = ConfigurationBuilder.newConfigurationBuilder()
    .withService(new CacheEventDispatcherFactoryConfiguration("foo")).build();
  ConfigType configType = new CacheEventDispatcherFactoryConfigurationParser().unparseServiceCreationConfiguration(config, new ConfigType());

  assertThat(configType.getEventDispatch().getThreadPool()).isEqualTo("foo");
}
 
Example #26
Source File: CoreConfigurationBuilderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithClassLoader() {
  ClassLoader classLoader = mock(ClassLoader.class);

  Configuration configuration = new CoreConfigurationBuilder<>()
    .withClassLoader(classLoader)
    .build();

  assertThat(configuration.getClassLoader(), sameInstance(classLoader));
}
 
Example #27
Source File: DefaultConfiguration.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Copy constructor
 *
 * @param cfg the configuration to copy
 */
public DefaultConfiguration(Configuration cfg) {
  if (cfg.getClassLoader() == null) {
    throw new NullPointerException();
  }
  this.caches = new ConcurrentHashMap<>(cfg.getCacheConfigurations());
  this.services = unmodifiableCollection(cfg.getServiceCreationConfigurations());
  this.classLoader = cfg.getClassLoader();
}
 
Example #28
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 #29
Source File: OffHeapDiskStoreProviderConfigurationParserTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void unparseServiceCreationConfiguration() {
  ConfigType configType = new ConfigType();
  Configuration config = ConfigurationBuilder.newConfigurationBuilder()
    .withService(new OffHeapDiskStoreProviderConfiguration("foo")).build();
  configType = new OffHeapDiskStoreProviderConfigurationParser().unparseServiceCreationConfiguration(config, configType);

  assertThat(configType.getDiskStore().getThreadPool()).isEqualTo("foo");
}
 
Example #30
Source File: XmlConfigTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTemplateConfigOverride() throws Exception {
  final URL myUrl = this.getClass().getResource("/configs/template-xa.xml");
  Configuration xmlConfig = new XmlConfiguration(myUrl);
  CacheConfiguration<?, ?> cacheConfiguration = xmlConfig.getCacheConfigurations().get("xaCache1");
  XAStoreConfiguration xaStoreConfiguration = ServiceUtils.findSingletonAmongst(XAStoreConfiguration.class, cacheConfiguration
      .getServiceConfigurations());

  assertThat(xaStoreConfiguration.getUniqueXAResourceId(), is("xaCache1"));
}