Java Code Examples for org.springframework.cache.Cache#ValueWrapper
The following examples show how to use
org.springframework.cache.Cache#ValueWrapper .
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: CacheAspectSupport.java From spring-analysis-note with MIT License | 6 votes |
/** * Find a cached item only for {@link CacheableOperation} that passes the condition. * @param contexts the cacheable operations * @return a {@link Cache.ValueWrapper} holding the cached item, * or {@code null} if none is found */ @Nullable private Cache.ValueWrapper findCachedItem(Collection<CacheOperationContext> contexts) { Object result = CacheOperationExpressionEvaluator.NO_RESULT; for (CacheOperationContext context : contexts) { if (isConditionPassing(context, result)) { Object key = generateKey(context, result); Cache.ValueWrapper cached = findInCaches(context, key); if (cached != null) { return cached; } else { if (logger.isTraceEnabled()) { logger.trace("No cache entry for key '" + key + "' in cache(s) " + context.getCacheNames()); } } } } return null; }
Example 2
Source File: AbstractJCacheAnnotationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void removeWithExceptionVetoRemove() { String keyItem = name.getMethodName(); Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(keyItem); Object value = new Object(); cache.put(key, value); try { service.removeWithException(keyItem, false); fail("Should have thrown an exception"); } catch (NullPointerException e) { // This is what we expect } Cache.ValueWrapper wrapper = cache.get(key); assertNotNull(wrapper); assertEquals(value, wrapper.get()); }
Example 3
Source File: CacheTemplate.java From n2o-framework with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public E execute(String cacheRegion, K key, CacheCallback<E> callback) { Cache cache = getCacheManager().getCache(cacheRegion); if (cache != null) { Cache.ValueWrapper cacheValueWrapper = cache.get(key); if (cacheValueWrapper != null) { E e = (E) cacheValueWrapper.get(); callback.doInCacheHit(e); return e; } } else { log.warn("Cannot find cache named [" + cacheRegion + "] for CacheTemplate"); return callback.doInCacheMiss(); } return handleCache(key, callback, cache); }
Example 4
Source File: AbstractJCacheAnnotationTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void cacheNull() { Cache cache = getCache(DEFAULT_CACHE); String keyItem = name.getMethodName(); assertNull(cache.get(keyItem)); Object first = service.cacheNull(keyItem); Object second = service.cacheNull(keyItem); assertSame(first, second); Cache.ValueWrapper wrapper = cache.get(keyItem); assertNotNull(wrapper); assertSame(first, wrapper.get()); assertNull("Cached value should be null", wrapper.get()); }
Example 5
Source File: AbstractJCacheAnnotationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void earlyPutWithExceptionVetoPut() { String keyItem = name.getMethodName(); Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(keyItem); Object value = new Object(); assertNull(cache.get(key)); try { service.earlyPutWithException(keyItem, value, false); fail("Should have thrown an exception"); } catch (NullPointerException e) { // This is what we expect } // This will be cached anyway as the earlyPut has updated the cache before Cache.ValueWrapper result = cache.get(key); assertNotNull(result); assertEquals(value, result.get()); }
Example 6
Source File: UserDAOImpl.java From icure-backend with GNU General Public License v2.0 | 6 votes |
@Override public User getOnFallback(String userId) { Cache.ValueWrapper valueWrapper = cache.get(userId); if (valueWrapper == null) { User user = ((CouchDbICureConnector) db).getFallbackConnector().find(User.class, userId); cache.put(userId, user); if (user == null) { throw new DocumentNotFoundException(userId); } return user; } if (valueWrapper.get() == null) { throw new DocumentNotFoundException(userId); } return (User) valueWrapper.get(); }
Example 7
Source File: PermissionServiceImpl.java From rice with Educational Community License v2.0 | 6 votes |
protected List<Permission> getPermissionsByName( String namespaceCode, String permissionName ) { String cacheKey = new StringBuilder("{getPermissionsByName}") .append("namespaceCode=").append(namespaceCode).append("|") .append("permissionName=").append(permissionName).toString(); Cache.ValueWrapper cachedValue = cacheManager.getCache(Permission.Cache.NAME).get(cacheKey); if (cachedValue != null && cachedValue.get() instanceof List) { return ((List<Permission>)cachedValue.get()); } HashMap<String,Object> criteria = new HashMap<String,Object>(3); criteria.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, namespaceCode); criteria.put(KimConstants.UniqueKeyConstants.PERMISSION_NAME, permissionName); criteria.put(KRADPropertyConstants.ACTIVE, Boolean.TRUE); List<Permission> permissions = toPermissions(dataObjectService.findMatching( PermissionBo.class, QueryByCriteria.Builder.andAttributes(criteria).build() ).getResults()); cacheManager.getCache(Permission.Cache.NAME).put(cacheKey, permissions); return permissions; }
Example 8
Source File: UserDAOImpl.java From icure-backend with GNU General Public License v2.0 | 6 votes |
@Override public User getUserOnUserDb(String userId, String groupId, boolean bypassCache) { CouchDbICureConnector userDb = ((CouchDbICureConnector) db).getCouchDbICureConnector(groupId); String fullId = userDb.getUuid() + ":" + userId; Cache.ValueWrapper value = bypassCache ? null : cache.get(fullId); if (value == null) { User user = userDb.find(User.class, userId); cache.put(fullId, user); if (user == null) { throw new DocumentNotFoundException(userId); } return user; } if (value.get() == null) { throw new DocumentNotFoundException(userId); } return (User) value.get(); }
Example 9
Source File: AbstractJCacheAnnotationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void earlyPutWithException() { String keyItem = name.getMethodName(); Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(keyItem); Object value = new Object(); assertNull(cache.get(key)); try { service.earlyPutWithException(keyItem, value, true); fail("Should have thrown an exception"); } catch (UnsupportedOperationException e) { // This is what we expect } Cache.ValueWrapper result = cache.get(key); assertNotNull(result); assertEquals(value, result.get()); }
Example 10
Source File: AbstractJCacheAnnotationTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void removeWithExceptionVetoRemove() { String keyItem = name.getMethodName(); Cache cache = getCache(DEFAULT_CACHE); Object key = createKey(keyItem); Object value = new Object(); cache.put(key, value); try { service.removeWithException(keyItem, false); fail("Should have thrown an exception"); } catch (NullPointerException e) { // This is what we expect } Cache.ValueWrapper wrapper = cache.get(key); assertNotNull(wrapper); assertEquals(value, wrapper.get()); }
Example 11
Source File: CacheResultInterceptor.java From java-technology-stack with MIT License | 5 votes |
@Override @Nullable protected Object invoke( CacheOperationInvocationContext<CacheResultOperation> context, CacheOperationInvoker invoker) { CacheResultOperation operation = context.getOperation(); Object cacheKey = generateKey(context); Cache cache = resolveCache(context); Cache exceptionCache = resolveExceptionCache(context); if (!operation.isAlwaysInvoked()) { Cache.ValueWrapper cachedValue = doGet(cache, cacheKey); if (cachedValue != null) { return cachedValue.get(); } checkForCachedException(exceptionCache, cacheKey); } try { Object invocationResult = invoker.invoke(); doPut(cache, cacheKey, invocationResult); return invocationResult; } catch (CacheOperationInvoker.ThrowableWrapper ex) { Throwable original = ex.getOriginal(); cacheException(exceptionCache, operation.getExceptionTypeFilter(), cacheKey, original); throw ex; } }
Example 12
Source File: ThymeleafTemplateSupportImpl.java From yes-cart with Apache License 2.0 | 5 votes |
@Override public V get(K key) { final Cache.ValueWrapper vw = cache.get(key); if (vw != null) { return (V) vw.get(); } return null; }
Example 13
Source File: CacheResultInterceptor.java From java-technology-stack with MIT License | 5 votes |
/** * Check for a cached exception. If the exception is found, throw it directly. */ protected void checkForCachedException(@Nullable Cache exceptionCache, Object cacheKey) { if (exceptionCache == null) { return; } Cache.ValueWrapper result = doGet(exceptionCache, cacheKey); if (result != null) { Throwable ex = (Throwable) result.get(); Assert.state(ex != null, "No exception in cache"); throw rewriteCallStack(ex, getClass().getName(), "invoke"); } }
Example 14
Source File: CachedDAOImpl.java From icure-backend with GNU General Public License v2.0 | 5 votes |
@Override public List<T> getList(Collection<String> ids) { List<String> missingKeys = new ArrayList<>(); ArrayList<T> result = new ArrayList<>(); // Get cached values for (String id : ids) { Cache.ValueWrapper value = cache.get(getFullId(id)); if (value != null) { if (value.get() != null) { result.add((T) value.get()); } } else { missingKeys.add(id); } } // Get missing values from storage if (!missingKeys.isEmpty()) { List<T> entities = super.getList(missingKeys).stream().filter(Objects::nonNull).collect(Collectors.toList()); for (T e : entities) { cache.put(getFullId(keyManager.getKey(e)), e); } result.addAll(entities); } return result; }
Example 15
Source File: CaffeineCacheTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testPutIfAbsentNullValue() throws Exception { CaffeineCache cache = getCache(); Object key = new Object(); Object value = null; assertNull(cache.get(key)); assertNull(cache.putIfAbsent(key, value)); assertEquals(value, cache.get(key).get()); Cache.ValueWrapper wrapper = cache.putIfAbsent(key, "anotherValue"); assertNotNull(wrapper); // A value is set but is 'null' assertEquals(null, wrapper.get()); assertEquals(value, cache.get(key).get()); // not changed }
Example 16
Source File: ThreeLevelCacheTemplate.java From n2o-framework with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public F execute(String firstLevelRegion, String secondLevelRegion, String thirdLevelRegion, Object firstKey, Object secondKey, Object thirdKey, ThreeLevelCacheCallback<F, S, T> callback) { Cache firstLevelCache = null; if (firstLevelRegion != null) { firstLevelCache = getCacheManager().getCache(firstLevelRegion); if (firstLevelCache != null) { Cache.ValueWrapper firstLevelCacheValueWrapper = firstLevelCache.get(firstKey); if (firstLevelCacheValueWrapper != null) { F f = (F) firstLevelCacheValueWrapper.get(); callback.doInFirstLevelCacheHit(f); return f; } } else { log.warn( "Cannot find cache named [" + firstLevelRegion + "] for ThreeLevelCacheTemplate"); } } Cache secondLevelCache = null; if (secondLevelRegion != null) { secondLevelCache = getCacheManager().getCache(secondLevelRegion); if (secondLevelCache != null) { Cache.ValueWrapper secondLevelCacheValueWrapper = secondLevelCache.get(secondKey); if (secondLevelCacheValueWrapper != null) { S secondLevelCacheValue = (S) secondLevelCacheValueWrapper.get(); if (secondLevelCacheValue != null) { callback.doInSecondLevelCacheHit(secondLevelCacheValue); return handleFirstCache(firstKey, secondLevelCacheValue, firstLevelCache, callback); } } } else { log.warn( "Cannot find cache named [" + secondLevelRegion + "] for ThreeLevelCacheTemplate"); } } Cache thirdLevelCache = null; if (thirdLevelRegion != null) { thirdLevelCache = getCacheManager().getCache(thirdLevelRegion); if (thirdLevelCache != null) { Cache.ValueWrapper thirdLevelCacheValueWrapper = thirdLevelCache.get(thirdKey); if (thirdLevelCacheValueWrapper != null) { T thirdLevelCacheValue = (T) thirdLevelCacheValueWrapper.get(); if (thirdLevelCacheValue != null) { callback.doInThirdLevelCacheHit(thirdLevelCacheValue); F result = handleSecondCache(firstKey, secondKey, callback, firstLevelCache, secondLevelCache, thirdLevelCacheValue); if (result != null) return result; } } } else { log.warn( "Cannot find cache named [" + thirdLevelRegion + "] for ThreeLevelCacheTemplate"); } } return handleThirdCache(firstKey, secondKey, thirdKey, callback, firstLevelCache, secondLevelCache, thirdLevelCache); }
Example 17
Source File: ResilientCartRepositoryImplTest.java From yes-cart with Apache License 2.0 | 4 votes |
@Test public void testGetShoppingCartFromCacheLoggedOutInactiveMutable() throws Exception { final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService"); final ShopService shopService = context.mock(ShopService.class, "shopService"); final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor"); final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor"); final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager"); final Cache cartCache = context.mock(Cache.class, "cartCache"); final Cache.ValueWrapper wrapper = context.mock(Cache.ValueWrapper.class, "wrapper"); final long modified = System.currentTimeMillis(); final byte[] cached = new byte[0]; final ShoppingCartImpl cachedCart = new ShoppingCartImpl() { @Override public long getModifiedTimestamp() { return modified - 121000L; } @Override public int getLogonState() { return ShoppingCart.SESSION_EXPIRED; } }; cachedCart.getShoppingContext().setCustomerEmail("[email protected]"); cachedCart.getShoppingContext().setShopId(111L); context.checking(new Expectations() {{ oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache)); oneOf(cartCache).get("IN-CACHE"); will(returnValue(wrapper)); oneOf(wrapper).get(); will(returnValue(cached)); oneOf(mockCartSerDes).restoreState(cached); will(returnValue(cachedCart)); }}); final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor) { @Override void storeAsynchronously(final ShoppingCart shoppingCart) { // If this cache is stale just update the state assertEquals(cachedCart.getGuid(), shoppingCart.getGuid()); assertNull(shoppingCart.getCustomerEmail()); } }; assertEquals(cachedCart, repo.getShoppingCart("IN-CACHE")); context.assertIsSatisfied(); }
Example 18
Source File: ResilientCartRepositoryImplTest.java From yes-cart with Apache License 2.0 | 4 votes |
@Test public void testGetShoppingCartFromCacheLoggedInInactiveMutable() throws Exception { final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService"); final ShopService shopService = context.mock(ShopService.class, "shopService"); final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor"); final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor"); final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager"); final Cache cartCache = context.mock(Cache.class, "cartCache"); final Cache.ValueWrapper wrapper = context.mock(Cache.ValueWrapper.class, "wrapper"); final long modified = System.currentTimeMillis(); final ShoppingCartImpl cachedCart = new ShoppingCartImpl() { @Override public long getModifiedTimestamp() { return modified - 121000L; } @Override public int getLogonState() { return ShoppingCart.LOGGED_IN; } }; cachedCart.getShoppingContext().setCustomerEmail("[email protected]"); cachedCart.getShoppingContext().setShopId(111L); final Shop shop = context.mock(Shop.class, "shop"); final byte[] cached = new byte[0]; context.checking(new Expectations() {{ oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache)); oneOf(cartCache).get("IN-CACHE"); will(returnValue(wrapper)); oneOf(wrapper).get(); will(returnValue(cached)); oneOf(mockCartSerDes).restoreState(cached); will(returnValue(cachedCart)); oneOf(cartUpdateProcessor).invalidateShoppingCart(cachedCart); oneOf(shopService).getById(111L); will(returnValue(shop)); oneOf(shop).getAttributeValueByCode(AttributeNamesKeys.Shop.CART_SESSION_EXPIRY_SECONDS); will(returnValue("120")); }}); final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor) { @Override void storeAsynchronously(final ShoppingCart shoppingCart) { // If this cache is stale just update the state assertEquals(cachedCart.getGuid(), shoppingCart.getGuid()); assertSame(cachedCart, shoppingCart); } }; assertSame(cachedCart, repo.getShoppingCart("IN-CACHE")); context.assertIsSatisfied(); }
Example 19
Source File: BookmarkServiceImpl.java From yes-cart with Apache License 2.0 | 4 votes |
private Pair<Long, String> getPairOfPkAndUriFromValueWrapper(final Cache.ValueWrapper wrapper) { if (wrapper != null) { return (Pair<Long, String>) wrapper.get(); } return null; }
Example 20
Source File: SafeCache.java From icure-backend with GNU General Public License v2.0 | 4 votes |
public V getIfPresent(K key) { Cache.ValueWrapper valueWrapper = cache.get(key); return (valueWrapper != null) ? (V) valueWrapper.get() : null; }