Java Code Examples for javax.cache.Cache#get()
The following examples show how to use
javax.cache.Cache#get() .
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: TCKCacheManagerTest.java From blazingcache with Apache License 2.0 | 6 votes |
@Test public void jmxExampleTest() throws Exception { CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<String, Integer> config = new MutableConfiguration<String, Integer>(); config.setTypes(String.class, Integer.class) .setStatisticsEnabled(true); cacheManager.createCache("simpleCache", config); Cache<String, Integer> cache = cacheManager.getCache("simpleCache", String.class, Integer.class); cache.get("test"); MBeanServer mBeanServer = JMXUtils.getMBeanServer(); System.out.println("mBeanServer:" + mBeanServer); ObjectName objectName = new ObjectName("javax.cache:type=CacheStatistics" + ",CacheManager=" + (cache.getCacheManager().getURI().toString()) + ",Cache=" + cache.getName()); System.out.println("obhectNAme:" + objectName); // Thread.sleep(Integer.MAX_VALUE); Long CacheMisses = (Long) mBeanServer.getAttribute(objectName, "CacheMisses"); System.out.println("CacheMisses:" + CacheMisses); assertEquals(1L, CacheMisses.longValue()); }
Example 2
Source File: UserRolesCache.java From micro-integrator with Apache License 2.0 | 6 votes |
public String[] getRolesListOfUser(String serverId, int tenantId, String userName) { Cache<UserRolesCacheKey, UserRolesCacheEntry> cache = this.getUserRolesCache(); //check for null if (isCacheNull(cache)) { return new String[0]; } if (!isCaseSensitiveUsername(userName, tenantId)) { userName = userName.toLowerCase(); } //create cache key UserRolesCacheKey userRolesCacheKey = new UserRolesCacheKey(serverId, tenantId, userName); //search cache and get cache entry UserRolesCacheEntry userRolesCacheEntry = cache.get(userRolesCacheKey); if (userRolesCacheEntry == null) { return new String[0]; } return userRolesCacheEntry.getUserRolesList(); }
Example 3
Source File: CacheLoaderTest.java From blazingcache with Apache License 2.0 | 6 votes |
@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 4
Source File: BaseCache.java From carbon-identity-framework with Apache License 2.0 | 6 votes |
/** * Retrieves a cache entry. * * @param key CacheKey * @return Cached entry. */ public V getValueFromCache(K key) { if (!isEnabled()) { return null; } if (key == null) { return null; } 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.get(key) != null) { return (V) cache.get(key); } return null; } finally { PrivilegedCarbonContext.endTenantFlow(); } }
Example 5
Source File: PolicyCacheManagerImpl.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
@Override public void updatePolicy(Policy policy) { Cache<Integer, List<Policy>> lCache = getPolicyListCache(); if (lCache.containsKey(1)) { List<Policy> cachedPolicy = lCache.get(1); Iterator iterator = cachedPolicy.iterator(); while (iterator.hasNext()) { Policy pol = (Policy) iterator.next(); if (pol.getId() == policy.getId()) { iterator.remove(); break; } } cachedPolicy.add(policy); lCache.replace(1, cachedPolicy); } }
Example 6
Source File: JSRExamplesTest.java From blazingcache with Apache License 2.0 | 6 votes |
@Test public void testJSRExample1() { CachingProvider cachingProvider = Caching.getCachingProvider(); Properties p = new Properties(); try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) { MutableConfiguration<String, Integer> config = new MutableConfiguration<String, Integer>() .setTypes(String.class, Integer.class) .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR)) .setStatisticsEnabled(true); Cache<String, Integer> cache = cacheManager.createCache("simpleCache", config); String key = "key"; Integer value1 = 1; cache.put("key", value1); Integer value2 = cache.get(key); assertEquals(value1, value2); cache.remove(key); assertNull(cache.get(key)); } }
Example 7
Source File: PolicyCacheManagerImpl.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
@Override public void addPolicy(Policy policy) { Cache<Integer, List<Policy>> lCache = getPolicyListCache(); if (lCache.containsKey(1)) { List<Policy> cachedPolicy = lCache.get(1); for (Policy pol : cachedPolicy) { if (pol.getId() == policy.getId()) { return; } } cachedPolicy.add(policy); } }
Example 8
Source File: PlatformDotNetEntityFrameworkCacheExtension.java From ignite with Apache License 2.0 | 5 votes |
/** * Tries to set the global cleanup node id to current node. * * @param grid Grid. * @param metaCache Meta cache. * * @return True if successfully set the flag indicating that current node performs the cleanup; otherwise false. */ private boolean trySetGlobalCleanupFlag(Ignite grid, final Cache<CleanupNodeId, UUID> metaCache) { final UUID localNodeId = grid.cluster().localNode().id(); while (true) { // Get the node performing cleanup. UUID nodeId = metaCache.get(CLEANUP_NODE_ID); if (nodeId == null) { if (metaCache.putIfAbsent(CLEANUP_NODE_ID, localNodeId)) return true; // Successfully reserved cleanup to local node. // Failed putIfAbsent: someone else may have started cleanup. Retry the check. continue; } if (nodeId.equals(localNodeId)) return false; // Current node already performs cleanup. if (grid.cluster().node(nodeId) != null) return false; // Another node already performs cleanup and is alive. // Node that performs cleanup has disconnected. if (metaCache.replace(CLEANUP_NODE_ID, nodeId, localNodeId)) return true; // Successfully replaced disconnected node id with our id. // Replace failed: someone else started cleanup. return false; } }
Example 9
Source File: CacheStopAndDestroySelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * Tests start -> destroy -> start -> close using CacheManager. */ @Test public void testTckStyleCreateDestroyClose() throws Exception { startGridsMultiThreaded(gridCount()); CacheManager mgr = Caching.getCachingProvider().getCacheManager(); String cacheName = "cache"; mgr.createCache(cacheName, new MutableConfiguration<Integer, String>().setTypes(Integer.class, String.class)); mgr.destroyCache(cacheName); Cache<Integer, String> cache = mgr.createCache(cacheName, new MutableConfiguration<Integer, String>().setTypes(Integer.class, String.class)); cache.close(); // Check second close succeeds without exception. cache.close(); try { cache.get(1); fail(); } catch (IllegalStateException ignored) { // No-op; } }
Example 10
Source File: SerializableEntityCache.java From requery with Apache License 2.0 | 5 votes |
@Override public <T> T get(Class<T> type, Object key) { Cache cache = getCache(type); if (cache != null && cache.isClosed()) { cache = null; } if (cache != null) { SerializedEntity container = (SerializedEntity) cache.get(key); if (container != null) { return type.cast(container.getEntity()); } } return null; }
Example 11
Source File: CacheExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void getShouldCallGetExpiryForAccessedEntry() { 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)); // when getting a non-existent entry, getExpiryForAccessedEntry is not called. cache.get(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(); // when getting an existing entry, getExpiryForAccessedEntry is called. cache.get(1); assertThat(expiryPolicy.getCreationCount(),is(0)); assertThat(expiryPolicy.getAccessCount(), greaterThanOrEqualTo(1)); assertThat(expiryPolicy.getUpdatedCount(), is(0)); expiryPolicy.resetCount(); }
Example 12
Source File: OpenJPAJCacheDataCache.java From commons-jcs with Apache License 2.0 | 5 votes |
@Override protected DataCachePCData getInternal(final Object oid) { Object result = null; if (OpenJPAId.class.isInstance(oid)) { final Class<?> cls = OpenJPAId.class.cast(oid).getType(); Cache<Object, Object> cache = manager.getOrCreateCache(OPENJPA_PREFIX, cls.getName()); if (cache == null) { return null; } else { result = cache.get(oid); } } else { final CacheManager cacheManager = manager.getCacheManager(); for (final String cacheName : cacheManager.getCacheNames()) { if (!cacheName.startsWith(OPENJPA_PREFIX)) { continue; } result = cacheManager.getCache(cacheName).get(oid); if (result != null) { break; } } } if (result == null) { return null; } return DataCachePCData.class.cast(result); }
Example 13
Source File: PolicyCacheManagerImpl.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
@Override public List<Policy> getAllPolicies() throws PolicyManagementException { Cache<Integer, List<Policy>> lCache = getPolicyListCache(); if (!lCache.containsKey(1)) { PolicyManager policyManager = new PolicyManagerImpl(); this.addAllPolicies(policyManager.getPolicies()); } if (log.isDebugEnabled()) { List<Policy> cachedPolicy = lCache.get(1); for (Policy policy : cachedPolicy) { log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy. getPolicyName() + " Activated : " + policy.isActive()); List<String> users = policy.getUsers(); for (String user : users) { log.debug("Users in cached policy : " + user); } List<String> roles = policy.getRoles(); for (String role : roles) { log.debug("Roles in cached policy : " + role); } } } return lCache.get(1); }
Example 14
Source File: DeviceCacheManagerImpl.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
@Override public Device getDeviceFromCache(DeviceIdentifier deviceIdentifier, int tenantId) { Cache<DeviceCacheKey, Device> lCache = DeviceManagerUtil.getDeviceCache(); if (lCache != null) { return lCache.get(getCacheKey(deviceIdentifier, tenantId)); } return null; }
Example 15
Source File: CacheLoaderTest.java From blazingcache with Apache License 2.0 | 5 votes |
@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 16
Source File: RecommenderDetailsExtractor.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * 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 17
Source File: OpenIDBaseCache.java From carbon-identity with Apache License 2.0 | 5 votes |
/** * Retrieves a cache entry. * * @param key CacheKey * @return Cached entry. */ public V getValueFromCache(K key) { Cache<K, V> cache = getOpenIDCache(); if (cache != null && cache.containsKey(key)) { return (V) cache.get(key); } return null; }
Example 18
Source File: RealmCache.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * Retrieves a cache entry. * * @param key CacheKey * @return Cached entry. */ public RealmCacheEntry getValueFromCache(RealmCacheKey key) { Cache<RealmCacheKey, RealmCacheEntry> cache = getRealmCache(); if (cache.containsKey(key)) { return cache.get(key); } return null; }
Example 19
Source File: LoaderWriterConfigTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void enablingReadThroughDoesNotForceWriteThrough() throws Exception { MutableConfiguration<Long, String> config = getConfiguration(true, cacheLoader, false, cacheWriter); Cache<Long, String> cache = cachingProvider.getCacheManager().createCache("writingCache", config); cache.put(42L, "Tadam!!!"); cache.get(100L); verifyZeroInteractions(cacheWriter); verify(cacheLoader).load(100L); }
Example 20
Source File: IteratorTest.java From ehcache3 with Apache License 2.0 | 5 votes |
@Test public void testIterateExpiredIsSkipped() throws Exception { EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider(); TestTimeSource testTimeSource = new TestTimeSource(); TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(testTimeSource); CacheManager cacheManager = provider.getCacheManager(new URI("test://testIterateExpiredReturnsNull"), new DefaultConfiguration(getClass().getClassLoader(), timeSourceConfiguration)); Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", new MutableConfiguration<Number, CharSequence>() .setExpiryPolicyFactory(() -> new ExpiryPolicy() { @Override public Duration getExpiryForCreation() { return Duration.ETERNAL; } @Override public Duration getExpiryForAccess() { return new Duration(TimeUnit.SECONDS, 1L); } @Override public Duration getExpiryForUpdate() { return Duration.ZERO; } }) .setTypes(Number.class, CharSequence.class)); testCache.put(1, "one"); testCache.get(1); testTimeSource.advanceTime(1000); Iterator<Cache.Entry<Number, CharSequence>> iterator = testCache.iterator(); assertThat(iterator.hasNext(), is(false)); cacheManager.close(); }