ReadCounterFromCacheAdvice extends CounterInCacheBase { @Around("readSingleCounter()") public Object readCounter(final ProceedingJoinPoint pjp) throws Throwable { if (isDisabled()) { getLogger().info("Cache disabled"); return pjp.proceed(); } String cacheKey = null; ReadCounterFromCache annotation; AnnotationData data; try { Method methodToCache = getCacheBase().getMethodToCache(pjp, ReadCounterFromCache.class); verifyMethodSignature(methodToCache); annotation = methodToCache.getAnnotation(ReadCounterFromCache.class); data = AnnotationDataBuilder.buildAnnotationData(annotation, ReadCounterFromCache.class, methodToCache); cacheKey = getCacheBase().getCacheKeyBuilder().getCacheKey(data, pjp.getArgs(), methodToCache.toString()); Long result = getCacheBase().getCache(data).getCounter(cacheKey); if (result != null) { getLogger().debug("Cache hit."); return convertResult(methodToCache, result); } } catch (Exception ex) { warn(ex, "Caching on method %s and key [%s] aborted due to an error.", pjp.toShortString(), cacheKey); return pjp.proceed(); } final Object result = pjp.proceed(); try { if (checkData(result, pjp)) { long value = ((Number) result).longValue(); getCacheBase().getCache(data).incr(cacheKey, 0, value, annotation.expiration()); } } catch (Exception ex) { warn(ex, "Caching on method %s and key [%s] aborted due to an error.", pjp.toShortString(), cacheKey); } return result; }  @Pointcut("@annotation(com.google.code.ssm.api.counter.ReadCounterFromCache)") void readSingleCounter(); @Around("readSingleCounter()") Object readCounter(final ProceedingJoinPoint pjp);  }
@Test public void validReadCounterCacheMiss() throws Throwable { Assume.assumeTrue(isValid); when(pjp.proceed()).thenReturn(expectedValue); when(cache.getCounter(eq(cacheKey))).thenReturn(null); assertEquals(expectedValue, advice.readCounter(pjp)); verify(cache).getCounter(eq(cacheKey)); verify(cache).incr(eq(cacheKey), eq(0), eq(((Number) expectedValue).longValue()), eq(EXPIRATION)); verify(pjp).proceed(); }
@Test public void validReadCounterCacheHit() throws Throwable { Assume.assumeTrue(isValid); Long value = 100L; when(cache.getCounter(eq(cacheKey))).thenReturn(value); assertEquals(value.intValue(), ((Number) advice.readCounter(pjp)).intValue()); verify(cache).getCounter(eq(cacheKey)); verify(cache, never()).incr(anyString(), anyInt(), anyLong(), anyInt()); verify(pjp, never()).proceed(); }
@Test public void invalidReadCounter() throws Throwable { Assume.assumeThat(isValid, CoreMatchers.is(false)); when(pjp.proceed()).thenReturn(expectedValue); assertEquals(expectedValue, advice.readCounter(pjp)); verify(cache, never()).getCounter(anyString()); verify(cache, never()).get(anyString(), any(SerializationType.class)); verify(cache, never()).incr(anyString(), anyInt(), anyLong(), anyInt()); verify(pjp).proceed(); }