javax.cache.Cache Java Examples

The following examples show how to use javax.cache.Cache. 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: DefaultClaimsRetrieverTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: JCacheTest.java    From redisson with 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 #3
Source File: BaseCache.java    From carbon-identity-framework with 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 #4
Source File: JCacheOAuthDataProvider.java    From cxf with 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 #5
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 #6
Source File: CacheWriterServer.java    From cache2k with 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 #7
Source File: CacheManagerClassLoadingTest.java    From cache2k with 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 #8
Source File: IgniteCacheConfigVariationsFullApiTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #9
Source File: GridCacheAbstractQueueFailoverDataConsistencySelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #10
Source File: CacheWriterClientServerTest.java    From cache2k with 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 #11
Source File: GridCacheStoreManagerAdapter.java    From ignite with 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 File: CacheManagerTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void getOrCreateCache_StatusOK() {
  String name = "c1";
  getCacheManager().createCache(name, new MutableConfiguration());
  Cache cache = getCacheManager().getCache(name);
  assertNotNull(cache);
  assertEquals(name, cache.getName());
}
 
Example #13
Source File: JCache.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
public JCache(URL url) {
    String method = url.getParameter(Constants.METHOD_KEY, "");
    String key = url.getAddress() + "." + url.getServiceKey() + "." + method;
    // jcache parameter is the full-qualified class name of SPI implementation
    String type = url.getParameter("jcache");

    CachingProvider provider = type == null || type.length() == 0 ? Caching.getCachingProvider() : Caching.getCachingProvider(type);
    CacheManager cacheManager = provider.getCacheManager();
    Cache<Object, Object> cache = cacheManager.getCache(key);
    if (cache == null) {
        try {
            //configure the cache
            MutableConfiguration config =
                    new MutableConfiguration<Object, Object>()
                            .setTypes(Object.class, Object.class)
                            .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000))))
                            .setStoreByValue(false)
                            .setManagementEnabled(true)
                            .setStatisticsEnabled(true);
            cache = cacheManager.createCache(key, config);
        } catch (CacheException e) {
            // concurrent cache initialization
            cache = cacheManager.getCache(key);
        }
    }

    this.store = cache;
}
 
Example #14
Source File: TenantConfigMediaTypeHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void clearConfigCache() {
    Cache tenantConfigCache = CacheProvider.getTenantConfigCache();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    String cacheName = tenantId + "_" + APIConstants.TENANT_CONFIG_CACHE_NAME;
    if (tenantConfigCache.containsKey(cacheName)) {
        tenantConfigCache.remove(cacheName);
    }

}
 
Example #15
Source File: DeviceCacheManagerImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public void addDeviceToCache(DeviceIdentifier deviceIdentifier, Device device, int tenantId) {
    Cache<DeviceCacheKey, Device> lCache = DeviceManagerUtil.getDeviceCache();
    if (lCache != null) {
        DeviceCacheKey cacheKey = getCacheKey(deviceIdentifier, tenantId);
        if (lCache.containsKey(cacheKey)) {
            this.updateDeviceInCache(deviceIdentifier, device, tenantId);
        } else {
            lCache.put(cacheKey, device);
        }
    }
}
 
Example #16
Source File: CacheProvider.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return the valid username cache
 */
public static Cache createGatewayUsernameCache() {
    String apimGWCacheExpiry = getApiManagerConfiguration().getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY);
    if (apimGWCacheExpiry != null) {
        return getCache(APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.GATEWAY_USERNAME_CACHE_NAME,
                Long.parseLong(apimGWCacheExpiry), Long.parseLong(apimGWCacheExpiry));
    } else {
        long defaultCacheTimeout = getDefaultCacheTimeout();
        return getCache(APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.GATEWAY_USERNAME_CACHE_NAME,
                defaultCacheTimeout, defaultCacheTimeout);
    }
}
 
Example #17
Source File: CacheFactory.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
public <K, V> Cache<K, V> getCache(String alias) {
    checkInitilized();
    Cache<K, V> cache = manager.getCache(alias);
    if(isNull(cache)) {
       cache = manager.createCache(alias, new MutableConfiguration<K, V>().setStoreByValue(false).setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(Duration.ONE_HOUR)));
    }
    return cache;
}
 
Example #18
Source File: IgniteCacheQueryMultiThreadedSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param entries Entries.
 * @param g Grid.
 * @return Affinity nodes.
 */
private Set<UUID> affinityNodes(Iterable<Cache.Entry<Integer, Integer>> entries, Ignite g) {
    Set<UUID> nodes = new HashSet<>();

    for (Cache.Entry<Integer, Integer> entry : entries)
        nodes.add(g.affinity(DEFAULT_CACHE_NAME).mapKeyToPrimaryAndBackups(entry.getKey()).iterator().next().id());

    return nodes;
}
 
Example #19
Source File: RecommenderDetailsExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Update the recommendationsCache by  connecting with the recommendation engine and getting recommendations for
 * the given user for given tenant domain. A user can have several entries cache for different tenants
 *
 * @param userName     User's Name
 * @param tenantDomain tenantDomain
 */
public void updateRecommendationsCache(String userName, String tenantDomain) {

    long currentTime = System.currentTimeMillis();
    long lastUpdatedTime = 0;
    long waitDuration = recommendationEnvironment.getWaitDuration() * 60 * 1000;
    Cache recommendationsCache = CacheProvider.getRecommendationsCache();
    String cacheName = userName + "_" + tenantDomain;
    JSONObject cachedObject = (JSONObject) recommendationsCache.get(cacheName);
    if (cachedObject != null) {
        lastUpdatedTime = (long) cachedObject.get(APIConstants.LAST_UPDATED_CACHE_KEY);
    }
    if (currentTime - lastUpdatedTime < waitDuration) { // double checked locking to avoid unnecessary locking
        return;
    }
    synchronized (RecommenderDetailsExtractor.class) {
        // Only get recommendations if the last update was was performed more than 15 minutes ago
        if (currentTime - lastUpdatedTime < waitDuration) {
            return;
        }
        String recommendations = getRecommendations(userName, tenantDomain);
        JSONObject object = new JSONObject();
        object.put(APIConstants.RECOMMENDATIONS_CACHE_KEY, recommendations);
        object.put(APIConstants.LAST_UPDATED_CACHE_KEY, System.currentTimeMillis());
        recommendationsCache.put(cacheName, object);
    }
}
 
Example #20
Source File: TcpClientCache.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** Handle scan query. */
private QueryCursor<Cache.Entry<K, V>> scanQuery(ScanQuery<K, V> qry) {
    Consumer<PayloadOutputChannel> qryWriter = payloadCh -> {
        writeCacheInfo(payloadCh);

        BinaryOutputStream out = payloadCh.out();

        if (qry.getFilter() == null)
            out.writeByte(GridBinaryMarshaller.NULL);
        else {
            serDes.writeObject(out, qry.getFilter());
            out.writeByte((byte)1); // Java platform
        }

        out.writeInt(qry.getPageSize());
        out.writeInt(qry.getPartition() == null ? -1 : qry.getPartition());
        out.writeBoolean(qry.isLocal());
    };

    return new ClientQueryCursor<>(new ClientQueryPager<>(
        ch,
        ClientOperation.QUERY_SCAN,
        ClientOperation.QUERY_SCAN_CURSOR_GET_PAGE,
        qryWriter,
        keepBinary,
        marsh
    ));
}
 
Example #21
Source File: DefaultClaimsRetriever.java    From carbon-apimgt with 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 #22
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 #23
Source File: ReliabilityTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Test that failover doesn't lead to silent query inconsistency.
 */
@Test
public void testQueryConsistencyOnFailover() throws Exception {
    int CLUSTER_SIZE = 2;

    try (LocalIgniteCluster cluster = LocalIgniteCluster.start(CLUSTER_SIZE);
         IgniteClient client = Ignition.startClient(new ClientConfiguration()
             .setAddresses(cluster.clientAddresses().toArray(new String[CLUSTER_SIZE])))
    ) {
        ClientCache<Integer, Integer> cache = client.createCache("cache");

        cache.put(0, 0);
        cache.put(1, 1);

        Query<Cache.Entry<Integer, String>> qry = new ScanQuery<Integer, String>().setPageSize(1);

        try (QueryCursor<Cache.Entry<Integer, String>> cur = cache.query(qry)) {
            int cnt = 0;

            for (Iterator<Cache.Entry<Integer, String>> it = cur.iterator(); it.hasNext(); it.next()) {
                cnt++;

                if (cnt == 1) {
                    for (int i = 0; i < CLUSTER_SIZE; i++)
                        dropAllThinClientConnections(Ignition.allGrids().get(i));
                }
            }

            fail("ClientReconnectedException must be thrown");
        }
        catch (ClientReconnectedException expected) {
            // No-op.
        }
    }
}
 
Example #24
Source File: TypesTest.java    From cache2k with 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()));

}
 
Example #25
Source File: IgniteDbPutGetAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param partCntrs Expected per-partition entries count.
 */
private void checkScanPartition(Ignite ignite,
    IgniteCache<DbKey, DbValue> cache,
    Map<Integer, Integer> partCntrs,
    boolean loc) {
    Affinity<Object> aff = ignite.affinity(cache.getName());

    int parts = aff.partitions();

    for (int p = 0; p < parts; p++) {
        ScanQuery<DbKey, DbValue> qry = new ScanQuery<>();

        qry.setPartition(p);
        qry.setLocal(loc);

        if (loc && !ignite.cluster().localNode().equals(aff.mapPartitionToNode(p)))
            continue;

        QueryCursor<Cache.Entry<DbKey, DbValue>> cur = cache.query(qry);

        Set<DbKey> allKeys = new HashSet<>();

        for (Cache.Entry<DbKey, DbValue> e : cur) {
            allKeys.add(e.getKey());
            assertEquals(e.getKey().val, e.getValue().iVal);
        }

        Integer exp = partCntrs.get(p);

        if (exp == null)
            exp = 0;

        assertEquals(exp, (Integer)allKeys.size());
    }
}
 
Example #26
Source File: CacheKeepBinaryWithInterceptorTest.java    From ignite with 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 #27
Source File: GridDhtCacheAdapter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param primary If {@code true} includes primary entries.
 * @param backup If {@code true} includes backup entries.
 * @param keepBinary Keep binary flag.
 * @return Local entries iterator.
 */
public Iterator<Cache.Entry<K, V>> localEntriesIterator(final boolean primary,
    final boolean backup,
    final boolean keepBinary) {
    return localEntriesIterator(primary,
        backup,
        keepBinary,
        ctx.affinity().affinityTopologyVersion());
}
 
Example #28
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 #29
Source File: GridCacheOffheapIndexEntryEvictTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @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 #30
Source File: JCacheCacheResolver.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public ProxyManager<String>  resolve(String cacheName) {
	Cache springCache = cacheManager.getCache(cacheName);
	if (springCache == null) {
		throw new JCacheNotFoundException(cacheName);
	}

	return Bucket4j.extension(JCache.class).proxyManagerForCache(springCache);
}