javax.cache.configuration.FactoryBuilder Java Examples

The following examples show how to use javax.cache.configuration.FactoryBuilder. 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: CacheExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheStatisticsRemoveAll() throws Exception {

  long _EXPIRY_MILLIS = 3;
  //cannot be zero or will not be added to the cache
  ExpiryPolicy policy = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, _EXPIRY_MILLIS));
  expiryPolicyServer.setExpiryPolicy(policy);

  MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
  config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient)).setStatisticsEnabled(true);
  Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);

  for (int i = 0; i < 100; i++) {
    cache.put(i, i+100);
  }
  //should work with all implementations
  Thread.sleep(_EXPIRY_MILLIS);
  cache.removeAll();

  assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CachePuts"));
  //Removals does not count expired entries
  assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheRemovals"));

}
 
Example #2
Source File: Runner.java    From ignite with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    ClientConnectorConfiguration connectorConfiguration = new ClientConnectorConfiguration().setPort(10890);

    TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder()
            .setAddresses(Collections.singleton("127.0.0.1:47500"));

    TcpDiscoverySpi discoSpi = new TcpDiscoverySpi()
        .setIpFinder(ipFinder)
        .setSocketTimeout(300)
        .setNetworkTimeout(300);

    CacheConfiguration expiryCacheCfg = new CacheConfiguration("twoSecondCache")
            .setExpiryPolicyFactory(FactoryBuilder.factoryOf(
                    new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 2))));

    IgniteConfiguration cfg = new IgniteConfiguration()
            .setClientConnectorConfiguration(connectorConfiguration)
            .setDiscoverySpi(discoSpi)
            .setCacheConfiguration(expiryCacheCfg)
            .setLocalHost("127.0.0.1");

    Ignition.start(cfg);
}
 
Example #3
Source File: AdditionalCacheListenerTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Override
protected MutableConfiguration<Integer, String> extraSetup(MutableConfiguration<Integer, String> cfg) {
  // cfg.setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, 5)));
  cacheEntryListenerServer = new CacheEntryListenerServer<>(10011, Integer.class, String.class);
  try {
    cacheEntryListenerServer.open();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  listener = new RecordingListener<>();
  cacheEntryListenerServer.addCacheEventListener(listener);
  CacheEntryListenerClient<Integer, String> clientListener =
    new CacheEntryListenerClient<>(cacheEntryListenerServer.getInetAddress(), cacheEntryListenerServer.getPort());
  boolean _isSynchronous = false;
  listenerConfiguration = new MutableCacheEntryListenerConfiguration<>(
    FactoryBuilder.factoryOf(clientListener), null, true, _isSynchronous);
  return cfg.addCacheEntryListenerConfiguration(listenerConfiguration);
}
 
Example #4
Source File: CacheWriterTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
/**
 * Configure write-through before each test.
 */
@Before
public void onBeforeEachTest() throws IOException {
  // establish and open a CacheWriterServer to handle cache
  // cache loading requests from a CacheWriterClient
  cacheWriter = new RecordingCacheWriter<>();
  cacheWriterServer = new CacheWriterServer<>(10000, cacheWriter);
  cacheWriterServer.open();

  // establish the CacheManager for the tests
  cacheManager = Caching.getCachingProvider().getCacheManager();

  // establish a CacheWriterClient that a Cache can use for writing/deleting entries
  // (via the CacheWriterServer)
  CacheWriterClient<Integer, String> theCacheWriter = new CacheWriterClient<>(cacheWriterServer.getInetAddress(),
      cacheWriterServer.getPort());

  MutableConfiguration<Integer, String> configuration = new MutableConfiguration<>();
  configuration.setTypes(Integer.class, String.class);
  configuration.setCacheWriterFactory(FactoryBuilder.factoryOf(theCacheWriter));
  configuration.setWriteThrough(true);

  getCacheManager().createCache("cache-writer-test", configuration);
  cache = getCacheManager().getCache("cache-writer-test", Integer.class, String.class);
}
 
Example #5
Source File: IgniteCacheRandomOperationBenchmark.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cache Ignite cache.
 * @param map Parameters map.
 * @throws Exception If failed.
 */
private void doContinuousQuery(IgniteCache<Object, Object> cache, Map<Object, Object> map) throws Exception {
    List<QueryCursor> cursors = (ArrayList<QueryCursor>)map.get(cache.getName());

    if (cursors == null) {
        cursors = new ArrayList<>(CONTINUOUS_QUERY_PER_CACHE);
        map.put(cache.getName(), cursors);
    }

    if (cursors.size() == CONTINUOUS_QUERY_PER_CACHE) {
        QueryCursor cursor = cursors.get(nextRandom(cursors.size()));
        cursor.close();
        cursors.remove(cursor);
    }

    ContinuousQuery qry = new ContinuousQuery();

    qry.setLocalListener(new ContinuousQueryUpdater());

    qry.setRemoteFilterFactory(FactoryBuilder.factoryOf(new ContinuousQueryFilter()));

    cursors.add(cache.query(qry));
}
 
Example #6
Source File: CacheLoaderWithoutReadThroughTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
/**
 * Establish the {@link javax.cache.CacheManager} and {@link javax.cache.Cache} for a test.
 */
@Before
public void onBeforeEachTest() throws IOException {
  //establish and open a CacheLoaderServer to handle cache
  //cache loading requests from a CacheLoaderClient
  cacheLoaderServer = new CacheLoaderServer<String, String>(10000);
  cacheLoaderServer.open();

  //establish the CacheManager for the tests
  cacheManager = Caching.getCachingProvider().getCacheManager();

  //establish a CacheLoaderClient that a Cache can use for loading entries
  //(via the CacheLoaderServer)
  CacheLoaderClient<String, String> cacheLoader =
      new CacheLoaderClient<>(cacheLoaderServer.getInetAddress(), cacheLoaderServer.getPort());

  //establish a Cache Configuration that uses a CacheLoader (no Read-Through)
  MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
  configuration.setTypes(String.class, String.class);
  configuration.setCacheLoaderFactory(FactoryBuilder.factoryOf(cacheLoader));
  configuration.setReadThrough(false);

  //configure the cache
  cacheManager.createCache("cache-loader-test", configuration);
  cache = cacheManager.getCache("cache-loader-test", String.class, String.class);
}
 
Example #7
Source File: ReadWriteICacheTest.java    From hazelcast-simulator with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup() {
    counters = targetInstance.getList(name + "counters");

    RecordingCacheLoader<Integer> loader = new RecordingCacheLoader<>();
    loader.loadDelayMs = getDelayMs;

    RecordingCacheWriter<Integer, Integer> writer = new RecordingCacheWriter<>();
    writer.writeDelayMs = putDelayMs;
    writer.deleteDelayMs = removeDelayMs;

    config = new CacheConfig<>();
    config.setReadThrough(true);
    config.setWriteThrough(true);
    config.setCacheLoaderFactory(FactoryBuilder.factoryOf(loader));
    config.setCacheWriterFactory(FactoryBuilder.factoryOf(writer));

    CacheManager cacheManager = createCacheManager(targetInstance);
    cacheManager.createCache(name, config);
    cache = cacheManager.getCache(name);
}
 
Example #8
Source File: CacheLoaderTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
/**
 * Establish the {@link CacheManager} and {@link Cache} for a test.
 */
@Before
public void onBeforeEachTest() throws IOException {
  //establish and open a CacheLoaderServer to handle cache
  //cache loading requests from a CacheLoaderClient
  cacheLoaderServer = new CacheLoaderServer<String, String>(10000);
  cacheLoaderServer.open();

  //establish the CacheManager for the tests
  cacheManager = Caching.getCachingProvider().getCacheManager();

  //establish a CacheLoaderClient that a Cache can use for loading entries
  //(via the CacheLoaderServer)
  CacheLoaderClient<String, String> cacheLoader =
      new CacheLoaderClient<>(cacheLoaderServer.getInetAddress(), cacheLoaderServer.getPort());

  //establish a Cache Configuration that uses a CacheLoader and Read-Through
  MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
  configuration.setTypes(String.class, String.class);
  configuration.setCacheLoaderFactory(FactoryBuilder.factoryOf(cacheLoader));
  configuration.setReadThrough(true);

  //configure the cache
  cacheManager.createCache("cache-loader-test", configuration);
  cache = cacheManager.getCache("cache-loader-test", String.class, String.class);
}
 
Example #9
Source File: CacheContinuousQueryRandomOperationsTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize continuous query with transformer.
 * Query will accumulate all events in accumulator.
 *
 * @param qry Continuous query.
 * @param acc Accumulator for events.
 * @param <K> Key type.
 * @param <V> Value type.
 */
private <K, V> void initQueryWithTransformer(
    ContinuousQueryWithTransformer<K, V, CacheEntryEvent> qry,
    Collection<CacheEntryEvent<? extends K, ? extends V>> acc) {

    IgniteClosure<CacheEntryEvent<? extends K, ? extends V>, CacheEntryEvent> transformer =
        new IgniteClosure<CacheEntryEvent<? extends K, ? extends V>, CacheEntryEvent>() {
            @Override public CacheEntryEvent apply(CacheEntryEvent<? extends K, ? extends V> event) {
                return event;
            }
        };

    ContinuousQueryWithTransformer<K, V, CacheEntryEvent> qry0 =
        (ContinuousQueryWithTransformer<K, V, CacheEntryEvent>)qry;

    qry0.setRemoteTransformerFactory(FactoryBuilder.factoryOf(transformer));

    qry0.setLocalListener(new EventListener<CacheEntryEvent>() {
        @Override public void onUpdated(Iterable<? extends CacheEntryEvent> events) {
            for (CacheEntryEvent e : events)
                acc.add(e);
        }
    });
}
 
Example #10
Source File: TypesafeConfigurator.java    From caffeine with Apache License 2.0 6 votes vote down vote up
/** Adds the JCache specification's lazy expiration settings. */
public void addLazyExpiration() {
  Duration creation = getDurationFor("policy.lazy-expiration.creation");
  Duration update = getDurationFor("policy.lazy-expiration.update");
  Duration access = getDurationFor("policy.lazy-expiration.access");
  requireNonNull(creation, "policy.lazy-expiration.creation may not be null");

  boolean eternal = Objects.equals(creation, Duration.ETERNAL)
      && Objects.equals(update, Duration.ETERNAL)
      && Objects.equals(access, Duration.ETERNAL);
  @SuppressWarnings("NullAway")
  Factory<? extends ExpiryPolicy> factory = eternal
      ? EternalExpiryPolicy.factoryOf()
      : FactoryBuilder.factoryOf(new JCacheExpiryPolicy(creation, update, access));
  configuration.setExpiryPolicyFactory(factory);
}
 
Example #11
Source File: IgniteCacheLoadRebalanceEvictionSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
    IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

    LruEvictionPolicy evictionPolicy = new LruEvictionPolicy<>();
    evictionPolicy.setMaxSize(LRU_MAX_SIZE);

    CacheConfiguration<String, byte[]> cacheCfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);
    cacheCfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
    cacheCfg.setCacheMode(CacheMode.PARTITIONED);
    cacheCfg.setBackups(1);
    cacheCfg.setReadFromBackup(true);
    cacheCfg.setEvictionPolicy(evictionPolicy);
    cacheCfg.setOnheapCacheEnabled(true);
    cacheCfg.setStatisticsEnabled(true);

    cacheCfg.setWriteThrough(false);
    cacheCfg.setReadThrough(false);

    cacheCfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(new Storage()));

    cfg.setCacheConfiguration(cacheCfg);

    return cfg;
}
 
Example #12
Source File: CacheLoaderTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoReadThrough() {

    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .setCacheLoaderFactory(new FactoryBuilder.ClassFactory(MockCacheLoader.class))
                .setReadThrough(false);

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);

        String key = "key";
        String result = cache.get(key);
        assertNull(result);
    }
}
 
Example #13
Source File: CacheLoaderTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadThroughGetAll() {

    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .setCacheLoaderFactory(new FactoryBuilder.ClassFactory(MockCacheLoader.class))
                .setReadThrough(true);

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);

        String key = "key";
        Map<String, String> result = cache.getAll(new HashSet<>(Arrays.asList(key)));
        assertEquals("LOADED_" + key, result.get(key));
        assertEquals("LOADED_" + key, cache.get(key));
    }
}
 
Example #14
Source File: IgniteCacheWriteBehindNoUpdateSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
    IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

    CacheConfiguration<String, Long> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);

    ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
    ccfg.setCacheMode(CacheMode.PARTITIONED);
    ccfg.setBackups(1);
    ccfg.setReadFromBackup(true);
    ccfg.setCopyOnRead(false);
    ccfg.setName(THROTTLES_CACHE_NAME);

    Duration expiryDuration = new Duration(TimeUnit.MINUTES, 1);

    ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(expiryDuration));
    ccfg.setReadThrough(false);
    ccfg.setWriteThrough(true);

    ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory<>(new TestCacheStore()));

    cfg.setCacheConfiguration(ccfg);

    return cfg;
}
 
Example #15
Source File: CacheLoaderTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
    public void shouldNotLoadWithNullKeyUsingLoadAll() throws Exception {

        HashSet<String> keys = new HashSet<>();
        keys.add(null);

        CachingProvider cachingProvider = Caching.getCachingProvider();
        Properties p = new Properties();
        try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
            MutableConfiguration<String, String> config
                    = new MutableConfiguration<String, String>()
                    .setTypes(String.class, String.class)
                    .setCacheLoaderFactory(new FactoryBuilder.ClassFactory(MockCacheLoader.class))
                    .setReadThrough(true);
            Cache<String, String> cache = cacheManager.createCache("test", config);
            CompletionListenerFuture future = new CompletionListenerFuture();
            cache.loadAll(keys, false, future);

            fail("Expected a NullPointerException");
        } catch (NullPointerException e) {
            //SKIP: expected
        } finally {
//            assertThat(cacheLoader.getLoadCount(), is(0));
        }
    }
 
Example #16
Source File: CacheWriterTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteThroughUsingInvoke_remove_nonExistingEntry() {
    RecordingCacheWriter<Integer, String> cacheWriter = new RecordingCacheWriter<>();
    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<Integer, String> config
                = new MutableConfiguration<Integer, String>()
                .setTypes(Integer.class, String.class)
                .setCacheWriterFactory(new FactoryBuilder.SingletonFactory<>(cacheWriter))
                .setWriteThrough(true);

        Cache<Integer, String> cache = cacheManager.createCache("simpleCache", config);
        assertEquals(0, cacheWriter.getWriteCount());
        assertEquals(0, cacheWriter.getDeleteCount());

        cache.invoke(1, new RemoveEntryProcessor<Integer, String, Object>());
        assertEquals(0, cacheWriter.getWriteCount());
        assertEquals(1, cacheWriter.getDeleteCount());
        assertFalse(cacheWriter.hasWritten(1));
    }
}
 
Example #17
Source File: CacheStoreReadFromBackupTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** */
@SuppressWarnings("unchecked")
private CacheConfiguration cacheConfig(String cacheName) {
    CacheConfiguration ccfg = new CacheConfiguration<>(cacheName);

    ccfg.setCacheMode(cacheMode);
    ccfg.setBackups(backups);
    ccfg.setAtomicityMode(atomicityMode());
    ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
    ccfg.setAffinity(new RendezvousAffinityFunction(false, 1));
    ccfg.setReadThrough(true);
    ccfg.setReadFromBackup(true);
    ccfg.setCacheStoreFactory(FactoryBuilder.factoryOf(TestStore.class));

    if (near)
        ccfg.setNearConfiguration(new NearCacheConfiguration());

    return ccfg;
}
 
Example #18
Source File: CacheWriterTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoWriteThrough() {
    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MockCacheWriter external = new MockCacheWriter();
        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .setCacheWriterFactory(new FactoryBuilder.SingletonFactory<>(external))
                .setWriteThrough(false);

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);
        String key = "key";
        cache.put(key, "some_datum");

        String result = external.database.get(key);
        assertNull(result);
    }
}
 
Example #19
Source File: CacheExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void putAllShouldCallGetExpiry() {
  CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
  expiryPolicyServer.setExpiryPolicy(expiryPolicy);

  MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
  config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
  Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);

  Map<Integer, Integer> map = new HashMap<>();
  map.put(1, 1);
  map.put(2, 2);

  cache.put(1, 1);

  assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), is(0));
  expiryPolicy.resetCount();

  cache.putAll(map);

  assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), greaterThanOrEqualTo(1));
  expiryPolicy.resetCount();
}
 
Example #20
Source File: CacheExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void invokeGetValueShouldCallGetExpiry() {
  CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
  expiryPolicyServer.setExpiryPolicy(expiryPolicy);

  MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
  config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
  Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);

  final Integer key = 123;
  final Integer setValue = 456;

  // verify non-access to non-existent entry does not call getExpiryForAccessedEntry. no read-through scenario.
  Integer resultValue = cache.invoke(key, new GetEntryProcessor<Integer, Integer>());

  assertEquals(null, resultValue);
  assertThat(expiryPolicy.getCreationCount(), is(0));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), is(0));

  // verify access to existing entry.
  resultValue = cache.invoke(key, new SetEntryProcessor<Integer, Integer>(setValue));

  assertEquals(resultValue, setValue);
  assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), is(0));
  expiryPolicy.resetCount();

  resultValue = cache.invoke(key, new GetEntryProcessor<Integer, Integer>());

  assertEquals(setValue, resultValue);
  assertThat(expiryPolicy.getCreationCount(), is(0));
  assertThat(expiryPolicy.getAccessCount(), greaterThanOrEqualTo(1));
  assertThat(expiryPolicy.getUpdatedCount(), is(0));
}
 
Example #21
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException, FailedToStartRedisException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();

    MutableConfiguration<String, String> config = new MutableConfiguration<>();
    config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
    config.setStoreByValue(true);
    
    URI configUri = getClass().getResource("redisson-jcache.json").toURI();
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager(configUri, null)
            .createCache("test", config);

    CountDownLatch latch = new CountDownLatch(1);
    
    String key = "123";
    ExpiredListener clientListener = new ExpiredListener(latch, key, "90");
    MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration = 
            new MutableCacheEntryListenerConfiguration<String, String>(FactoryBuilder.factoryOf(clientListener), null, true, true);
    cache.registerCacheEntryListener(listenerConfiguration);

    cache.put(key, "90");
    Assert.assertNotNull(cache.get(key));
    
    latch.await();
    
    Assert.assertNull(cache.get(key));
    
    cache.close();
    runner.stop();
}
 
Example #22
Source File: CacheLoaderTest.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadallReplaceExisting() throws Exception {

    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .setCacheLoaderFactory(new FactoryBuilder.ClassFactory(MockCacheLoader.class))
                .setReadThrough(false);

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);
        cache.put("one", "to_be_replaced");
        Set<String> keys = new HashSet<>();
        keys.add("one");
        keys.add("two");
        keys.add("three");
        CompletionListenerFuture future = new CompletionListenerFuture();
        cache.loadAll(keys, true, future);
        future.get();

        for (String key : keys) {
            String result = cache.get(key);
            assertEquals("LOADED_" + key, result);
        }
    }
}
 
Example #23
Source File: ImmediateExpiryTest.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
@Test
public void immediate()
{
    final CachingProvider cachingProvider = Caching.getCachingProvider();
    final CacheManager cacheManager = cachingProvider.getCacheManager();
    cacheManager.createCache("default",
            new MutableConfiguration<>()
                    .setExpiryPolicyFactory(
                            new FactoryBuilder.SingletonFactory<ExpiryPolicy>(new CreatedExpiryPolicy(Duration.ZERO))));
    final Cache<String, String> cache = cacheManager.getCache("default");
    assertFalse(cache.containsKey("foo"));
    cache.put("foo", "bar");
    assertFalse(cache.containsKey("foo"));
    cachingProvider.close();
}
 
Example #24
Source File: CacheListenersTest.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateListenerSynch() {

    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        Map<String, String> created = new HashMap<>();
        CacheEntryCreatedListener<String, String> listener = new CacheEntryCreatedListener<String, String>() {
            @Override
            public void onCreated(Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException {
                for (CacheEntryEvent<? extends String, ? extends String> e : events) {
                    created.put(e.getKey(), e.getValue());
                }
            }
        };

        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .addCacheEntryListenerConfiguration(new MutableCacheEntryListenerConfiguration<>(
                        new FactoryBuilder.SingletonFactory(listener), null, true, true)
                );

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);

        String key = "key";
        cache.put(key, "value");
        assertEquals("value", created.get(key));
    }
}
 
Example #25
Source File: CacheExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void invokeGetValueWithReadThroughForNonExistentEntryShouldCallGetExpiryForCreatedEntry() throws IOException {

  //establish and open a CacheLoaderServer to handle cache
  //cache loading requests from a CacheLoaderClient

  // this cacheLoader just returns the key as the value.
  RecordingCacheLoader<Integer> recordingCacheLoader = new RecordingCacheLoader<>();
  try (CacheLoaderServer<Integer, Integer> cacheLoaderServer = new CacheLoaderServer<>(10000, recordingCacheLoader)) {
    cacheLoaderServer.open();

    //establish a CacheLoaderClient that a Cache can use for loading entries
    //(via the CacheLoaderServer)
    CacheLoaderClient<Integer, Integer> cacheLoader =
        new CacheLoaderClient<>(cacheLoaderServer.getInetAddress(), cacheLoaderServer.getPort());

    CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
    expiryPolicyServer.setExpiryPolicy(expiryPolicy);

    MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
    config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
    config.setCacheLoaderFactory(FactoryBuilder.factoryOf(cacheLoader));
    config.setReadThrough(true);
    Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);

    final Integer key = 123;
    final Integer recordingCacheLoaderValue = key;

    // verify create when read through is enabled and entry was non-existent in cache.
    Integer resultValue = cache.invoke(key, new GetEntryProcessor<Integer, Integer>());

    assertEquals(recordingCacheLoaderValue, resultValue);
    assertTrue(recordingCacheLoader.hasLoaded(key));

    assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1));
    assertThat(expiryPolicy.getAccessCount(), is(0));
    assertThat(expiryPolicy.getUpdatedCount(), is(0));
    closeTestCache();
  }
}
 
Example #26
Source File: CacheWriterTest.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWriteThroughUsingInvoke_setValue_CreateEntryThenRemove() {
    RecordingCacheWriter<Integer, String> cacheWriter = new RecordingCacheWriter<>();
    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<Integer, String> config
                = new MutableConfiguration<Integer, String>()
                .setTypes(Integer.class, String.class)
                .setCacheWriterFactory(new FactoryBuilder.SingletonFactory<>(cacheWriter))
                .setWriteThrough(true);

        Cache<Integer, String> cache = cacheManager.createCache("simpleCache", config);
        assertEquals(0, cacheWriter.getWriteCount());
        assertEquals(0, cacheWriter.getDeleteCount());

        EntryProcessor processors[]
                = new EntryProcessor[]{
                    new AssertNotPresentEntryProcessor(null),
                    new SetEntryProcessor<Integer, String>("Gudday World"),
                    new RemoveEntryProcessor<Integer, String, Object>(true)
                };
        cache.invoke(1, new CombineEntryProcessor<Integer, String>(processors));
        assertEquals(0, cacheWriter.getWriteCount());
        assertEquals(0, cacheWriter.getDeleteCount());
        assertTrue(!cacheWriter.hasWritten(1));
        assertTrue(cache.get(1) == null);
        assertFalse(cache.containsKey(1));
    }
}
 
Example #27
Source File: CacheExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void putShouldCallGetExpiry() {
  CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
  expiryPolicyServer.setExpiryPolicy(expiryPolicy);

  MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
  config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
  Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);

  cache.containsKey(1);

  assertThat(expiryPolicy.getCreationCount(), is(0));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), is(0));

  cache.put(1, 1);

  assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), is(0));
  expiryPolicy.resetCount();

  cache.put(1, 1);

  assertThat(expiryPolicy.getCreationCount(), is(0));
  assertThat(expiryPolicy.getAccessCount(), is(0));
  assertThat(expiryPolicy.getUpdatedCount(), greaterThanOrEqualTo(1));
  expiryPolicy.resetCount();
}
 
Example #28
Source File: CreateBasicJCacheProgrammatic.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
public void run(int numberOfIteration, int numberOfObjectPerIteration, int sleepTimeMillisBetweenIterations) throws Exception {
  LOGGER.info("JCache testing BEGIN - Creating JCache Programmatically without any XML config");

  //finds ehcache provider automatically if it is in the classpath
  CachingProvider cachingProvider = Caching.getCachingProvider();

  // If there are multiple providers in your classpath, use the fully qualified name to retrieve the Ehcache caching provider.
  //CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");

  try (CacheManager cacheManager = cachingProvider.getCacheManager()) {
    Cache<Long, String> myJCache = cacheManager.createCache(
      CACHE_NAME,
      new MutableConfiguration<Long, String>()
        .setTypes(Long.class, String.class)
        .setStoreByValue(false)
        .setStatisticsEnabled(true)
        .setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 5)))));

    simpleGetsAndPutsCacheTest(myJCache, numberOfIteration, numberOfObjectPerIteration, sleepTimeMillisBetweenIterations, new KeyValueGenerator<Long, String>() {
      @Override
      public Long getKey(Number k) {
        return new Long(k.longValue());
      }

      @Override
      public String getValue(Number v) {
        return String.format("Da One %s!!", v.toString());
      }
    });
  }
  LOGGER.info("JCache testing DONE - Creating JCache Programmatically without any XML config");
}
 
Example #29
Source File: CacheLoadOnlyStoreExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates cache configurations for the loader.
 *
 * @return {@link CacheConfiguration}.
 */
private static CacheConfiguration cacheConfiguration(ProductLoader productLoader) {
    CacheConfiguration cacheCfg = new CacheConfiguration();

    cacheCfg.setCacheMode(CacheMode.PARTITIONED);
    cacheCfg.setName(CACHE_NAME);

    // provide the loader.
    cacheCfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(productLoader));

    return cacheCfg;
}
 
Example #30
Source File: TCKCacheManagerTest.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Test
public void containsKeyShouldNotCallExpiryPolicyMethods() {

    CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();

    MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
    config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicy));
    Cache<Integer, Integer> cache = getCacheManager().createCache("test", config);

    cache.containsKey(1);

    assertThat(expiryPolicy.getCreationCount(), is(0));
    assertThat(expiryPolicy.getAccessCount(), is(0));
    assertThat(expiryPolicy.getUpdatedCount(), is(0));

    cache.put(1, 1);

    assertTrue(expiryPolicy.getCreationCount() >= 1);
    assertThat(expiryPolicy.getAccessCount(), is(0));
    assertThat(expiryPolicy.getUpdatedCount(), is(0));
    expiryPolicy.resetCount();

    cache.containsKey(1);

    assertThat(expiryPolicy.getCreationCount(), is(0));
    assertThat(expiryPolicy.getAccessCount(), is(0));
    assertThat(expiryPolicy.getUpdatedCount(), is(0));
}