Java Code Examples for javax.cache.Cache

The following examples show how to use javax.cache.Cache. These examples are extracted from open source projects. 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
/**
 * @throws Exception If failed.
 */
@Test
public void testIterator() throws Exception {
    IgniteCache<Integer, Integer> cache = grid(0).cache(cacheName());

    final int KEYS = 1000;

    for (int i = 0; i < KEYS; i++)
        cache.put(i, i);

    // Try to initialize readers in case when near cache is enabled.
    for (int i = 0; i < gridCount(); i++) {
        cache = grid(i).cache(cacheName());

        for (int k = 0; k < KEYS; k++)
            assertEquals((Object)k, cache.get(k));
    }

    int cnt = 0;

    for (Cache.Entry e : cache)
        cnt++;

    assertEquals(KEYS, cnt);
}
 
Example 2
Source Project: carbon-identity-framework   Source File: BaseCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Clears a cache entry.
 *
 * @param key Key to clear cache.
 */
public void clearCacheEntry(K key) {

    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.remove(key);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example 3
@Test
public void testGetClaimsWhenCacheNonEmpty() throws Exception{
    DefaultClaimsRetriever defaultClaimsRetriever = new DefaultClaimsRetriever();
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_CLAIM_CACHE_EXPIRY)).thenReturn("3600");
    CacheBuilder cacheBuilder = Mockito.mock(CacheBuilder.class);
    Mockito.when(cacheManager.createCacheBuilder(APIConstants.CLAIMS_APIM_CACHE)).thenReturn(cacheBuilder);
    Cache cache = Mockito.mock(Cache.class);

    Mockito.when(cacheBuilder.setStoreByValue(false)).thenReturn(cacheBuilder);
    Mockito.when(cacheBuilder.setExpiry(Matchers.any(CacheConfiguration.ExpiryType.class),Matchers.any(
            CacheConfiguration.Duration.class))).thenReturn(cacheBuilder);
    Mockito.when(cacheBuilder.build()).thenReturn(cache);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTenantId(USER_NAME)).thenReturn(TENANT_ID);

    SortedMap<String, String> claimValues = new TreeMap<String, String>();
    claimValues.put("claim1", "http://wso2.org/claim1");
    claimValues.put("claim2", "http://wso2.org/claim2");
    UserClaims userClaims = new UserClaims(claimValues);
    Mockito.when(cache.get(Matchers.any(ClaimCacheKey.class))).thenReturn(userClaims);
    SortedMap<String, String> claims = defaultClaimsRetriever.getClaims(USER_NAME);

    Assert.assertNotNull(claims);
    Assert.assertEquals(claimValues, claims);
}
 
Example 4
Source Project: cache2k   Source File: CacheWriterClientServerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that entry can be written from the {@link CacheWriterClient} via
 * the {@link CacheWriterServer}.
 */
@Test
public void shouldWriteFromServerWithClient() throws Exception {

    RecordingCacheWriter<String, String> recordingCacheWriter = new RecordingCacheWriter<>();

    CacheWriterServer<String, String> serverCacheWriter = new CacheWriterServer<>(10000,
                                                              recordingCacheWriter);
    serverCacheWriter.open();

    CacheWriterClient<String, String> clientCacheWriter =
        new CacheWriterClient<>(serverCacheWriter.getInetAddress(), serverCacheWriter.getPort());
    Cache.Entry<String, String> entry = new Entry<>("hello", "gudday");
    clientCacheWriter.write(entry);
    String writtenValue = recordingCacheWriter.get("hello");

    Assert.assertThat(writtenValue, is(notNullValue()));
    Assert.assertThat(writtenValue, is("gudday"));
    Assert.assertThat(recordingCacheWriter.hasWritten("hello"), is(true));
    clientCacheWriter.close();
    serverCacheWriter.close();
}
 
Example 5
/**
 * @param queue Queue.
 * @return Primary node for queue's header.
 * @throws Exception If failed.
 */
private int primaryQueueNode(IgniteQueue queue) throws Exception {
    GridCacheContext cctx = GridTestUtils.getFieldValue(queue, "cctx");

    GridCacheAffinityManager aff = cctx.affinity();

    CachePeekMode[] modes = new CachePeekMode[]{CachePeekMode.ALL};

    for (int i = 0; i < gridCount(); i++) {
        for (Cache.Entry e : grid(i).context().cache().internalCache(cctx.name()).localEntries(modes)) {
            Object key = e.getKey();

            if (aff.primaryByKey(grid(i).localNode(), key, AffinityTopologyVersion.NONE)
                && key instanceof GridCacheQueueHeaderKey)
                return i;
        }
    }

    fail("Failed to find primary node for queue header.");

    return -1;
}
 
Example 6
Source Project: cache2k   Source File: CacheManagerClassLoadingTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Request cache manager with different class loader and put a value in the cache that
 * was loaded by that class loader. equals() needs to work and class loaders needs to be
 * identical
 */
@Test
public void testCorrectClassLoaderForValue() throws Exception {
  SpecialClassLoader loader = new SpecialClassLoader();
  CachingProvider provider = Caching.getCachingProvider();
  CacheManager mgr = Caching.getCachingProvider().getCacheManager(provider.getDefaultURI(), loader);
  Cache<Object, Object> cache = mgr.createCache(CACHE_NAME, new MutableConfiguration());
  Class valueClass = loader.loadSpecial(DomainValue.class);
  assertEquals(valueClass.getClassLoader(), loader);
  Object value = valueClass.newInstance();
  setValue(value, "someValue");
  String someKey = "Key";
  cache.put(someKey, value);
  Cache.Entry e = cache.iterator().next();
  assertSame("class loaders identical", value.getClass().getClassLoader(), e.getValue().getClass().getClassLoader());
  assertEquals(value, e.getValue());
  mgr.close();
}
 
Example 7
Source Project: blazingcache   Source File: CacheLoaderTest.java    License: 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 8
Source Project: redisson   Source File: JCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClear() 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.clear();
    assertThat(cache.get("1")).isNull();

    cache.close();
    runner.stop();
}
 
Example 9
Source Project: cxf   Source File: JCacheOAuthDataProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected static <K, V extends ServerAccessToken> List<V> getTokens(Cache<K, V> cache,
                                                                  Client client, UserSubject sub) {
    final Set<K> toRemove = new HashSet<>();
    final List<V> tokens = new ArrayList<>();

    for (Iterator<Cache.Entry<K, V>> it = cache.iterator(); it.hasNext();) {
        Cache.Entry<K, V> entry = it.next();
        V token = entry.getValue();

        if (isExpired(token)) {
            toRemove.add(entry.getKey());
        } else if (isTokenMatched(token, client, sub)) {
            tokens.add(token);
        }
    }

    cache.removeAll(toRemove);

    return tokens;
}
 
Example 10
Source Project: cache2k   Source File: CacheWriterServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onProcess(ObjectInputStream ois, ObjectOutputStream oos)
        throws IOException, ClassNotFoundException {
    if (cacheWriter == null) {
        throw new NullPointerException("The cacheWriter for the CacheWriterServer has not be set");
    } else {
        Collection<Cache.Entry<? extends K, ? extends V>> entrys = readEntries(ois);
        try {
            cacheWriter.writeAll(entrys);
        } catch (Exception e) {
            oos.writeObject(e);

            for (Cache.Entry<? extends K, ? extends V> entry1 : entrys) {
                oos.writeObject(entry1.getKey());
            }

            oos.writeObject(null);

            return;
        }

        assert(entrys.size() == 0);
        oos.writeObject(null);
    }
}
 
Example 11
Source Project: ignite   Source File: GridCacheStoreManagerAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public String toString() {
    if (!S.includeSensitive())
        return "[size=" + size() + "]";

    Iterator<Cache.Entry<?, ?>> it = iterator();

    if (!it.hasNext())
        return "[]";

    SB sb = new SB("[");

    while (true) {
        Cache.Entry<?, ?> e = it.next();

        sb.a(e.toString());

        if (!it.hasNext())
            return sb.a(']').toString();

        sb.a(", ");
    }
}
 
Example 12
Source Project: blazingcache   Source File: TCKCacheManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void removeCache_CacheStopped() {
    CacheManager cacheManager = getCacheManager();
    String name1 = "c1";
    cacheManager.createCache(name1, new MutableConfiguration());
    Cache cache1 = cacheManager.getCache(name1);
    cacheManager.destroyCache(name1);
    ensureClosed(cache1);
}
 
Example 13
Source Project: commons-jcs   Source File: CacheWriterAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeAll(final Collection<Cache.Entry<? extends K, ? extends V>> entries) throws CacheWriterException
{
    for (final Cache.Entry<? extends K, ? extends V> entry : entries)
    {
        write(entry);
    }
}
 
Example 14
Source Project: micro-integrator   Source File: ClaimInvalidationCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Clears a cache entry.
 *
 * @param key Key to clear cache.
 */
private void clearCacheEntry(String key) {
    Cache<String, Integer> cache = getClaimCache();
    if (cache != null) {
        cache.remove(key);
    }
}
 
Example 15
Source Project: cache2k   Source File: CacheManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void create_cache2k_config_nowrap() {
  CachingProvider p = Caching.getCachingProvider();
  CacheManager cm = p.getCacheManager();
  Cache<Long, Double> cache = cm.createCache("aCache", ExtendedMutableConfiguration.of(
    new Cache2kBuilder<Long, Double>(){}
      .entryCapacity(10000)
      .expireAfterWrite(5, TimeUnit.MINUTES)
  ));
  assertFalse(cache instanceof CopyCacheProxy);
  assertNull(cache.unwrap(org.cache2k.Cache.class).requestInterface(WiredCache.class));
  cache.close();
}
 
Example 16
Source Project: ignite   Source File: GridCacheProxyImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Iterator<Cache.Entry<K, V>> iterator() {
    CacheOperationContext prev = gate.enter(opCtx);

    try {
        return delegate.iterator();
    }
    finally {
        gate.leave(prev);
    }
}
 
Example 17
Source Project: ignite   Source File: GridCacheUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Entry predicate factory mostly used for deserialization.
 *
 * @param <K> Key type.
 * @param <V> Value type.
 * @return Factory instance.
 */
public static <K, V> IgniteClosure<Integer, IgnitePredicate<Cache.Entry<K, V>>[]> factory() {
    return new IgniteClosure<Integer, IgnitePredicate<Cache.Entry<K, V>>[]>() {
        @Override public IgnitePredicate<Cache.Entry<K, V>>[] apply(Integer len) {
            return (IgnitePredicate<Cache.Entry<K, V>>[])(len == 0 ? EMPTY : new IgnitePredicate[len]);
        }
    };
}
 
Example 18
Source Project: component-runtime   Source File: VaultProxyCacheResolver.java    License: Apache License 2.0 5 votes vote down vote up
private Cache<?, ?> createCache(final String exceptionCacheName) {
    final CacheSizeManager<Object, Object> listener = new CacheSizeManager<>(cacheConfiguration.maxSize());
    final Configuration<Object, Object> configuration = cacheConfiguration.createConfiguration(listener);
    final Cache<Object, Object> instance = cacheManager.createCache(exceptionCacheName, configuration);
    listener.accept(instance);
    return instance;
}
 
Example 19
Source Project: blazingcache   Source File: CacheLoaderTest.java    License: 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 20
Source Project: pippo   Source File: JCacheSessionDataStorage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a cache with name and expiry policy with idle time.
 *
 * @param name name of cache
 * @param idleTime idle time in seconds
 * @return the cache with name and expiry policy with idle time
 */
protected Cache<String, SessionData> create(String name, long idleTime) {
    return Caching
            .getCachingProvider()
            .getCacheManager()
            .createCache(
                    name,
                    new MutableConfiguration<String, SessionData>()
                    .setTypes(String.class, SessionData.class)
                    .setExpiryPolicyFactory(
                            TouchedExpiryPolicy.factoryOf(
                                    new Duration(
                                            TimeUnit.SECONDS,
                                            idleTime))));
}
 
Example 21
Source Project: carbon-apimgt   Source File: CacheProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create and return GATEWAY_INVALID_TOKEN_CACHE
 */
public static Cache createInvalidTokenCache() {
    String apimGWCacheExpiry = getApiManagerConfiguration().getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY);
    if (apimGWCacheExpiry != null) {
        return getCache(APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants
                .GATEWAY_INVALID_TOKEN_CACHE_NAME, Long.parseLong(apimGWCacheExpiry), Long.parseLong
                (apimGWCacheExpiry));
    } else {
        long defaultCacheTimeout = getDefaultCacheTimeout();
        return getCache(APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants
                .GATEWAY_INVALID_TOKEN_CACHE_NAME, defaultCacheTimeout, defaultCacheTimeout);
    }
}
 
Example 22
/** {@inheritDoc} */
@Override public IgniteBiTuple<Boolean, Object> onBeforeRemove(Cache.Entry<Object, Object> entry) {
    if (!noInterceptor)
        return (IgniteBiTuple)delegate.onBeforeRemove((Cache.Entry)entry);

    return new IgniteBiTuple<>(false, entry.getValue());
}
 
Example 23
Source Project: ignite   Source File: ViewCacheClosure.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param ctx Context.
 * @param compiled Compiled pattern.
 * @param cacheInfo Cache info.
 */
private void collectSequences(GridKernalContext ctx, Pattern compiled, List<CacheInfo> cacheInfo) throws IgniteCheckedException {
    String dsCacheName = DataStructuresProcessor.ATOMICS_CACHE_NAME + "@default-ds-group";

    IgniteInternalCache<GridCacheInternalKey, AtomicDataStructureValue> cache0 = ctx.cache().cache(dsCacheName);

    final Iterator<Cache.Entry<GridCacheInternalKey, AtomicDataStructureValue>> iter = cache0.scanIterator(false, null);

    while (iter.hasNext()) {
        Cache.Entry<GridCacheInternalKey, AtomicDataStructureValue> entry = iter.next();

        final AtomicDataStructureValue val = entry.getValue();

        if (val.type() == DataStructureType.ATOMIC_SEQ) {
            final String name = entry.getKey().name();

            if (compiled.matcher(name).find()) {
                CacheInfo ci = new CacheInfo();
                ci.setSeqName(name);
                ci.setSeqVal(((GridCacheAtomicSequenceValue)val).get());

                cacheInfo.add(ci);
            }

        }
    }
}
 
Example 24
Source Project: ignite   Source File: CacheBasedLabelPairCursor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Queries the specified cache using the specified filter.
 *
 * @param upstreamCache Ignite cache with {@code upstream} data.
 * @param filter Filter for {@code upstream} data. If {@code null} then all entries will be returned.
 * @return Query cursor.
 */
private QueryCursor<Cache.Entry<K, V>> query(IgniteCache<K, V> upstreamCache, IgniteBiPredicate<K, V> filter) {
    ScanQuery<K, V> qry = new ScanQuery<>();

    if (filter != null) // This section was added to keep code correct of qry.setFilter(null) behaviour will changed.
        qry.setFilter(filter);

    return upstreamCache.query(qry);
}
 
Example 25
/** */
@Test
public void testRemoteFilterFactory() {
    checkContinuousQuery(() -> {
        ContinuousQueryWithTransformer<Integer, Integer, Integer> q = new ContinuousQueryWithTransformer<>();

        q.setRemoteFilterFactory(() -> RMT_FILTER);
        q.setRemoteTransformerFactory(() -> Cache.Entry::getValue);

        return q;
    }, false);
}
 
Example 26
Source Project: blazingcache   Source File: TCKCacheManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getOrCreateCache_Different() {
    String name1 = "c1";
    CacheManager cacheManager = getCacheManager();
    cacheManager.createCache(name1, new MutableConfiguration());
    Cache cache1 = cacheManager.getCache(name1);

    String name2 = "c2";
    cacheManager.createCache(name2, new MutableConfiguration());
    Cache cache2 = cacheManager.getCache(name2);

    assertEquals(cache1, cacheManager.getCache(name1));
    assertEquals(cache2, cacheManager.getCache(name2));
}
 
Example 27
Source Project: carbon-apimgt   Source File: DefaultClaimsRetriever.java    License: Apache License 2.0 5 votes vote down vote up
protected Cache getClaimsLocalCache() {
    String apimClaimsCacheExpiry = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().
            getAPIManagerConfiguration().getFirstProperty(APIConstants.JWT_CLAIM_CACHE_EXPIRY);
    if(!isClaimsCacheInitialized && apimClaimsCacheExpiry != null) {init();
        isClaimsCacheInitialized = true;
       return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).
                createCacheBuilder(APIConstants.CLAIMS_APIM_CACHE)
               .setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
                       Long.parseLong(apimClaimsCacheExpiry)))
               .setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
                       Long.parseLong(apimClaimsCacheExpiry))).setStoreByValue(false).build();
    }else {
       return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.CLAIMS_APIM_CACHE);
    }
}
 
Example 28
/**
 * @param cache Cache.
 * @param sql Query.
 * @param expCnt Number of expected entries.
 */
private void checkQuery(IgniteCache<Integer, TestValue> cache, String sql, int expCnt) {
    SqlQuery<Integer, TestValue> qry = new SqlQuery<>(TestValue.class, sql);

    List<Cache.Entry<Integer, TestValue>> res = cache.query(qry).getAll();

    assertEquals(expCnt, res.size());

    for (Cache.Entry<Integer, TestValue> e : res) {
        assertNotNull(e.getKey());

        assertEquals((int)e.getKey(), e.getValue().val);
    }
}
 
Example 29
Source Project: ignite   Source File: CacheKeepBinaryWithInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void onAfterPut(Cache.Entry<Integer, Integer> entry) {
    System.out.println("After put [e=" + entry + ']');

    onAfterPut++;

    assertEquals((Integer)1, entry.getKey());
    assertEquals((Integer)10, entry.getValue());
}
 
Example 30
Source Project: cache2k   Source File: TypesTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * What happens when you:
 *
 * 1) declare using generics and
 * 2) don't specify types during configuration.
 */
@Test
public void simpleAPIWithGenericsAndNoTypeEnforcement() {

  MutableConfiguration config = new MutableConfiguration<String, Integer>();
  Cache<Identifier, Dog> cache = cacheManager.createCache(cacheName, config);


  //Types are restricted
  //Cannot put in wrong types
  //cache.put(1, "something");

  //can put in
  cache.put(pistachio.getName(), pistachio);
  cache.put(tonto.getName(), tonto);

  //cannot get out wrong key types
  //assertNotNull(cache.get(1));
  assertNotNull(cache.get(pistachio.getName()));
  assertNotNull(cache.get(tonto.getName()));

  //cannot remove wrong key types
  //assertTrue(cache.remove(1));
  assertTrue(cache.remove(pistachio.getName()));
  assertTrue(cache.remove(tonto.getName()));

}