Java Code Examples for org.ehcache.config.builders.CacheConfigurationBuilder#build()

The following examples show how to use org.ehcache.config.builders.CacheConfigurationBuilder#build() . 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: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutAll_without_cache_writer() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

  HashMap<String, String> stringStringHashMap = new HashMap<>();
  for (int i = 0; i < 3; i++) {
    stringStringHashMap.put("key" + i, "value" + i);
  }

  // the call to putAll
  myCache.putAll(stringStringHashMap);

  for (int i = 0; i < 3; i++) {
    assertThat(myCache.get("key" + i), is("value" + i));
  }

}
 
Example 2
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
  public void testPutAll_store_throws_cache_exception() throws Exception {
    CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
        heap(100));
    CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder
        .build();


    CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
    CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
    doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriter).write(ArgumentMatchers.any(), ArgumentMatchers.any());
    when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);

    CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider).using(new CustomStoreProvider());
    CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

    Map<String, String> stringStringHashMap = new HashMap<>();
    for (int i = 0; i < 3; i++) {
      stringStringHashMap.put("key" + i, "value" + i);
    }

    // the call to putAll
    myCache.putAll(stringStringHashMap);

    for (int i = 0; i < 3; i++) {
      // the store threw an exception when we call bulkCompute
      assertThat(myCache.get("key" + i), is(nullValue()));
      // but still, the cache writer could writeAll the values !
//      assertThat(cacheWriterToHashMapMap.get("key" + i), is("value" + i));
    }
    // but still, the cache writer could writeAll the values at once !
    verify(cacheLoaderWriter, times(1)).writeAll(ArgumentMatchers.any(Iterable.class));
    Set set = new HashSet() {{add(entry("key0", "value0")); add(entry("key1", "value1")); add(entry("key2", "value2"));}};
    verify(cacheLoaderWriter).writeAll(set);
  }
 
Example 3
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll_without_cache_loader() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };
  // the call to getAll
  Map<String, String> fewEntries = myCache.getAll(fewKeysSet);

  assertThat(fewEntries.size(), is(2));
  assertThat(fewEntries.get("key0"), is("value0"));
  assertThat(fewEntries.get("key2"), is("value2"));

}
 
Example 4
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll_store_throws_cache_exception() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriter.load(ArgumentMatchers.any())).thenThrow(new RuntimeException("We should not have called .load() but .loadAll()"));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);
  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider).using(new CustomStoreProvider());
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  when(cacheLoaderWriter.loadAll(argThat(hasItems("key0", "key2")))).thenReturn( new HashMap(){{put("key0","value0");  put("key2","value2");}});

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

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };

  // the call to getAll
  Map<String, String> fewEntries = myCache.getAll(fewKeysSet);

  assertThat(fewEntries.size(), is(2));
  assertThat(fewEntries.get("key0"), is("value0"));
  assertThat(fewEntries.get("key2"), is("value2"));

}
 
Example 5
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAll_without_cache_writer() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };
  // the call to removeAll
  myCache.removeAll(fewKeysSet);

  for (int i = 0; i < 3; i++) {
    if (i == 0 || i == 2) {
      assertThat(myCache.get("key" + i), is(nullValue()));
    } else {
      assertThat(myCache.get("key" + i), is("value" + i));
    }
  }

}
 
Example 6
Source File: ZTSClientCache.java    From athenz with Apache License 2.0 4 votes vote down vote up
/**
 * Prepare an ehcache CacheConfiguration from one &lt;ehcache:cache&gt; element in the config xml file.
 * Returns a function that should be executed after cacheManagerBuilder is fully initialized, and cacheManager is built.
 */
private <K, V> Runnable prepareCache(
        String cacheName,
        Class<K> keyClass,
        Class<V> valueClass,
        Class<? extends CopierAndSerializer<K>> keyCopierAndSerializerClass,
        Class<? extends CopierAndSerializer<V>> valueCopierAndSerializerClass,
        Consumer<Cache<K, V>> cacheIsReady) {

    // Get our cache's configuration from the config file, and apply the value-serializer.
    CacheConfiguration<K, V> cacheConfiguration;
    try {
        CacheConfigurationBuilder<K, V> configurationBuilder = xmlConfiguration.newCacheConfigurationBuilderFromTemplate(cacheName, keyClass, valueClass);
        if (configurationBuilder == null) {
            LOG.info("ZTSClient \"{}\" cache is disabled: system-property \"{}\" references the file \"{}\" - which has errors in the <ehcache:cache alias=\"{}\"> element.", cacheName, ZTS_CLIENT_PROP_EHCACHE_XML_PATH_ROLE_ACCESS, ehcacheConfigXmlFile.getAbsoluteFile(), cacheName);
            return null;
        }
        if (keyCopierAndSerializerClass != null) {
            configurationBuilder = configurationBuilder
                    .withKeySerializer(keyCopierAndSerializerClass)
                    .withKeyCopier(keyCopierAndSerializerClass);
        }
        if (valueCopierAndSerializerClass != null) {
            configurationBuilder = configurationBuilder
                    .withValueSerializer(valueCopierAndSerializerClass)
                    .withValueCopier(valueCopierAndSerializerClass);
        }
        cacheConfiguration = configurationBuilder.build();
    } catch (Exception exception) {
        LOG.info("ZTSClient \"{}\" cache is disabled: system-property \"{}\" references the file \"{}\" - which has errors in the <ehcache:cache alias=\"{}\"> element: ", cacheName, ZTS_CLIENT_PROP_EHCACHE_XML_PATH_ROLE_ACCESS, ehcacheConfigXmlFile.getAbsoluteFile(), cacheName, exception);
        return null;
    }

    // Store this cache's configuration - so it is available to the to-be-built cacheManager.
    cacheManagerBuilder = cacheManagerBuilder.withCache(cacheName, cacheConfiguration);

    // This will be executed after cacheManagerBuilder is fully initialized, and cacheManager is built.
    return () -> {
        Cache<K, V> cache = cacheManager.getCache(cacheName, keyClass, valueClass);
        if (cache == null) {
            LOG.info("ZTSClient \"{}\" cache is disabled: system-property \"{}\" references the file \"{}\" - which has errors in the <ehcache:cache alias=\"{}\"> element: unknown error", cacheName, ZTS_CLIENT_PROP_EHCACHE_XML_PATH_ROLE_ACCESS, ehcacheConfigXmlFile.getAbsoluteFile(), cacheName);
        } else {
            LOG.info("ZTSClient \"{}\" cache is enabled", cacheName);
            cacheIsReady.accept(cache);
        }
    };
}
 
Example 7
Source File: EhCachePoolMixin.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
private <T> EhCacheImpl<T> createNewCache( String cacheId, Class<T> valueType )
{
    configuration.refresh();
    EhCacheConfiguration config = configuration.get();

    ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();

    poolsBuilder = poolsBuilder.heap( config.heapSize().get(), MemoryUnit.valueOf( config.heapUnit().get() ) );

    if( config.offHeapSize().get() != null )
    {
        poolsBuilder = poolsBuilder.offheap( config.offHeapSize().get(),
                                             MemoryUnit.valueOf( config.offHeapUnit().get() ) );
    }
    if( config.diskSize().get() != null )
    {
        poolsBuilder = poolsBuilder.disk( config.diskSize().get(),
                                          MemoryUnit.valueOf( config.diskUnit().get() ),
                                          config.diskPersistent().get() );
    }

    CacheConfigurationBuilder<String, T> configBuilder = CacheConfigurationBuilder
        .newCacheConfigurationBuilder( String.class, valueType, poolsBuilder );
    if( config.maxObjectSize().get() != null )
    {
        configBuilder = configBuilder.withSizeOfMaxObjectSize( config.maxObjectSize().get(),
                                                               MemoryUnit.valueOf( config.maxObjectSizeUnit().get() ) );
    }
    if( config.maxObjectGraphDepth().get() != null )
    {
        configBuilder = configBuilder.withSizeOfMaxObjectGraph( config.maxObjectGraphDepth().get() );
    }
    switch( config.expiry().get() )
    {
        case "TIME_TO_IDLE":
            configBuilder = configBuilder.withExpiry( timeToIdleExpiration( Duration.of(
                config.expiryLength().get() == null ? - 1L : config.expiryLength().get(),
                TimeUnit.valueOf( config.expiryTimeUnit().get() ) ) ) );
            break;
        case "TIME_TO_LIVE":
            configBuilder = configBuilder.withExpiry( timeToLiveExpiration( Duration.of(
                config.expiryLength().get() == null ? - 1L : config.expiryLength().get(),
                TimeUnit.valueOf( config.expiryTimeUnit().get() ) ) ) );
            break;
        case "NONE":
        default:
            configBuilder = configBuilder.withExpiry( noExpiration() );
            break;
    }
    CacheConfiguration<String, T> cacheConfig = configBuilder.build();
    org.ehcache.Cache<String, T> cache = cacheManager.createCache( cacheId, cacheConfig );
    return new EhCacheImpl<>( cacheId, cache, valueType );
}
 
Example 8
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveAll_with_store_that_throws() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder
      .build();

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriter);

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider).using(new CustomStoreProvider());
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriter).write(ArgumentMatchers
      .any(), ArgumentMatchers.any());

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };

  // the call to removeAll
  myCache.removeAll(fewKeysSet);
  for (int i = 0; i < 3; i++) {
    if (i == 0 || i == 2) {
      assertThat(myCache.get("key" + i), is(nullValue()));

    } else {
      assertThat(myCache.get("key" + i), is("value" + i));
    }
  }

  Set set = new HashSet(){{add("key0"); add("key2");}};
  verify(cacheLoaderWriter).deleteAll(set);

}
 
Example 9
Source File: ConfigurationMerger.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
<K, V> ConfigHolder<K, V> mergeConfigurations(String cacheName, Configuration<K, V> configuration) {
  final Eh107CompleteConfiguration<K, V> jsr107Configuration = new Eh107CompleteConfiguration<>(configuration);

  Eh107Expiry<K, V> expiryPolicy = null;
  Jsr107CacheLoaderWriter<? super K, V> loaderWriter = null;
  try {
    CacheConfigurationBuilder<K, V> builder = newCacheConfigurationBuilder(configuration.getKeyType(), configuration.getValueType(), heap(Long.MAX_VALUE));

    String templateName = jsr107Service.getTemplateNameForCache(cacheName);
    if (xmlConfiguration != null && templateName != null) {
      CacheConfigurationBuilder<K, V> templateBuilder;
      try {
        templateBuilder = xmlConfiguration.newCacheConfigurationBuilderFromTemplate(templateName,
            jsr107Configuration.getKeyType(), jsr107Configuration.getValueType());
      } catch (IllegalStateException e) {
        templateBuilder = xmlConfiguration.newCacheConfigurationBuilderFromTemplate(templateName,
                      jsr107Configuration.getKeyType(), jsr107Configuration.getValueType(), heap(Long.MAX_VALUE));
      }
      if (templateBuilder != null) {
        builder = templateBuilder;
        LOG.info("Configuration of cache {} will be supplemented by template {}", cacheName, templateName);
      }
    }

    builder = handleStoreByValue(jsr107Configuration, builder, cacheName);

    final boolean hasConfiguredExpiry = builder.hasConfiguredExpiry();
    if (hasConfiguredExpiry) {
      LOG.info("Cache {} will use expiry configuration from template {}", cacheName, templateName);
    } else {
      expiryPolicy = initExpiryPolicy(jsr107Configuration);
      builder = builder.withExpiry(expiryPolicy);
    }

    boolean useEhcacheLoaderWriter;
    CacheLoaderWriterConfiguration<?> ehcacheLoaderWriterConfiguration = builder.getService(DefaultCacheLoaderWriterConfiguration.class);
    if (ehcacheLoaderWriterConfiguration == null) {
      useEhcacheLoaderWriter = false;
      // No template loader/writer - let's activate the JSR-107 one if any
      loaderWriter = initCacheLoaderWriter(jsr107Configuration);
      if (loaderWriter != null && (jsr107Configuration.isReadThrough() || jsr107Configuration.isWriteThrough())) {
        cacheLoaderWriterFactory.registerJsr107Loader(cacheName, loaderWriter);
      }
    } else {
      useEhcacheLoaderWriter = true;
      if (!jsr107Configuration.isReadThrough() && !jsr107Configuration.isWriteThrough()) {
        LOG.warn("Activating Ehcache loader/writer for JSR-107 cache {} which was neither read-through nor write-through", cacheName);
      }
      LOG.info("Cache {} will use loader/writer configuration from template {}", cacheName, templateName);
    }

    CacheConfiguration<K, V> cacheConfiguration = builder.build();

    setupManagementAndStatsInternal(jsr107Configuration, findSingletonAmongst(Jsr107CacheConfiguration.class, cacheConfiguration.getServiceConfigurations()));

    if (hasConfiguredExpiry) {
      expiryPolicy = new EhcacheExpiryWrapper<>(cacheConfiguration.getExpiryPolicy());
    }

    return new ConfigHolder<>(
      new CacheResources<>(cacheName, loaderWriter, expiryPolicy, initCacheEventListeners(jsr107Configuration)),
      new Eh107CompleteConfiguration<>(jsr107Configuration, cacheConfiguration, hasConfiguredExpiry, useEhcacheLoaderWriter),
      cacheConfiguration, useEhcacheLoaderWriter);
  } catch (Throwable throwable) {
    if (throwable instanceof IllegalArgumentException) {
      throw closeAllAfter((IllegalArgumentException) throwable, expiryPolicy, loaderWriter);
    } else {
      throw closeAllAfter(new CacheException(throwable), expiryPolicy, loaderWriter);
    }
  }
}