org.springframework.cache.Cache

Here are the examples of the java api org.springframework.cache.Cache taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

525 Examples 7

19 View Source File : CacheManagerUtil.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

public void evictCache(String cacheName, String key) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache != null) {
        cache.evict(key);
    }
}

19 View Source File : CacheManagerUtil.java
License : GNU Affero General Public License v3.0
Project Creator : zycSummer

public void putCache(String cacheName, String key, Object value) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache != null) {
        cache.put(key, value);
    }
}

19 View Source File : MyRedisCacheManager.java
License : Apache License 2.0
Project Creator : Zoctan

@Override
public Cache getCache(@NonNull final String name) {
    final Cache cache = super.getCache(name);
    return new RedisCacheWrapper(cache);
}

19 View Source File : CaffeineCacheManager.java
License : Apache License 2.0
Project Creator : zhouxx

@Override
@Nullable
public Cache getCache(String name) {
    Cache cache = this.cacheMap.get(name);
    if (cache == null && this.dynamic) {
        synchronized (this.cacheMap) {
            cache = this.cacheMap.get(name);
            if (cache == null) {
                cache = createCaffeineCache(name);
                this.cacheMap.put(name, cache);
            }
        }
    }
    return cache;
}

19 View Source File : DemoCacheErrorHandler.java
License : MIT License
Project Creator : ZeroOrInfinity

@Override
public void handleCachePutError(@NonNull RuntimeException e, @NonNull Cache cache, @NonNull Object key, Object value) {
    log.error("redis异常:cacheName={}, key={}", cache.getName(), key, e);
}

19 View Source File : DemoCacheErrorHandler.java
License : MIT License
Project Creator : ZeroOrInfinity

@Override
public void handleCacheGetError(@NonNull RuntimeException e, @NonNull Cache cache, @NonNull Object key) {
    log.error("redis异常:cacheName={}, key={}", cache.getName(), key, e);
}

19 View Source File : DemoCacheErrorHandler.java
License : MIT License
Project Creator : ZeroOrInfinity

@Override
public void handleCacheEvictError(@NonNull RuntimeException e, @NonNull Cache cache, @NonNull Object key) {
    log.error("redis异常:cacheName={}, key={}", cache.getName(), key, e);
}

19 View Source File : DemoCacheErrorHandler.java
License : MIT License
Project Creator : ZeroOrInfinity

@Override
public void handleCacheClearError(@NonNull RuntimeException e, @NonNull Cache cache) {
    log.error("redis异常:cacheName={}, ", cache.getName(), e);
}

19 View Source File : SampleCacheApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void validateCache() {
    Cache countries = this.cacheManager.getCache("countries");
    replacedertThat(countries).isNotNull();
    // Simple test replaceduming the cache is empty
    countries.clear();
    replacedertThat(countries.get("BE")).isNull();
    Country be = this.countryRepository.findByCode("BE");
    replacedertThat((Country) countries.get("BE").get()).isEqualTo(be);
}

19 View Source File : CacheAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void couchbaseCacheExplicitWithTtl() {
    this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.clreplaced).withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", "spring.cache.couchbase.expiration=2000").run((context) -> {
        CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.clreplaced);
        replacedertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
        Cache cache = cacheManager.getCache("foo");
        replacedertThat(cache).isInstanceOf(CouchbaseCache.clreplaced);
        replacedertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(2);
        replacedertThat(((CouchbaseCache) cache).getNativeCache()).isEqualTo(context.getBean("bucket"));
    });
}

19 View Source File : CacheAutoConfigurationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void couchbaseCacheExplicitWithCaches() {
    this.contextRunner.withUserConfiguration(CouchbaseCacheConfiguration.clreplaced).withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar").run((context) -> {
        CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.clreplaced);
        replacedertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar");
        Cache cache = cacheManager.getCache("foo");
        replacedertThat(cache).isInstanceOf(CouchbaseCache.clreplaced);
        replacedertThat(((CouchbaseCache) cache).getTtl()).isEqualTo(0);
        replacedertThat(((CouchbaseCache) cache).getNativeCache()).isEqualTo(context.getBean("bucket"));
    });
}

19 View Source File : CachesEndpointWebIntegrationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void clearNamedCache() {
    Cache b = context.getBean("one", CacheManager.clreplaced).getCache("b");
    b.put("test", "value");
    client.delete().uri("/actuator/caches/b").exchange().expectStatus().isNoContent();
    replacedertThat(b.get("test")).isNull();
}

19 View Source File : CachesEndpointTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void clearCacheWithUnknownCache() {
    Cache a = mockCache("a");
    CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a)));
    replacedertThat(endpoint.clearCache("unknown", null)).isFalse();
    verify(a, never()).clear();
}

19 View Source File : CachesEndpointTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void clearCache() {
    Cache a = mockCache("a");
    Cache b = mockCache("b");
    CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b)));
    replacedertThat(endpoint.clearCache("a", null)).isTrue();
    verify(a).clear();
    verify(b, never()).clear();
}

19 View Source File : CachesEndpointTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void clearCacheWithSeveralCacheManagersWithCacheManagerFilter() {
    Map<String, CacheManager> cacheManagers = new LinkedHashMap<>();
    Cache a = mockCache("a");
    Cache b = mockCache("b");
    cacheManagers.put("test", cacheManager(a, b));
    Cache anotherA = mockCache("a");
    cacheManagers.put("another", cacheManager(anotherA));
    CachesEndpoint endpoint = new CachesEndpoint(cacheManagers);
    replacedertThat(endpoint.clearCache("a", "another")).isTrue();
    verify(a, never()).clear();
    verify(anotherA).clear();
    verify(b, never()).clear();
}

19 View Source File : CachesEndpointTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void clearAllCaches() {
    Cache a = mockCache("a");
    Cache b = mockCache("b");
    CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a, b)));
    endpoint.clearCaches();
    verify(a).clear();
    verify(b).clear();
}

19 View Source File : CachesEndpointTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private Cache mockCache(String name) {
    Cache cache = mock(Cache.clreplaced);
    given(cache.getName()).willReturn(name);
    given(cache.getNativeCache()).willReturn(new Object());
    return cache;
}

19 View Source File : CachesEndpointTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void clearCacheWithUnknownCacheManager() {
    Cache a = mockCache("a");
    CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", cacheManager(a)));
    replacedertThat(endpoint.clearCache("a", "unknown")).isFalse();
    verify(a, never()).clear();
}

19 View Source File : CacheMetricsRegistrar.java
License : Apache License 2.0
Project Creator : yuanmabiji

private Cache unwrapIfNecessary(Cache cache) {
    if (ClreplacedUtils.isPresent("org.springframework.cache.transaction.TransactionAwareCacheDecorator", getClreplaced().getClreplacedLoader())) {
        return TransactionAwareCacheDecoratorHandler.unwrapIfNecessary(cache);
    }
    return cache;
}

19 View Source File : CachesEndpoint.java
License : Apache License 2.0
Project Creator : yuanmabiji

private boolean clearCache(CacheEntry entry) {
    String cacheName = entry.getName();
    String cacheManager = entry.getCacheManager();
    Cache cache = this.cacheManagers.get(cacheManager).getCache(cacheName);
    if (cache != null) {
        cache.clear();
        return true;
    }
    return false;
}

19 View Source File : CheckRepeatSubmitInterceptor.java
License : Apache License 2.0
Project Creator : yang-cruise

/**
 * 校验重复提交拦截器
 * @author yangzongmin
 * @since 2020/6/16 15:52
 */
@Component
@SuppressWarnings("NullableProblems")
public clreplaced CheckRepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    @Resource(name = "checkRepeatSubmitCache")
    private Cache checkRepeatSubmitCache;

    @Resource
    private CheckRepeatSubmitStrategy checkRepeatSubmitStrategy;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        CheckRepeatSubmit checkRepeatSubmit = ((HandlerMethod) handler).getMethodAnnotation(CheckRepeatSubmit.clreplaced);
        if (Objects.nonNull(checkRepeatSubmit) && isRepeatSubmit(request)) {
            throw new BusinessException(HttpStatusEnum.REPEAT_SUBMIT_ERROR);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if (!(handler instanceof HandlerMethod)) {
            return;
        }
        CheckRepeatSubmit checkRepeatSubmit = ((HandlerMethod) handler).getMethodAnnotation(CheckRepeatSubmit.clreplaced);
        if (Objects.isNull(checkRepeatSubmit)) {
            return;
        }
        String key = checkRepeatSubmitStrategy.getCacheKey(request);
        if (StringUtils.isNotBlank(key)) {
            checkRepeatSubmitCache.evict(key);
        }
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String key = checkRepeatSubmitStrategy.getCacheKey(request);
        if (StringUtils.isBlank(key)) {
            return false;
        }
        if (Objects.isNull(checkRepeatSubmitCache.get(key))) {
            checkRepeatSubmitCache.put(key, 1);
            return false;
        }
        return true;
    }
}

19 View Source File : PersonalController.java
License : MIT License
Project Creator : wormhole

/**
 * 更新用户基础信息接口
 *
 * @param userVO
 * @param session
 * @return
 */
@ApiOperation(value = "更新用户基础信息接口", response = Result.clreplaced)
@RequestMapping(value = "/update_base", method = RequestMethod.POST)
@ResponseBody
public ResponseEnreplacedy updateBase(@ApiParam(name = "userVO", value = "用户VO对象") @Validated(UserVO.UpdateBaseGroup.clreplaced) @RequestBody UserVO userVO, HttpSession session) {
    User user = (User) session.getAttribute("user");
    // 校验邮箱是否重复
    if (!userVO.getEmail().equals(user.getEmail()) && userService.selectByCondition(new HashMap<String, Object>(16) {

        {
            put("email", userVO.getEmail());
        }
    }).size() != 0) {
        throw new BusinessException("邮箱已经存在");
    }
    User updateUser = new User();
    BeanUtils.copyProperties(userVO, updateUser);
    updateUser.setId(user.getId());
    // 删除缓存
    if (!updateUser.getEmail().equals(user.getEmail())) {
        Cache authenticationCache = redisCacheManager.getCache("authentication");
        authenticationCache.evict("shiro:authentication:" + user.getEmail());
        Cache authorizationCache = redisCacheManager.getCache("authorization");
        authorizationCache.evict("shiro:authorization:" + user.getEmail());
    }
    // 更新用户基础信息
    User newUser = userService.update(updateUser);
    session.setAttribute("user", newUser);
    Result result = new Result();
    result.setStatus(Result.SUCCESS);
    result.setMessage("基础信息修改成功");
    return new ResponseEnreplacedy(result, HttpStatus.OK);
}

19 View Source File : RequestScopedCacheManager.java
License : Apache License 2.0
Project Creator : WeBankPartners

@Override
public Cache getCache(String name) {
    final Map<String, Cache> cacheMap = threadLocalCache.get();
    Cache cache = cacheMap.get(name);
    if (cache == null) {
        cache = createCache(name);
        cacheMap.put(name, cache);
    }
    return cache;
}

19 View Source File : CacheUtils.java
License : Apache License 2.0
Project Creator : WeBankPartners

public static Object cacheLocaleCall(CacheManager cacheManager, String cacheName, Object key, Callable process) {
    Cache cache = cacheManager.getCache(cacheName);
    Cache.ValueWrapper vw = cache.get(key);
    if (vw != null && vw.get() != null) {
        return vw.get();
    }
    Object result = null;
    try {
        result = process.call();
    } catch (Exception ex) {
        throw new CmdbException("Exception happen ", ex);
    }
    cache.put(key, result);
    return result;
}

19 View Source File : UserService.java
License : Apache License 2.0
Project Creator : WeBankFinTech

public Boolean deleteAllUserCache() {
    log.info("delete all user cache");
    Cache cache = cacheManager.getCache("user");
    if (cache != null) {
        cache.clear();
    }
    return true;
}

19 View Source File : UserService.java
License : Apache License 2.0
Project Creator : WeBankFinTech

public Boolean deleteAllCredentialCache() {
    log.info("delete all Credential cache");
    Cache cache = cacheManager.getCache("getCredentials");
    if (cache != null) {
        cache.clear();
    }
    return true;
}

19 View Source File : CachingResourceTransformer.java
License : MIT License
Project Creator : Vip-Augus

/**
 * A {@link org.springframework.web.servlet.resource.ResourceTransformer} that checks a
 * {@link org.springframework.cache.Cache} to see if a previously transformed resource
 * exists in the cache and returns it if found, and otherwise delegates to the resolver
 * chain and saves the result in the cache.
 *
 * @author Rossen Stoyanchev
 * @since 4.1
 */
public clreplaced CachingResourceTransformer implements ResourceTransformer {

    private static final Log logger = LogFactory.getLog(CachingResourceTransformer.clreplaced);

    private final Cache cache;

    public CachingResourceTransformer(Cache cache) {
        replacedert.notNull(cache, "Cache is required");
        this.cache = cache;
    }

    public CachingResourceTransformer(CacheManager cacheManager, String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new IllegalArgumentException("Cache '" + cacheName + "' not found");
        }
        this.cache = cache;
    }

    /**
     * Return the configured {@code Cache}.
     */
    public Cache getCache() {
        return this.cache;
    }

    @Override
    public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {
        Resource transformed = this.cache.get(resource, Resource.clreplaced);
        if (transformed != null) {
            logger.trace("Resource resolved from cache");
            return transformed;
        }
        transformed = transformerChain.transform(request, resource);
        this.cache.put(resource, transformed);
        return transformed;
    }
}

19 View Source File : ResourceHandlerRegistration.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Configure a chain of resource resolvers and transformers to use. This
 * can be useful, for example, to apply a version strategy to resource URLs.
 * <p>If this method is not invoked, by default only a simple
 * {@link PathResourceResolver} is used in order to match URL paths to
 * resources under the configured locations.
 * @param cacheResources whether to cache the result of resource resolution;
 * setting this to "true" is recommended for production (and "false" for
 * development, especially when applying a version strategy
 * @param cache the cache to use for storing resolved and transformed resources;
 * by default a {@link org.springframework.cache.concurrent.ConcurrentMapCache}
 * is used. Since Resources aren't serializable and can be dependent on the
 * application host, one should not use a distributed cache but rather an
 * in-memory cache.
 * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation
 * @since 4.1
 */
public ResourceChainRegistration resourceChain(boolean cacheResources, Cache cache) {
    this.resourceChainRegistration = new ResourceChainRegistration(cacheResources, cache);
    return this.resourceChainRegistration;
}

19 View Source File : EncodedResourceResolverTests.java
License : MIT License
Project Creator : Vip-Augus

@Before
public void setup() {
    Cache cache = new ConcurrentMapCache("resourceCache");
    VersionResourceResolver versionResolver = new VersionResourceResolver();
    versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy()));
    List<ResourceResolver> resolvers = new ArrayList<>();
    resolvers.add(new CachingResourceResolver(cache));
    resolvers.add(new EncodedResourceResolver());
    resolvers.add(versionResolver);
    resolvers.add(new PathResourceResolver());
    this.resolver = new DefaultResourceResolverChain(resolvers);
    this.locations = new ArrayList<>();
    this.locations.add(new ClreplacedPathResource("test/", getClreplaced()));
    this.locations.add(new ClreplacedPathResource("testalternatepath/", getClreplaced()));
}

19 View Source File : CachingResourceTransformer.java
License : MIT License
Project Creator : Vip-Augus

/**
 * A {@link ResourceTransformer} that checks a {@link Cache} to see if a
 * previously transformed resource exists in the cache and returns it if found,
 * or otherwise delegates to the resolver chain and caches the result.
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 */
public clreplaced CachingResourceTransformer implements ResourceTransformer {

    private static final Log logger = LogFactory.getLog(CachingResourceTransformer.clreplaced);

    private final Cache cache;

    public CachingResourceTransformer(Cache cache) {
        replacedert.notNull(cache, "Cache is required");
        this.cache = cache;
    }

    public CachingResourceTransformer(CacheManager cacheManager, String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new IllegalArgumentException("Cache '" + cacheName + "' not found");
        }
        this.cache = cache;
    }

    /**
     * Return the configured {@code Cache}.
     */
    public Cache getCache() {
        return this.cache;
    }

    @Override
    public Mono<Resource> transform(ServerWebExchange exchange, Resource resource, ResourceTransformerChain transformerChain) {
        Resource cachedResource = this.cache.get(resource, Resource.clreplaced);
        if (cachedResource != null) {
            if (logger.isTraceEnabled()) {
                logger.trace(exchange.getLogPrefix() + "Resource resolved from cache");
            }
            return Mono.just(cachedResource);
        }
        return transformerChain.transform(exchange, resource).doOnNext(transformed -> this.cache.put(resource, transformed));
    }
}

19 View Source File : ResourceHandlerRegistration.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Configure a chain of resource resolvers and transformers to use. This
 * can be useful, for example, to apply a version strategy to resource URLs.
 * <p>If this method is not invoked, by default only a simple
 * {@code PathResourceResolver} is used in order to match URL paths to
 * resources under the configured locations.
 * @param cacheResources whether to cache the result of resource resolution;
 * setting this to "true" is recommended for production (and "false" for
 * development, especially when applying a version strategy
 * @param cache the cache to use for storing resolved and transformed resources;
 * by default a {@link org.springframework.cache.concurrent.ConcurrentMapCache}
 * is used. Since Resources aren't serializable and can be dependent on the
 * application host, one should not use a distributed cache but rather an
 * in-memory cache.
 * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation
 */
public ResourceChainRegistration resourceChain(boolean cacheResources, Cache cache) {
    this.resourceChainRegistration = new ResourceChainRegistration(cacheResources, cache);
    return this.resourceChainRegistration;
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void putIfAbsent() {
    // no transactional support for putIfAbsent
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    Object key = new Object();
    replacedertNull(cache.putIfAbsent(key, "123"));
    replacedertEquals("123", target.get(key, String.clreplaced));
    replacedertEquals("123", cache.putIfAbsent(key, "456").get());
    // unchanged
    replacedertEquals("123", target.get(key, String.clreplaced));
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void evictTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    Object key = new Object();
    cache.put(key, "123");
    TransactionStatus status = this.txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
    cache.evict(key);
    replacedertEquals("123", target.get(key, String.clreplaced));
    this.txManager.commit(status);
    replacedertNull(target.get(key));
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void evictNonTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    Object key = new Object();
    cache.put(key, "123");
    cache.evict(key);
    replacedertNull(target.get(key));
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void putTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    TransactionStatus status = this.txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
    Object key = new Object();
    cache.put(key, "123");
    replacedertNull(target.get(key));
    this.txManager.commit(status);
    replacedertEquals("123", target.get(key, String.clreplaced));
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void putNonTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    Object key = new Object();
    cache.put(key, "123");
    replacedertEquals("123", target.get(key, String.clreplaced));
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void clearNonTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    Object key = new Object();
    cache.put(key, "123");
    cache.clear();
    replacedertNull(target.get(key));
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void getTargetCache() {
    Cache target = new ConcurrentMapCache("testCache");
    TransactionAwareCacheDecorator cache = new TransactionAwareCacheDecorator(target);
    replacedertSame(target, cache.getTargetCache());
}

19 View Source File : TransactionAwareCacheDecoratorTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void clearTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    Object key = new Object();
    cache.put(key, "123");
    TransactionStatus status = this.txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
    cache.clear();
    replacedertEquals("123", target.get(key, String.clreplaced));
    this.txManager.commit(status);
    replacedertNull(target.get(key));
}

19 View Source File : JCacheKeyGeneratorTests.java
License : MIT License
Project Creator : Vip-Augus

/**
 * @author Stephane Nicoll
 */
public clreplaced JCacheKeyGeneratorTests {

    private TestKeyGenerator keyGenerator;

    private SimpleService simpleService;

    private Cache cache;

    @Before
    public void setup() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.clreplaced);
        this.keyGenerator = context.getBean(TestKeyGenerator.clreplaced);
        this.simpleService = context.getBean(SimpleService.clreplaced);
        this.cache = context.getBean(CacheManager.clreplaced).getCache("test");
    }

    @Test
    public void getSimple() {
        this.keyGenerator.expect(1L);
        Object first = this.simpleService.get(1L);
        Object second = this.simpleService.get(1L);
        replacedertSame(first, second);
        Object key = new SimpleKey(1L);
        replacedertEquals(first, cache.get(key).get());
    }

    @Test
    public void getFlattenVararg() {
        this.keyGenerator.expect(1L, "foo", "bar");
        Object first = this.simpleService.get(1L, "foo", "bar");
        Object second = this.simpleService.get(1L, "foo", "bar");
        replacedertSame(first, second);
        Object key = new SimpleKey(1L, "foo", "bar");
        replacedertEquals(first, cache.get(key).get());
    }

    @Test
    public void getFiltered() {
        this.keyGenerator.expect(1L);
        Object first = this.simpleService.getFiltered(1L, "foo", "bar");
        Object second = this.simpleService.getFiltered(1L, "foo", "bar");
        replacedertSame(first, second);
        Object key = new SimpleKey(1L);
        replacedertEquals(first, cache.get(key).get());
    }

    @Configuration
    @EnableCaching
    static clreplaced Config extends JCacheConfigurerSupport {

        @Bean
        @Override
        public CacheManager cacheManager() {
            return new ConcurrentMapCacheManager();
        }

        @Bean
        @Override
        public KeyGenerator keyGenerator() {
            return new TestKeyGenerator();
        }

        @Bean
        public SimpleService simpleService() {
            return new SimpleService();
        }
    }

    @CacheDefaults(cacheName = "test")
    public static clreplaced SimpleService {

        private AtomicLong counter = new AtomicLong();

        @CacheResult
        public Object get(long id) {
            return counter.getAndIncrement();
        }

        @CacheResult
        public Object get(long id, String... items) {
            return counter.getAndIncrement();
        }

        @CacheResult
        public Object getFiltered(@CacheKey long id, String... items) {
            return counter.getAndIncrement();
        }
    }

    private static clreplaced TestKeyGenerator extends SimpleKeyGenerator {

        private Object[] expectedParams;

        private void expect(Object... params) {
            this.expectedParams = params;
        }

        @Override
        public Object generate(Object target, Method method, Object... params) {
            replacedertTrue("Unexpected parameters: expected: " + Arrays.toString(this.expectedParams) + " but got: " + Arrays.toString(params), Arrays.equals(expectedParams, params));
            return new SimpleKey(params);
        }
    }
}

19 View Source File : JCacheErrorHandlerTests.java
License : MIT License
Project Creator : Vip-Augus

/**
 * @author Stephane Nicoll
 */
public clreplaced JCacheErrorHandlerTests {

    private Cache cache;

    private Cache errorCache;

    private CacheErrorHandler errorHandler;

    private SimpleService simpleService;

    @Before
    public void setup() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.clreplaced);
        this.cache = context.getBean("mockCache", Cache.clreplaced);
        this.errorCache = context.getBean("mockErrorCache", Cache.clreplaced);
        this.errorHandler = context.getBean(CacheErrorHandler.clreplaced);
        this.simpleService = context.getBean(SimpleService.clreplaced);
    }

    @Test
    public void getFail() {
        UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on get");
        Object key = SimpleKeyGenerator.generateKey(0L);
        willThrow(exception).given(this.cache).get(key);
        this.simpleService.get(0L);
        verify(this.errorHandler).handleCacheGetError(exception, this.cache, key);
    }

    @Test
    public void getPutNewElementFail() {
        UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put");
        Object key = SimpleKeyGenerator.generateKey(0L);
        given(this.cache.get(key)).willReturn(null);
        willThrow(exception).given(this.cache).put(key, 0L);
        this.simpleService.get(0L);
        verify(this.errorHandler).handleCachePutError(exception, this.cache, key, 0L);
    }

    @Test
    public void getFailPutExceptionFail() {
        UnsupportedOperationException exceptionOnPut = new UnsupportedOperationException("Test exception on put");
        Object key = SimpleKeyGenerator.generateKey(0L);
        given(this.cache.get(key)).willReturn(null);
        willThrow(exceptionOnPut).given(this.errorCache).put(key, SimpleService.TEST_EXCEPTION);
        try {
            this.simpleService.getFail(0L);
        } catch (IllegalStateException ex) {
            replacedertEquals("Test exception", ex.getMessage());
        }
        verify(this.errorHandler).handleCachePutError(exceptionOnPut, this.errorCache, key, SimpleService.TEST_EXCEPTION);
    }

    @Test
    public void putFail() {
        UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on put");
        Object key = SimpleKeyGenerator.generateKey(0L);
        willThrow(exception).given(this.cache).put(key, 234L);
        this.simpleService.put(0L, 234L);
        verify(this.errorHandler).handleCachePutError(exception, this.cache, key, 234L);
    }

    @Test
    public void evictFail() {
        UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict");
        Object key = SimpleKeyGenerator.generateKey(0L);
        willThrow(exception).given(this.cache).evict(key);
        this.simpleService.evict(0L);
        verify(this.errorHandler).handleCacheEvictError(exception, this.cache, key);
    }

    @Test
    public void clearFail() {
        UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on evict");
        willThrow(exception).given(this.cache).clear();
        this.simpleService.clear();
        verify(this.errorHandler).handleCacheClearError(exception, this.cache);
    }

    @Configuration
    @EnableCaching
    static clreplaced Config extends JCacheConfigurerSupport {

        @Bean
        @Override
        public CacheManager cacheManager() {
            SimpleCacheManager cacheManager = new SimpleCacheManager();
            cacheManager.setCaches(Arrays.asList(mockCache(), mockErrorCache()));
            return cacheManager;
        }

        @Bean
        @Override
        public CacheErrorHandler errorHandler() {
            return mock(CacheErrorHandler.clreplaced);
        }

        @Bean
        public SimpleService simpleService() {
            return new SimpleService();
        }

        @Bean
        public Cache mockCache() {
            Cache cache = mock(Cache.clreplaced);
            given(cache.getName()).willReturn("test");
            return cache;
        }

        @Bean
        public Cache mockErrorCache() {
            Cache cache = mock(Cache.clreplaced);
            given(cache.getName()).willReturn("error");
            return cache;
        }
    }

    @CacheDefaults(cacheName = "test")
    public static clreplaced SimpleService {

        private static final IllegalStateException TEST_EXCEPTION = new IllegalStateException("Test exception");

        private AtomicLong counter = new AtomicLong();

        @CacheResult
        public Object get(long id) {
            return this.counter.getAndIncrement();
        }

        @CacheResult(exceptionCacheName = "error")
        public Object getFail(long id) {
            throw TEST_EXCEPTION;
        }

        @CachePut
        public void put(long id, @CacheValue Object object) {
        }

        @CacheRemove
        public void evict(long id) {
        }

        @CacheRemoveAll
        public void clear() {
        }
    }
}

19 View Source File : JCacheCustomInterceptorTests.java
License : MIT License
Project Creator : Vip-Augus

/**
 * @author Stephane Nicoll
 */
public clreplaced JCacheCustomInterceptorTests {

    protected ConfigurableApplicationContext ctx;

    protected JCacheableService<?> cs;

    protected Cache exceptionCache;

    @Before
    public void setup() {
        ctx = new AnnotationConfigApplicationContext(EnableCachingConfig.clreplaced);
        cs = ctx.getBean("service", JCacheableService.clreplaced);
        exceptionCache = ctx.getBean("exceptionCache", Cache.clreplaced);
    }

    @After
    public void tearDown() {
        if (ctx != null) {
            ctx.close();
        }
    }

    @Test
    public void onlyOneInterceptorIsAvailable() {
        Map<String, JCacheInterceptor> interceptors = ctx.getBeansOfType(JCacheInterceptor.clreplaced);
        replacedertEquals("Only one interceptor should be defined", 1, interceptors.size());
        JCacheInterceptor interceptor = interceptors.values().iterator().next();
        replacedertEquals("Custom interceptor not defined", TestCacheInterceptor.clreplaced, interceptor.getClreplaced());
    }

    @Test
    public void customInterceptorAppliesWithRuntimeException() {
        Object o = cs.cacheWithException("id", true);
        // See TestCacheInterceptor
        replacedertEquals(55L, o);
    }

    @Test
    public void customInterceptorAppliesWithCheckedException() {
        try {
            cs.cacheWithCheckedException("id", true);
            fail("Should have failed");
        } catch (RuntimeException e) {
            replacedertNotNull("missing original exception", e.getCause());
            replacedertEquals(IOException.clreplaced, e.getCause().getClreplaced());
        } catch (Exception e) {
            fail("Wrong exception type " + e);
        }
    }

    @Configuration
    @EnableCaching
    static clreplaced EnableCachingConfig {

        @Bean
        public CacheManager cacheManager() {
            SimpleCacheManager cm = new SimpleCacheManager();
            cm.setCaches(Arrays.asList(defaultCache(), exceptionCache()));
            return cm;
        }

        @Bean
        public JCacheableService<?> service() {
            return new AnnotatedJCacheableService(defaultCache());
        }

        @Bean
        public Cache defaultCache() {
            return new ConcurrentMapCache("default");
        }

        @Bean
        public Cache exceptionCache() {
            return new ConcurrentMapCache("exception");
        }

        @Bean
        public JCacheInterceptor jCacheInterceptor(JCacheOperationSource cacheOperationSource) {
            JCacheInterceptor cacheInterceptor = new TestCacheInterceptor();
            cacheInterceptor.setCacheOperationSource(cacheOperationSource);
            return cacheInterceptor;
        }
    }

    /**
     * A test {@link org.springframework.cache.interceptor.CacheInterceptor} that handles special exception
     * types.
     */
    @SuppressWarnings("serial")
    static clreplaced TestCacheInterceptor extends JCacheInterceptor {

        @Override
        protected Object invokeOperation(CacheOperationInvoker invoker) {
            try {
                return super.invokeOperation(invoker);
            } catch (CacheOperationInvoker.ThrowableWrapper e) {
                Throwable original = e.getOriginal();
                if (original.getClreplaced() == UnsupportedOperationException.clreplaced) {
                    return 55L;
                } else {
                    throw new CacheOperationInvoker.ThrowableWrapper(new RuntimeException("wrapping original", original));
                }
            }
        }
    }
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void removeAllWithException() {
    Cache cache = getCache(DEFAULT_CACHE);
    Object key = createKey(name.getMethodName());
    cache.put(key, new Object());
    try {
        service.removeAllWithException(true);
        fail("Should have thrown an exception");
    } catch (UnsupportedOperationException e) {
    // This is what we expect
    }
    replacedertTrue(isEmpty(cache));
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void removeWithException() {
    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, true);
        fail("Should have thrown an exception");
    } catch (UnsupportedOperationException e) {
    // This is what we expect
    }
    replacedertNull(cache.get(key));
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void earlyPutWithExceptionVetoPut() {
    String keyItem = name.getMethodName();
    Cache cache = getCache(DEFAULT_CACHE);
    Object key = createKey(keyItem);
    Object value = new Object();
    replacedertNull(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);
    replacedertNotNull(result);
    replacedertEquals(value, result.get());
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void cacheNull() {
    Cache cache = getCache(DEFAULT_CACHE);
    String keyItem = name.getMethodName();
    replacedertNull(cache.get(keyItem));
    Object first = service.cacheNull(keyItem);
    Object second = service.cacheNull(keyItem);
    replacedertSame(first, second);
    Cache.ValueWrapper wrapper = cache.get(keyItem);
    replacedertNotNull(wrapper);
    replacedertSame(first, wrapper.get());
    replacedertNull("Cached value should be null", wrapper.get());
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void earlyRemoveWithException() {
    String keyItem = name.getMethodName();
    Cache cache = getCache(DEFAULT_CACHE);
    Object key = createKey(keyItem);
    Object value = new Object();
    cache.put(key, value);
    try {
        service.earlyRemoveWithException(keyItem, true);
        fail("Should have thrown an exception");
    } catch (UnsupportedOperationException e) {
    // This is what we expect
    }
    replacedertNull(cache.get(key));
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void earlyRemoveAllWithException() {
    Cache cache = getCache(DEFAULT_CACHE);
    Object key = createKey(name.getMethodName());
    cache.put(key, new Object());
    try {
        service.earlyRemoveAllWithException(true);
        fail("Should have thrown an exception");
    } catch (UnsupportedOperationException e) {
    // This is what we expect
    }
    replacedertTrue(isEmpty(cache));
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void earlyRemoveWithExceptionVetoRemove() {
    String keyItem = name.getMethodName();
    Cache cache = getCache(DEFAULT_CACHE);
    Object key = createKey(keyItem);
    Object value = new Object();
    cache.put(key, value);
    try {
        service.earlyRemoveWithException(keyItem, false);
        fail("Should have thrown an exception");
    } catch (NullPointerException e) {
    // This is what we expect
    }
    // This will be remove anyway as the earlyRemove has removed the cache before
    replacedertNull(cache.get(key));
}

19 View Source File : AbstractJCacheAnnotationTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void earlyPut() {
    String keyItem = name.getMethodName();
    Cache cache = getCache(DEFAULT_CACHE);
    Object key = createKey(keyItem);
    Object value = new Object();
    replacedertNull(cache.get(key));
    service.earlyPut(keyItem, value);
    Cache.ValueWrapper result = cache.get(key);
    replacedertNotNull(result);
    replacedertEquals(value, result.get());
}

See More Examples