org.ehcache.spi.loaderwriter.CacheLoaderWriter Java Examples

The following examples show how to use org.ehcache.spi.loaderwriter.CacheLoaderWriter. 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: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchedOverwrittenKeyReturnsNewValue() throws Exception {
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  when(loaderWriter.load("key")).thenReturn("value");
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testBatchedOverwrittenKeyReturnsNewValue", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 2).build())
      .build());

    assertThat(testCache.get("key"), is("value"));

    testCache.put("key", "value2");

    assertThat(testCache.get("key"), is("value2"));
  }
}
 
Example #2
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchedDeletedKeyReturnsNull() throws Exception {
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  when(loaderWriter.load("key")).thenReturn("value");
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testBatchedDeletedKeyReturnsNull", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 2).build())
      .build());

    assertThat(testCache.get("key"), is("value"));

    testCache.remove("key");

    assertThat(testCache.get("key"), nullValue());
  }
}
 
Example #3
Source File: BatchingLocalHeapWriteBehindQueue.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public BatchingLocalHeapWriteBehindQueue(ExecutionService executionService, String defaultThreadPool, WriteBehindConfiguration<?> config, CacheLoaderWriter<K, V> cacheLoaderWriter) {
  super(cacheLoaderWriter);
  this.cacheLoaderWriter = cacheLoaderWriter;
  BatchingConfiguration batchingConfig = config.getBatchingConfiguration();
  this.maxWriteDelayMs = batchingConfig.getMaxDelayUnit().toMillis(batchingConfig.getMaxDelay());
  this.batchSize = batchingConfig.getBatchSize();
  this.coalescing = batchingConfig.isCoalescing();
  this.executorQueue = new LinkedBlockingQueue<>(config.getMaxQueueSize() / batchSize);
  if (config.getThreadPoolAlias() == null) {
    this.executor = executionService.getOrderedExecutor(defaultThreadPool, executorQueue);
  } else {
    this.executor = executionService.getOrderedExecutor(config.getThreadPoolAlias(), executorQueue);
  }
  if (config.getThreadPoolAlias() == null) {
    this.scheduledExecutor = executionService.getScheduledExecutor(defaultThreadPool);
  } else {
    this.scheduledExecutor = executionService.getScheduledExecutor(config.getThreadPoolAlias());
  }
}
 
Example #4
Source File: ClusteredLoaderWriterStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * For Tests
 */
ClusteredLoaderWriterStore(Configuration<K, V> config, OperationsCodec<K, V> codec, EternalChainResolver<K, V> resolver,
                           ServerStoreProxy proxy, TimeSource timeSource, CacheLoaderWriter<? super K, V> loaderWriter, StatisticsService statisticsService) {
  super(config, codec, resolver, proxy, timeSource, null, statisticsService);
  this.cacheLoaderWriter = loaderWriter;
  this.useLoaderInAtomics = true;
}
 
Example #5
Source File: Eh107CacheLoaderWriterProvider.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <K, V> CacheLoaderWriter<? super K, V> createCacheLoaderWriter(String alias,
    org.ehcache.config.CacheConfiguration<K, V> cacheConfiguration) {
  CacheLoaderWriter<?, ?> cacheLoaderWriter = cacheLoaderWriters.remove(alias);
  if (cacheLoaderWriter == null) {
    return super.createCacheLoaderWriter(alias, cacheConfiguration);
  }

  return (CacheLoaderWriter<? super K, V>)cacheLoaderWriter;
}
 
Example #6
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAll_with_cache_loader() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));

  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);
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriter).build();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  when(cacheLoaderWriter.loadAll(argThat(IsCollectionContaining.<String>hasItem("key0")))).thenReturn(new HashMap(){{put("key0","value0");}});
  when(cacheLoaderWriter.loadAll(argThat(IsCollectionContaining.<String>hasItem("key2")))).thenReturn(new HashMap(){{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 #7
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 #8
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 #9
Source File: Eh107CacheLoaderWriterProvider.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
<K, V> void registerJsr107Loader(String alias, CacheLoaderWriter<K, V> cacheLoaderWriter) {
  CacheLoaderWriter<?, ?> prev = cacheLoaderWriters.putIfAbsent(alias, cacheLoaderWriter);
  registerJsrLoaderForCache(alias);
  if (prev != null) {
    throw new IllegalStateException("loader already registered for [" + alias + "]");
  }
}
 
Example #10
Source File: ConfigurationMergerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void jsr107WriterGetsRegistered() {
  MutableConfiguration<Object, Object> configuration = new MutableConfiguration<>();
  CacheWriter<Object, Object> mock = mock(CacheWriter.class);
  RecordingFactory<CacheWriter<Object, Object>> factory = factoryOf(mock);
  configuration.setWriteThrough(true).setCacheWriterFactory(factory);

  merger.mergeConfigurations("cache", configuration);

  assertThat(factory.called, is(true));
  verify(cacheLoaderWriterFactory).registerJsr107Loader(eq("cache"), ArgumentMatchers.<CacheLoaderWriter<Object, Object>>isNotNull());
}
 
Example #11
Source File: XAGettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testXACacheWithWriteThrough() throws Exception {
  // tag::testXACacheWithWriteThrough[]
  BitronixTransactionManager transactionManager =
      TransactionManagerServices.getTransactionManager(); // <1>

  Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (SampleLoaderWriter.class);

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class)) // <2>
      .withCache("xaCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, // <3>
                                                          ResourcePoolsBuilder.heap(10)) // <4>
              .withService(new XAStoreConfiguration("xaCache")) // <5>
              .withService(new DefaultCacheLoaderWriterConfiguration(klazz, singletonMap(1L, "eins"))) // <6>
              .build()
      )
      .build(true);

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

  transactionManager.begin(); // <7>
  {
    assertThat(xaCache.get(1L), equalTo("eins")); // <8>
    xaCache.put(1L, "one"); // <9>
  }
  transactionManager.commit(); // <10>

  cacheManager.close();
  transactionManager.shutdown();
  // end::testXACacheWithWriteThrough[]
}
 
Example #12
Source File: UserManagedCacheBuilder.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a {@link CacheLoaderWriter} to the returned builder.
 *
 * @param loaderWriter the cache loader writer to use
 * @return a new builder with the added cache loader writer
 */
public UserManagedCacheBuilder<K, V, T> withLoaderWriter(CacheLoaderWriter<K, V> loaderWriter) {
  if (loaderWriter == null) {
    throw new NullPointerException("Null loaderWriter");
  }
  UserManagedCacheBuilder<K, V, T> otherBuilder = new UserManagedCacheBuilder<>(this);
  otherBuilder.cacheLoaderWriter = loaderWriter;
  return otherBuilder;
}
 
Example #13
Source File: DefaultResilienceStrategyProvider.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <K, V> ResilienceStrategy<K, V> create(String alias, DefaultResilienceStrategyConfiguration config,
                                              RecoveryStore<K> recoveryStore, CacheLoaderWriter<? super K, V> loaderWriter) {
  if (config == null) {
    DefaultResilienceStrategyConfiguration preconfigured = getPreconfigured(alias);
    if (preconfigured == null) {
      return (ResilienceStrategy<K, V>) newInstance(alias, defaultConfiguration.bind(recoveryStore, loaderWriter));
    } else {
      return (ResilienceStrategy<K, V>) newInstance(alias, preconfigured.bind(recoveryStore, loaderWriter));
    }
  } else {
    return (ResilienceStrategy<K, V>) newInstance(alias, config.bind(recoveryStore, loaderWriter));
  }
}
 
Example #14
Source File: NonBatchingLocalHeapWriteBehindQueue.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public NonBatchingLocalHeapWriteBehindQueue(ExecutionService executionService, String defaultThreadPool, WriteBehindConfiguration<?> config, CacheLoaderWriter<K, V> cacheLoaderWriter) {
  super(cacheLoaderWriter);
  this.cacheLoaderWriter = cacheLoaderWriter;
  this.executorQueue = new LinkedBlockingQueue<>(config.getMaxQueueSize());
  if (config.getThreadPoolAlias() == null) {
    this.executor = executionService.getOrderedExecutor(defaultThreadPool, executorQueue);
  } else {
    this.executor = executionService.getOrderedExecutor(config.getThreadPoolAlias(), executorQueue);
  }
}
 
Example #15
Source File: UserManagedCacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserManagedCacheDelegatesLifecycleCallsToStore() throws Exception {
  final Store store = mock(Store.class);
  CacheConfiguration<Object, Object> config = mock(CacheConfiguration.class);
  Ehcache ehcache = new Ehcache(config, store, mock(ResilienceStrategy.class), mock(CacheEventDispatcher.class), LoggerFactory.getLogger(Ehcache.class + "testUserManagedCacheDelegatesLifecycleCallsToStore"));
  assertCacheDelegatesLifecycleCallsToStore(ehcache);

  Ehcache ehcacheWithLoaderWriter = new Ehcache(config, store, mock(ResilienceStrategy.class),
      mock(CacheEventDispatcher.class), LoggerFactory.getLogger(Ehcache.class + "testUserManagedCacheDelegatesLifecycleCallsToStore"),
          mock(CacheLoaderWriter.class));
  assertCacheDelegatesLifecycleCallsToStore(ehcacheWithLoaderWriter);
}
 
Example #16
Source File: ClusteredLoaderWriterStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemove2ArgsValuePresentInCachePresentInSOR() throws Exception {
  LockingServerStoreProxyImpl storeProxy = mock(LockingServerStoreProxyImpl.class);
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<Long, String> loaderWriter = mock(CacheLoaderWriter.class);
  PutOperation<Long, String> operation = new PutOperation<>(1L, "one", System.currentTimeMillis());
  ServerStoreProxy.ChainEntry toReturn = entryOf(codec.encode(operation));
  when(storeProxy.lock(anyLong())).thenReturn(toReturn);
  ClusteredLoaderWriterStore<Long, String> store = new ClusteredLoaderWriterStore<>(configuration, codec, resolver, storeProxy,
          timeSource, loaderWriter, new DefaultStatisticsService());
  assertThat(store.remove(1L, "one"), is(Store.RemoveStatus.REMOVED));
  verify(storeProxy, times(1)).append(anyLong(), ArgumentMatchers.any(ByteBuffer.class));
  verify(loaderWriter, times(0)).load(anyLong());
  verify(loaderWriter, times(1)).delete(anyLong());
}
 
Example #17
Source File: ClusteredLoaderWriterStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetValueAbsentInSOR() throws Exception {
  ServerStoreProxy storeProxy = mock(LockingServerStoreProxyImpl.class);
  CacheLoaderWriter<Long, String> loaderWriter = new TestCacheLoaderWriter();
  when(storeProxy.get(eq(1L))).thenReturn(entryOf());
  ClusteredLoaderWriterStore<Long, String> store = new ClusteredLoaderWriterStore<>(configuration, codec, resolver, storeProxy,
          timeSource, loaderWriter, new DefaultStatisticsService());
  assertThat(store.get(1L), is(nullValue()));
}
 
Example #18
Source File: WriteBehindProviderFactory.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> WriteBehind<K, V> createWriteBehindLoaderWriter(CacheLoaderWriter<K, V> cacheLoaderWriter, WriteBehindConfiguration<?> configuration) {
  if (cacheLoaderWriter == null) {
    throw new NullPointerException("WriteBehind requires a non null CacheLoaderWriter.");
  }
  return new StripedWriteBehind<>(executionService, threadPoolAlias, configuration, cacheLoaderWriter);
}
 
Example #19
Source File: DefaultCacheLoaderWriterConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeriveDetachesCorrectly() {
  CacheLoaderWriter<?, ?> mock = mock(CacheLoaderWriter.class);
  DefaultCacheLoaderWriterConfiguration configuration = new DefaultCacheLoaderWriterConfiguration(mock);
  DefaultCacheLoaderWriterConfiguration derived = configuration.build(configuration.derive());

  assertThat(derived, is(not(sameInstance(configuration))));
  assertThat(derived.getInstance(), sameInstance(configuration.getInstance()));
}
 
Example #20
Source File: DefaultCacheLoaderWriterProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddingCacheLoaderWriterConfigurationAtCacheLevel() {
  CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (MyLoader.class);
  CacheManager cacheManager = cacheManagerBuilder.build(true);
  final Cache<Long, String> cache = cacheManager.createCache("cache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(100))
          .withService(new DefaultCacheLoaderWriterConfiguration(klazz))
          .build());
  Collection<ServiceConfiguration<?, ?>> serviceConfiguration = cache.getRuntimeConfiguration()
      .getServiceConfigurations();
  assertThat(serviceConfiguration, IsCollectionContaining.<ServiceConfiguration<?, ?>>hasItem(instanceOf(DefaultCacheLoaderWriterConfiguration.class)));
  cacheManager.close();
}
 
Example #21
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreconfiguredLoaderWriterInstanceReturned() {
  ResilienceStrategy<?, ?> resilienceStrategy = mock(ResilienceStrategy.class);

  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  configuration.addResilienceStrategyFor("foo", resilienceStrategy);

  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  assertThat(provider.createResilienceStrategy("foo", mock(CacheConfiguration.class), mock(RecoveryStore.class), mock(CacheLoaderWriter.class)), sameInstance(resilienceStrategy));
}
 
Example #22
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreconfiguredLoaderWriterInstanceConstructed() {
  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  configuration.addResilienceStrategyFor("foo", TestResilienceStrategy.class, "FooBar");

  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  ResilienceStrategy<?, ?> resilienceStrategy = provider.createResilienceStrategy("foo", mock(CacheConfiguration.class), mock(RecoveryStore.class), mock(CacheLoaderWriter.class));
  assertThat(resilienceStrategy, instanceOf(TestResilienceStrategy.class));
  assertThat(((TestResilienceStrategy) resilienceStrategy).message, is("FooBar"));
}
 
Example #23
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvidedLoaderWriterInstanceReturned() {
  ResilienceStrategy<?, ?> resilienceStrategy = mock(ResilienceStrategy.class);

  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  CacheConfiguration<?, ?> cacheConfiguration = mock(CacheConfiguration.class);
  when(cacheConfiguration.getServiceConfigurations()).thenReturn(Collections.singleton(new DefaultResilienceStrategyConfiguration(resilienceStrategy)));

  assertThat(provider.createResilienceStrategy("foo", cacheConfiguration, mock(RecoveryStore.class), mock(CacheLoaderWriter.class)), sameInstance(resilienceStrategy));
}
 
Example #24
Source File: DefaultResilienceStrategyProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvidedLoaderWriterInstanceConstructed() {
  DefaultResilienceStrategyProviderConfiguration configuration = new DefaultResilienceStrategyProviderConfiguration();
  DefaultResilienceStrategyProvider provider = new DefaultResilienceStrategyProvider(configuration);

  CacheConfiguration<?, ?> cacheConfiguration = mock(CacheConfiguration.class);
  when(cacheConfiguration.getServiceConfigurations()).thenReturn(Collections.singleton(new DefaultResilienceStrategyConfiguration(TestResilienceStrategy.class, "FooBar")));

  ResilienceStrategy<?, ?> resilienceStrategy = provider.createResilienceStrategy("foo", cacheConfiguration, mock(RecoveryStore.class), mock(CacheLoaderWriter.class));
  assertThat(resilienceStrategy, instanceOf(TestResilienceStrategy.class));
  assertThat(((TestResilienceStrategy) resilienceStrategy).message, is("FooBar"));
}
 
Example #25
Source File: DefaultResilienceStrategyConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlreadyBoundConfigurationCannotBeBound() {
  DefaultResilienceStrategyConfiguration configuration = new DefaultResilienceStrategyConfiguration(RobustResilienceStrategy.class);
  RecoveryStore<?> recoveryStore = mock(RecoveryStore.class);
  CacheLoaderWriter<?, ?> loaderWriter = mock(CacheLoaderWriter.class);
  DefaultResilienceStrategyConfiguration bound = configuration.bind(recoveryStore, loaderWriter);

  try {
    bound.bind(recoveryStore);
    fail("Expected IllegalStateException");
  } catch (IllegalStateException e) {
    //expected
  }
}
 
Example #26
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnBatchedOverwrittenKeyReturnsNewValue() throws Exception {
  final Semaphore semaphore = new Semaphore(0);

  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  when(loaderWriter.load("key")).thenReturn("value");
  doAnswer(invocation -> {
    semaphore.acquire();
    return null;
  }).when(loaderWriter).delete("key");
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true);
  try {
    Cache<String, String> testCache = cacheManager.createCache("testUnBatchedOverwrittenKeyReturnsNewValue", configurationBuilder()
        .withLoaderWriter(loaderWriter)
        .withService(newUnBatchedWriteBehindConfiguration().build())
        .build());

    assertThat(testCache.get("key"), is("value"));

    testCache.remove("key");

    assertThat(testCache.get("key"), nullValue());
  } finally {
    semaphore.release();
    cacheManager.close();
  }
}
 
Example #27
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnBatchedWriteBehindBlocksWhenFull() throws Exception {
  final Semaphore gate = new Semaphore(0);
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  doAnswer(invocation -> {
    gate.acquire();
    return null;
  }).when(loaderWriter).write(anyString(), anyString());

  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    final Cache<String, String> testCache = cacheManager.createCache("testUnBatchedWriteBehindBlocksWhenFull", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newUnBatchedWriteBehindConfiguration().queueSize(1).build())
      .build());

    testCache.put("key1", "value");
    testCache.put("key2", "value");

    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
      Future<?> blockedPut = executor.submit(() -> testCache.put("key3", "value"));

      try {
        blockedPut.get(100, MILLISECONDS);
        fail("Expected TimeoutException");
      } catch (TimeoutException e) {
        //expected
      }
      gate.release();
      blockedPut.get(10, SECONDS);
      gate.release(Integer.MAX_VALUE);
    } finally {
      executor.shutdown();
    }
  }
}
 
Example #28
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBatchedWriteBehindBlocksWhenFull() throws Exception {
  final Semaphore gate = new Semaphore(0);
  CacheLoaderWriter<String, String> loaderWriter = mock(CacheLoaderWriter.class);
  doAnswer(invocation -> {
    gate.acquire();
    return null;
  }).when(loaderWriter).writeAll(any(Iterable.class));

  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    final Cache<String, String> testCache = cacheManager.createCache("testBatchedWriteBehindBlocksWhenFull", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 1).queueSize(1).build())
      .build());

    testCache.put("key1", "value");
    testCache.put("key2", "value");

    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
      Future<?> blockedPut = executor.submit(() -> testCache.put("key3", "value"));

      try {
        blockedPut.get(100, MILLISECONDS);
        fail("Expected TimeoutException");
      } catch (TimeoutException e) {
        //expected
      }
      gate.release();
      blockedPut.get(10, SECONDS);
      gate.release(Integer.MAX_VALUE);
    } finally {
      executor.shutdown();
    }
  }
}
 
Example #29
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBehindQueueSize() throws Exception {

  class TestWriteBehindProvider extends WriteBehindProviderFactory.Provider {

    private WriteBehind<?, ?> writeBehind = null;

    @Override
    @SuppressWarnings("unchecked")
    public <K, V> WriteBehind<K, V> createWriteBehindLoaderWriter(CacheLoaderWriter<K, V> cacheLoaderWriter, WriteBehindConfiguration<?> configuration) {
      this.writeBehind = super.createWriteBehindLoaderWriter(cacheLoaderWriter, configuration);
      return (WriteBehind<K, V>) writeBehind;
    }

    public WriteBehind<?, ?> getWriteBehind() {
      return writeBehind;
    }
  }

  TestWriteBehindProvider writeBehindProvider = new TestWriteBehindProvider();
  WriteBehindTestLoaderWriter<String, String> loaderWriter = new WriteBehindTestLoaderWriter<>();

  try (CacheManager cacheManager = managerBuilder().using(writeBehindProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testAgedBatchedIsWritten", configurationBuilder()
      .withService(new DefaultCacheLoaderWriterConfiguration(loaderWriter))
      .withService(newBatchedWriteBehindConfiguration(5, SECONDS, 2).build())
      .build());

    testCache.put("key1", "value1");
    assertThat(writeBehindProvider.getWriteBehind().getQueueSize(), is(1L));
    testCache.put("key2", "value2");

  }
}
 
Example #30
Source File: ClusteredLoaderWriterStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testReplace2ArgsValueAbsentInCacheAbsentInSOR() throws Exception {
  LockingServerStoreProxyImpl storeProxy = mock(LockingServerStoreProxyImpl.class);
  @SuppressWarnings("unchecked")
  CacheLoaderWriter<Long, String> loaderWriter = mock(CacheLoaderWriter.class);
  when(storeProxy.lock(anyLong())).thenReturn(entryOf());
  ClusteredLoaderWriterStore<Long, String> store = new ClusteredLoaderWriterStore<>(configuration, codec, resolver, storeProxy,
          timeSource, loaderWriter, new DefaultStatisticsService());
  assertThat(store.replace(1L, "one", "Again"), is(Store.ReplaceStatus.MISS_NOT_PRESENT));
  verify(storeProxy, times(0)).append(anyLong(), ArgumentMatchers.any(ByteBuffer.class));
  verify(loaderWriter, times(1)).load(anyLong());
  verify(loaderWriter, times(0)).write(anyLong(), anyString());
}