javax.cache.configuration.Configuration Java Examples

The following examples show how to use javax.cache.configuration.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: CacheManagerImpl.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable <K, V> Cache<K, V> getCache(
    String cacheName, Class<K> keyType, Class<V> valueType) {
  CacheProxy<K, V> cache = getCache(cacheName);
  if (cache == null) {
    return null;
  }
  requireNonNull(keyType);
  requireNonNull(valueType);

  Configuration<?, ?> config = cache.getConfiguration();
  if (keyType != config.getKeyType()) {
    throw new ClassCastException("Incompatible cache key types specified, expected " +
        config.getKeyType() + " but " + keyType + " was specified");
  } else if (valueType != config.getValueType()) {
    throw new ClassCastException("Incompatible cache value types specified, expected " +
        config.getValueType() + " but " + valueType + " was specified");
  }
  return cache;
}
 
Example #2
Source File: JCSCachingManager.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
@Override
// TODO: use configuration + handle not serializable key/values
public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(final String cacheName, final C configuration)
        throws IllegalArgumentException
{
    assertNotClosed();
    assertNotNull(cacheName, "cacheName");
    assertNotNull(configuration, "configuration");
    final Class<?> keyType = configuration == null ? Object.class : configuration.getKeyType();
    final Class<?> valueType = configuration == null ? Object.class : configuration.getValueType();
    if (!caches.containsKey(cacheName))
    {
        final Cache<K, V> cache = ClassLoaderAwareCache.wrap(loader,
                new JCSCache/*<K, V>*/(
                        loader, this, cacheName,
                        new JCSConfiguration/*<K, V>*/(configuration, keyType, valueType),
                        properties,
                        ExpiryAwareCache.class.cast(delegate.getCache(cacheName))));
        caches.putIfAbsent(cacheName, cache);
    }
    else
    {
        throw new javax.cache.CacheException("cache " + cacheName + " already exists");
    }
    return (Cache<K, V>) getCache(cacheName, keyType, valueType);
}
 
Example #3
Source File: BlazingCacheManager.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Override
public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyType, Class<V> valueType) {
    checkClosed();
    if (keyType == null || valueType == null) {
        throw new NullPointerException();
    }
    if (cacheName == null) {
        throw new NullPointerException();
    }
    Cache<K, V> res = caches.get(cacheName);
    if (res == null) {
        return null;
    }
    Configuration configuration = res.getConfiguration(Configuration.class);
    if ((!keyType.equals(configuration.getKeyType()))
            || !valueType.equals(configuration.getValueType())) {
        throw new ClassCastException();
    }
    return res;
}
 
Example #4
Source File: JCacheTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRx() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);

    CacheRx<String, String> rx = cache.unwrap(CacheRx.class);
    rx.put("1", "2").blockingAwait();
    assertThat(rx.get("1").blockingGet()).isEqualTo("2");
    
    cache.close();
    runner.stop();
}
 
Example #5
Source File: JCacheManagerAdapter.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Override @SuppressWarnings("unchecked")
public <K, V> Cache<K, V> getCache(String _cacheName, final Class<K> _keyType, final Class<V> _valueType) {
  if (_keyType == null || _valueType == null) {
    throw new NullPointerException();
  }
  Cache<K, V> c = getCache(_cacheName);
  if (c == null) {
    return null;
  }
  Configuration cfg = c.getConfiguration(Configuration.class);
  if (!cfg.getKeyType().equals(_keyType)) {
    throw new ClassCastException("key type mismatch, expected: " + cfg.getKeyType().getName());
  }
  if (!cfg.getValueType().equals(_valueType)) {
    throw new ClassCastException("value type mismatch, expected: " + cfg.getValueType().getName());
  }
  return c;
}
 
Example #6
Source File: CacheManagerImpl.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@Override
public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(
    String cacheName, C configuration) {
  requireNotClosed();
  requireNonNull(configuration);

  CacheProxy<?, ?> cache = caches.compute(cacheName, (name, existing) -> {
    if ((existing != null) && !existing.isClosed()) {
      throw new CacheException("Cache " + cacheName + " already exists");
    } else if (CacheFactory.isDefinedExternally(cacheName)) {
      throw new CacheException("Cache " + cacheName + " is configured externally");
    }
    return CacheFactory.createCache(this, cacheName, configuration);
  });
  enableManagement(cache.getName(), cache.getConfiguration().isManagementEnabled());
  enableStatistics(cache.getName(), cache.getConfiguration().isStatisticsEnabled());

  @SuppressWarnings("unchecked")
  Cache<K, V> castedCache = (Cache<K, V>) cache;
  return castedCache;
}
 
Example #7
Source File: JCacheTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsync() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);

    CacheAsync<String, String> async = cache.unwrap(CacheAsync.class);
    async.putAsync("1", "2").get();
    assertThat(async.getAsync("1").get()).isEqualTo("2");
    
    cache.close();
    runner.stop();
}
 
Example #8
Source File: JCacheCacher.java    From moleculer-java with MIT License 6 votes vote down vote up
public JCacheCacher(CacheManager cacheManager) {
	this.cacheManager = cacheManager;

	// Create default configuration
	defaultConfiguration = new Configuration<String, byte[]>() {

		private static final long serialVersionUID = 7207355369349418992L;

		@Override
		public final Class<String> getKeyType() {
			return String.class;
		}

		@Override
		public final Class<byte[]> getValueType() {
			return byte[].class;
		}

		@Override
		public final boolean isStoreByValue() {
			return true;
		}

	};
}
 
Example #9
Source File: JCacheTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testJson() throws InterruptedException, IllegalArgumentException, URISyntaxException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    cfg.setCodec(new TypedJsonJacksonCodec(String.class, LocalDateTime.class, objectMapper));
    
    Configuration<String, LocalDateTime> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, LocalDateTime> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);
    
    LocalDateTime t = LocalDateTime.now();
    cache.put("1", t);
    Assert.assertEquals(t, cache.get("1"));
    
    cache.close();
    runner.stop();
}
 
Example #10
Source File: TCacheFactory.java    From triava with Apache License 2.0 6 votes vote down vote up
@Override
public <K, V, C extends Configuration<K, V>> javax.cache.Cache<K, V> createCache(String cacheName, C configuration)
		throws IllegalArgumentException
{
	assertNotClosed();
	
	if (cacheName == null)
	{
		throw new NullPointerException("cacheName is null"); // JSR-107 compliance
	}

	// Create a new Builder, this will copy the configuration.
	InternalBuilder<K,V> builder = new InternalBuilder<>(this, configuration);
	builder.setId(cacheName);
	Cache<K, V> tcache = builder.build();
	return tcache.jsr107cache();
}
 
Example #11
Source File: JCacheConfiguration.java    From redisson with Apache License 2.0 6 votes vote down vote up
public JCacheConfiguration(Configuration<K, V> configuration) {
    if (configuration != null) {
        if (configuration instanceof RedissonConfiguration) {
            configuration = ((RedissonConfiguration<K, V>) configuration).getJcacheConfig();
        }
        
        if (configuration instanceof CompleteConfiguration) {
            delegate = new MutableConfiguration<K, V>((CompleteConfiguration<K, V>) configuration);
        } else {
            delegate = new MutableConfiguration<K, V>();
            delegate.setStoreByValue(configuration.isStoreByValue());
            delegate.setTypes(configuration.getKeyType(), configuration.getValueType());
        }
    } else {
        delegate = new MutableConfiguration<K, V>();
    }
    
    this.expiryPolicy = delegate.getExpiryPolicyFactory().create();
}
 
Example #12
Source File: CsCache107Manager.java    From demo_cache with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
synchronized public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(String cacheName, C configuration)
		throws IllegalArgumentException {
	if (isClosed()) {
		throw new IllegalStateException();
	}

	checkNotNull(cacheName, "cacheName");
	checkNotNull(configuration, "configuration");

	CsCache107<?, ?> cache = caches.get(cacheName);

	if (cache == null) {
		cache = new CsCache107<K, V>(this, cacheName, configuration);
		caches.put(cache.getName(), cache);

		return (Cache<K, V>) cache;
	} else {
		throw new CacheException("A cache named " + cacheName + " already exists.");
	}
}
 
Example #13
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutAll() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);
    
    Map<String, String> map = new HashMap<>();
    for (int i = 0; i < 10000; i++) {
        map.put("" + i, "" + i);
    }
    
    long start = System.currentTimeMillis();
    cache.putAll(map);
    System.out.println(System.currentTimeMillis() - start);
    
    for (int i = 0; i < 10000; i++) {
        assertThat(cache.containsKey("" + i)).isTrue();
    }
    
    cache.close();
    runner.stop();
}
 
Example #14
Source File: ClassLoaderAwareCache.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
@Override
public <C extends Configuration<K, V>> C getConfiguration(final Class<C> clazz)
{
    final Thread thread = Thread.currentThread();
    final ClassLoader loader = before(thread);
    try
    {
        return delegate.getConfiguration(clazz);
    }
    finally
    {
        thread.setContextClassLoader(loader);
    }
}
 
Example #15
Source File: IgniteCacheProxyImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <C extends Configuration<K, V>> C getConfiguration(Class<C> clazz) {
    GridCacheContext<K, V> ctx = getContextSafe();

    CacheConfiguration cfg = ctx.config();

    if (!clazz.isAssignableFrom(cfg.getClass()))
        throw new IllegalArgumentException();

    return clazz.cast(cfg);
}
 
Example #16
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedissonConfig() throws InterruptedException, IllegalArgumentException, URISyntaxException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);
    
    cache.put("1", "2");
    Assert.assertEquals("2", cache.get("1"));
    
    cache.put("key", "value");
    String result = cache.getAndRemove("key");

    Assert.assertEquals("value", result);
    Assert.assertNull(cache.get("key"));

    cache.put("key", "value");
    cache.remove("key");
    Assert.assertNull(cache.get("key"));
    
    cache.close();
    runner.stop();
}
 
Example #17
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAll() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);
    
    cache.put("1", "2");
    cache.put("3", "4");
    cache.put("4", "4");
    cache.put("5", "5");
    
    Set<? extends String> keys = new HashSet<String>(Arrays.asList("1", "3", "4", "5"));
    cache.removeAll(keys);
    assertThat(cache.containsKey("1")).isFalse();
    assertThat(cache.containsKey("3")).isFalse();
    assertThat(cache.containsKey("4")).isFalse();
    assertThat(cache.containsKey("5")).isFalse();
    
    cache.close();
    runner.stop();
}
 
Example #18
Source File: BlazingCacheManager.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V, C extends Configuration<K, V>>
        Cache<K, V> createCache(String cacheName, C configuration) throws IllegalArgumentException {
    checkClosed();
    if (cacheName == null || configuration == null) {
        throw new NullPointerException();
    }
    BlazingCacheCache c = new BlazingCacheCache(cacheName, client, this, keysSerializer, valuesSerializer, usefetch, configuration);
    if (caches.putIfAbsent(cacheName, c) != null) {
        throw new CacheException("A cache with name " + cacheName + " already exists");
    }
    return c;
}
 
Example #19
Source File: CsCache107Manager.java    From demo_cache with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyClazz, Class<V> valueClazz) {
	if (isClosed()) {
		throw new IllegalStateException();
	}

	checkNotNull(keyClazz, "keyType");
	checkNotNull(valueClazz, "valueType");

	CsCache107<K, V> cache = (CsCache107<K, V>) caches.get(cacheName);

	if (cache == null) {
		return null;
	} else {
		Configuration<?, ?> configuration = cache.getConfiguration(Configuration.class);

		if (configuration.getKeyType() != null && configuration.getKeyType().equals(keyClazz)) {
			if (configuration.getValueType() != null && configuration.getValueType().equals(valueClazz)) {
				return cache;
			} else {
				throw new ClassCastException("Incompatible cache value types specified, expected "
						+ configuration.getValueType() + " but " + keyClazz + " was specified");
			}
		} else {
			throw new ClassCastException("Incompatible cache key types specified, expected "
					+ configuration.getKeyType() + " but " + valueClazz + " was specified");
		}
	}
}
 
Example #20
Source File: JCacheManagerAdapter.java    From cache2k with Apache License 2.0 5 votes vote down vote up
public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(String _cacheName, C cfg)
  throws IllegalArgumentException {
  checkClosed();
  checkNonNullCacheName(_cacheName);
  synchronized (getLockObject()) {
    Cache _jsr107cache = name2adapter.get(_cacheName);
    if (_jsr107cache != null && !_jsr107cache.isClosed()) {
      throw new CacheException("cache already existing with name: " + _cacheName);
    }
    org.cache2k.Cache _existingCache = manager.getCache(_cacheName);
    if (_existingCache != null && !_existingCache.isClosed()) {
      throw new CacheException("A cache2k instance is already existing with name: " + _cacheName);
    }
    JCacheBuilder<K,V> _builder = new JCacheBuilder<K, V>(_cacheName, this);
    _builder.setConfiguration(cfg);
    Cache<K,V> _cache = _builder.build();
    org.cache2k.Cache _cache2k = _cache.unwrap(org.cache2k.Cache.class);
    Map<org.cache2k.Cache, Cache> _cloneC2k2jCache = new WeakHashMap<org.cache2k.Cache, Cache>(c2k2jCache);
    _cloneC2k2jCache.put(_cache2k, _cache);
    c2k2jCache = _cloneC2k2jCache;
    name2adapter.put(_cache.getName(), _cache);
    if (_builder.isStatisticsEnabled()) {
      enableStatistics(_cacheName, true);
    }
    if (_builder.isManagementEnabled()) {
      enableManagement(_cacheName, true);
    }
    return _cache;
  }
}
 
Example #21
Source File: Eh107CacheManager.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <K, V> Cache<K, V> getCache(String cacheName, Class<K> keyType, Class<V> valueType) {
  checkClosed();

  if (cacheName == null || keyType == null || valueType == null) {
    throw new NullPointerException();
  }

  Eh107Cache<K, V> cache = safeCacheRetrieval(cacheName);
  if (cache == null) {
    return null;
  }

  Class<?> actualKeyType = cache.getConfiguration(Configuration.class).getKeyType();
  Class<?> actualValueType = cache.getConfiguration(Configuration.class).getValueType();

  if (keyType != actualKeyType) {
    throw new ClassCastException("Cache has key type " + actualKeyType.getName()
        + ", but getCache() called with key type " + keyType.getName());
  }

  if (valueType != actualValueType) {
    throw new ClassCastException("Cache has value type " + actualValueType.getName()
        + ", but getCache() called with value type " + valueType.getName());
  }

  return cache;
}
 
Example #22
Source File: DefaultCacheManager.java    From lemon with Apache License 2.0 5 votes vote down vote up
public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(
        String cacheName, C configuration) throws IllegalArgumentException {
    Cache cache = new DefaultCache(cacheName, this);
    cacheMap.put(cacheName, cache);

    return cache;
}
 
Example #23
Source File: CacheManagerTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test @Ignore("not yet")
public void create_config_cache2k_types() {
  CachingProvider p = Caching.getCachingProvider();
  CacheManager cm = p.getCacheManager();
  ExtendedMutableConfiguration<String, BigDecimal> mc = new ExtendedMutableConfiguration<String, BigDecimal>();
  mc.setCache2kConfiguration(
    new Cache2kBuilder<String, BigDecimal>(){}
      .toConfiguration()
  );
  Cache<String, BigDecimal> c = cm.createCache("aCache", mc);
  assertEquals("aCache", c.getName());
  assertEquals(String.class, c.getConfiguration(Configuration.class).getKeyType());
  assertEquals(BigDecimal.class, c.getConfiguration(Configuration.class).getValueType());
  c.close();
}
 
Example #24
Source File: EhCache107ConfigurationIntegrationDocTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testTemplateOverridingStoreByValue() throws Exception {
  cacheManager = cachingProvider.getCacheManager(
      getClass().getResource("/org/ehcache/docs/ehcache-jsr107-template-override.xml").toURI(),
      getClass().getClassLoader());

  MutableConfiguration<Long, Client> mutableConfiguration = new MutableConfiguration<>();
  mutableConfiguration.setTypes(Long.class, Client.class);

  Client client1 = new Client("client1", 1);

  Cache<Long, Client> myCache = null;
  myCache = cacheManager.createCache("anyCache", mutableConfiguration);
  myCache.put(1L, client1);
  assertNotSame(client1, myCache.get(1L));
  assertTrue(myCache.getConfiguration(Configuration.class).isStoreByValue());

  myCache = cacheManager.createCache("byRefCache", mutableConfiguration);
  myCache.put(1L, client1);
  assertSame(client1, myCache.get(1L));
  assertFalse(myCache.getConfiguration(Configuration.class).isStoreByValue());

  myCache = cacheManager.createCache("weirdCache1", mutableConfiguration);
  myCache.put(1L, client1);
  assertNotSame(client1, myCache.get(1L));
  assertTrue(myCache.getConfiguration(Configuration.class).isStoreByValue());

  myCache = cacheManager.createCache("weirdCache2", mutableConfiguration);
  myCache.put(1L, client1);
  assertSame(client1, myCache.get(1L));
  assertFalse(myCache.getConfiguration(Configuration.class).isStoreByValue());
}
 
Example #25
Source File: Eh107XmlIntegrationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void test107CacheCanReturnCompleteConfigurationWhenNonePassedIn() {
  CacheManager cacheManager = cachingProvider.getCacheManager();
  Cache<Long, String> cache = cacheManager.createCache("cacheWithoutCompleteConfig", new Configuration<Long, String>() {
    private static final long serialVersionUID = 1L;

    @Override
    public Class<Long> getKeyType() {
      return Long.class;
    }

    @Override
    public Class<String> getValueType() {
      return String.class;
    }

    @Override
    public boolean isStoreByValue() {
      return true;
    }
  });

  @SuppressWarnings("unchecked")
  CompleteConfiguration<Long, String> configuration = cache.getConfiguration(CompleteConfiguration.class);
  assertThat(configuration, notNullValue());
  assertThat(configuration.isStoreByValue(), is(true));

  // Respects defaults
  assertThat(configuration.getExpiryPolicyFactory(), equalTo(EternalExpiryPolicy.factoryOf()));
}
 
Example #26
Source File: Eh107XmlIntegrationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testXmlExampleIn107() throws Exception {
  javax.cache.Cache<Long, Product> productCache = cacheManager.getCache("productCache", Long.class, Product.class);
  assertThat(productCache, is(notNullValue()));
  Configuration<Long, Product> configuration = productCache.getConfiguration(Configuration.class);
  assertThat(configuration.getKeyType(), is(equalTo(Long.class)));
  assertThat(configuration.getValueType(), is(equalTo(Product.class)));

  Eh107ReverseConfiguration<Long, Product> eh107ReverseConfiguration = productCache.getConfiguration(Eh107ReverseConfiguration.class);
  assertThat(eh107ReverseConfiguration.isReadThrough(), is(true));
  assertThat(eh107ReverseConfiguration.isWriteThrough(), is(true));
  assertThat(eh107ReverseConfiguration.isStoreByValue(), is(true));

  Product product = new Product(1L);
  productCache.put(1L, product);
  assertThat(productCache.get(1L).getId(), equalTo(product.getId()));

  product.setMutable("foo");
  assertThat(productCache.get(1L).getMutable(), nullValue());
  assertThat(productCache.get(1L), not(sameInstance(product)));

  javax.cache.Cache<Long, Customer> customerCache = cacheManager.getCache("customerCache", Long.class, Customer.class);
  assertThat(customerCache, is(notNullValue()));
  Configuration<Long, Customer> customerConfiguration = customerCache.getConfiguration(Configuration.class);
  assertThat(customerConfiguration.getKeyType(), is(equalTo(Long.class)));
  assertThat(customerConfiguration.getValueType(), is(equalTo(Customer.class)));

  Customer customer = new Customer(1L);
  customerCache.put(1L, customer);
  assertThat(customerCache.get(1L).getId(), equalTo(customer.getId()));
}
 
Example #27
Source File: JCacheBuilder.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void setConfiguration(Configuration<K,V> cfg) {
  if (cfg instanceof CompleteConfiguration) {
    config = (CompleteConfiguration<K,V>) cfg;
    if (cfg instanceof ExtendedConfiguration) {
      cache2kConfiguration = ((ExtendedConfiguration<K,V>) cfg).getCache2kConfiguration();
      if (cache2kConfiguration != null) {
        if (cache2kConfiguration.getName() != null && !cache2kConfiguration.getName().equals(name)) {
          throw new IllegalArgumentException("cache name mismatch.");
        }
        cache2kConfigurationWasProvided = true;
      }
    }
  } else {
    MutableConfiguration<K, V> _cfgCopy = new MutableConfiguration<K, V>();
    _cfgCopy.setTypes(cfg.getKeyType(), cfg.getValueType());
    _cfgCopy.setStoreByValue(cfg.isStoreByValue());
    config = _cfgCopy;
  }
  if (cache2kConfiguration == null) {
    cache2kConfiguration = CacheManagerImpl.PROVIDER.getDefaultConfiguration(manager.getCache2kManager());
    if (cfg instanceof ExtendedMutableConfiguration) {
      ((ExtendedMutableConfiguration) cfg).setCache2kConfiguration(cache2kConfiguration);
    }
  }
  cache2kConfiguration.setName(name);
  Cache2kCoreProviderImpl.CACHE_CONFIGURATION_PROVIDER.augmentConfiguration(manager.getCache2kManager(), cache2kConfiguration);
  cache2kConfigurationWasProvided |= cache2kConfiguration.isExternalConfigurationPresent();
  if (cache2kConfigurationWasProvided) {
    extraConfiguration = CACHE2K_DEFAULTS;
    JCacheConfiguration _extraConfigurationSpecified =
      cache2kConfiguration.getSections().getSection(JCacheConfiguration.class);
    if (_extraConfigurationSpecified != null) {
      extraConfiguration = _extraConfigurationSpecified;
    }
  }
}
 
Example #28
Source File: JCache.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public <C extends Configuration<K, V>> C getConfiguration(Class<C> clazz) {
    if (clazz.isInstance(config)) {
        return clazz.cast(config);
    }

    throw new IllegalArgumentException("Configuration object is not an instance of " + clazz);
}
 
Example #29
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatedExpiryPolicy() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();

    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);

    MutableConfiguration c = new MutableConfiguration();
    c.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(MILLISECONDS, 500)));
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg, c);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);

    cache.put("1", "2");
    Thread.sleep(500);
    assertThat(cache.get("1")).isNull();
    cache.put("1", "3");
    assertThat(cache.get("1")).isEqualTo("3");
    Thread.sleep(500);
    assertThat(cache.get("1")).isNull();

    cache.put("1", "4");
    assertThat(cache.get("1")).isEqualTo("4");
    Thread.sleep(100);
    cache.put("1", "5");
    assertThat(cache.get("1")).isEqualTo("5");

    cache.close();
    runner.stop();
}
 
Example #30
Source File: JCacheAdapter.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <C extends Configuration<K, V>> C getConfiguration(Class<C> _class) {
  if (CompleteConfiguration.class.isAssignableFrom(_class)) {
    MutableConfiguration<K, V> cfg = new MutableConfiguration<K, V>();
    cfg.setTypes(keyType, valueType);
    cfg.setStatisticsEnabled(jmxStatisticsEnabled);
    cfg.setManagementEnabled(jmxEnabled);
    cfg.setStoreByValue(storeByValue);
    Collection<CacheEntryListenerConfiguration<K,V>> _listenerConfigurations = eventHandling.getAllListenerConfigurations();
    for (CacheEntryListenerConfiguration<K,V> _listenerConfig : _listenerConfigurations) {
      cfg.addCacheEntryListenerConfiguration(_listenerConfig);
    }
    return (C) cfg;
  }
  return (C) new Configuration<K, V>() {
    @Override
    public Class<K> getKeyType() {
      return keyType;
    }

    @Override
    public Class<V> getValueType() {
      return valueType;
    }

    @Override
    public boolean isStoreByValue() {
      return storeByValue;
    }
  };
}