@Test
  public void testDynamicMode() {
    CacheManager cm = new ConcurrentMapCacheManager();
    Cache cache1 = cm.getCache("c1");
    assertTrue(cache1 instanceof ConcurrentMapCache);
    Cache cache1again = cm.getCache("c1");
    assertSame(cache1again, cache1);
    Cache cache2 = cm.getCache("c2");
    assertTrue(cache2 instanceof ConcurrentMapCache);
    Cache cache2again = cm.getCache("c2");
    assertSame(cache2again, cache2);
    Cache cache3 = cm.getCache("c3");
    assertTrue(cache3 instanceof ConcurrentMapCache);
    Cache cache3again = cm.getCache("c3");
    assertSame(cache3again, cache3);

    cache1.put("key1", "value1");
    assertEquals("value1", cache1.get("key1").get());
    cache1.put("key2", 2);
    assertEquals(2, cache1.get("key2").get());
    cache1.put("key3", null);
    assertNull(cache1.get("key3").get());
    cache1.evict("key3");
    assertNull(cache1.get("key3"));
  }
  public void testConditionalCacheUpdate(CacheableService<?> service) {
    Integer one = Integer.valueOf(1);
    Integer three = Integer.valueOf(3);

    Cache cache = cm.getCache("default");
    assertEquals(one, Integer.valueOf(service.conditionalUpdate(one).toString()));
    assertNull(cache.get(one));

    assertEquals(three, Integer.valueOf(service.conditionalUpdate(three).toString()));
    assertEquals(three, Integer.valueOf(cache.get(three).get().toString()));
  }
  public void testCacheUpdate(CacheableService<?> service) {
    Object o = new Object();
    Cache cache = cm.getCache("default");
    assertNull(cache.get(o));
    Object r1 = service.update(o);
    assertSame(r1, cache.get(o).get());

    o = new Object();
    assertNull(cache.get(o));
    Object r2 = service.update(o);
    assertSame(r2, cache.get(o).get());
  }
  public void testMultiCache(CacheableService<?> service) {
    Object o1 = new Object();
    Object o2 = new Object();

    Cache primary = cm.getCache("primary");
    Cache secondary = cm.getCache("secondary");

    assertNull(primary.get(o1));
    assertNull(secondary.get(o1));
    Object r1 = service.multiCache(o1);
    assertSame(r1, primary.get(o1).get());
    assertSame(r1, secondary.get(o1).get());

    Object r2 = service.multiCache(o1);
    Object r3 = service.multiCache(o1);

    assertSame(r1, r2);
    assertSame(r1, r3);

    assertNull(primary.get(o2));
    assertNull(secondary.get(o2));
    Object r4 = service.multiCache(o2);
    assertSame(r4, primary.get(o2).get());
    assertSame(r4, secondary.get(o2).get());
  }
Esempio n. 5
0
 /**
  * 获得当前锁定的票数
  *
  * @param cacheManager
  * @param witRewardid
  * @return
  */
 public static int getLockedTicketNum(CacheManager cacheManager, String witRewardid) {
   Cache ticketindex = cacheManager.getCache(CacheConfig.CACHE_NAME_WIT_TICKET_LOCKED_INDEX);
   Cache ticketCache = cacheManager.getCache(CacheConfig.CACHE_NAME_WIT_TICKET_LOCKED);
   List<String> newTickets = new ArrayList<>();
   String json = ticketindex.get(witRewardid, String.class);
   if (json != null && !json.isEmpty()) {
     List<String> tickets = Json.fromJson(json, ArrayList.class);
     for (String t : tickets) {
       if (ticketCache.get(t) != null) {
         newTickets.add(t);
       }
     }
     ticketindex.put(witRewardid, Json.toJson(newTickets));
   }
   return newTickets.size();
 }
 public void testMethodName(CacheableService<?> service, String keyName) throws Exception {
   Object key = new Object();
   Object r1 = service.name(key);
   assertSame(r1, service.name(key));
   Cache cache = cm.getCache("default");
   // assert the method name is used
   assertNotNull(cache.get(keyName));
 }
 private void validateGuavaCacheWithStats() {
   GuavaCacheManager cacheManager = validateCacheManager(GuavaCacheManager.class);
   assertThat(cacheManager.getCacheNames(), containsInAnyOrder("foo", "bar"));
   assertThat(cacheManager.getCacheNames(), hasSize(2));
   Cache foo = cacheManager.getCache("foo");
   foo.get("1");
   assertThat(((GuavaCache) foo).getNativeCache().stats().missCount(), equalTo(1L));
 }
 @Test
 public void guavaCacheExplicitWithCaches() {
   load(DefaultCacheConfiguration.class, "spring.cache.type=guava", "spring.cache.cacheNames=foo");
   GuavaCacheManager cacheManager = validateCacheManager(GuavaCacheManager.class);
   Cache foo = cacheManager.getCache("foo");
   foo.get("1");
   // See next tests: no spec given so stats should be disabled
   assertThat(((GuavaCache) foo).getNativeCache().stats().missCount(), equalTo(0L));
 }
Esempio n. 9
0
 private Script compileIfNotCompiled(String scriptString, Context ctx) {
   ValueWrapper vw = scriptCache.get(scriptString);
   Script script = null;
   if (vw == null) {
     script = ctx.compileString(scriptString, UUID.randomUUID().toString(), 0, null);
     scriptCache.put(scriptString, script);
   } else {
     script = (Script) vw.get();
   }
   return script;
 }
Esempio n. 10
0
 private Function compileIfNotCompiled(Context ctx, String funcStr) {
   ValueWrapper vw = funtionCache.get(funcStr);
   Function func = null;
   if (vw == null) {
     func = ctx.compileFunction(global, funcStr, null, 1, null);
     funtionCache.put(funcStr, func);
   } else {
     func = (Function) vw.get();
   }
   return func;
 }
  public void testMultiCacheAndEvict(CacheableService<?> service) {
    String methodName = "multiCacheAndEvict";

    Cache primary = cm.getCache("primary");
    Cache secondary = cm.getCache("secondary");
    Object key = Integer.valueOf(1);

    secondary.put(key, key);

    assertNull(secondary.get(methodName));
    assertSame(key, secondary.get(key).get());

    Object r1 = service.multiCacheAndEvict(key);
    assertSame(r1, service.multiCacheAndEvict(key));

    // assert the method name is used
    assertSame(r1, primary.get(methodName).get());
    assertNull(secondary.get(methodName));
    assertNull(secondary.get(key));
  }
 /** Collect agent system data every second. */
 @Scheduled(fixedDelay = 1000)
 public void collectAgentSystemData() {
   Ehcache nativeCache = (Ehcache) agentMonioringTargetsCache.getNativeCache();
   List<String> keysWithExpiryCheck = convert(nativeCache.getKeysWithExpiryCheck());
   for (String each : keysWithExpiryCheck) {
     ValueWrapper value = agentMonioringTargetsCache.get(each);
     if (value != null && value.get() != null) {
       writeObjectToFile(
           getAgentPath(each), getAgentManager().getSystemDataModel((AgentIdentity) value.get()));
     }
   }
 }
  private <T, E extends Throwable> T getValue(Callback<T, E> callback, Cache cache, Object key)
      throws E {
    @Nullable final Cache.ValueWrapper valueWrapper = cache.get(key);
    if (valueWrapper != null) {
      return cast(valueWrapper.get());
    }

    final T loadedValue = callback.call();
    putValue(cache, key, loadedValue);

    return loadedValue;
  }
  public UserDetails getUserFromCache(String username) {
    Cache.ValueWrapper element = username != null ? cache.get(username) : null;

    if (logger.isDebugEnabled()) {
      logger.debug("Cache hit: " + (element != null) + "; username: " + username);
    }

    if (element == null) {
      return null;
    } else {
      return (UserDetails) element.get();
    }
  }
  @Test
  public void getAndPut() {
    cache.clear();

    long key = 1;
    Long value = service.getAndPut(key);

    assertEquals("Wrong value for @Cacheable key", value, cache.get(key).get());
    assertEquals(
        "Wrong value for @CachePut key", value, cache.get(value + 100).get()); // See @CachePut

    // CachePut forced a method call
    Long anotherValue = service.getAndPut(key);
    assertNotSame(value, anotherValue);
    // NOTE: while you might expect the main key to have been updated, it hasn't. @Cacheable
    // operations
    // are only processed in case of a cache miss. This is why combining @Cacheable with @CachePut
    // is a very bad idea. We could refine the condition now that we can figure out if we are going
    // to invoke the method anyway but that brings a whole new set of potential regressions.
    // assertEquals("Wrong value for @Cacheable key", anotherValue, cache.get(key).get());
    assertEquals(
        "Wrong value for @CachePut key", anotherValue, cache.get(anotherValue + 100).get());
  }
  public void testMultiConditionalCacheAndEvict(CacheableService<?> service) {
    Cache primary = cm.getCache("primary");
    Cache secondary = cm.getCache("secondary");
    Object key = Integer.valueOf(1);

    secondary.put(key, key);

    assertNull(primary.get(key));
    assertSame(key, secondary.get(key).get());

    Object r1 = service.multiConditionalCacheAndEvict(key);
    Object r3 = service.multiConditionalCacheAndEvict(key);

    assertTrue(!r1.equals(r3));
    assertNull(primary.get(key));

    Object key2 = Integer.valueOf(3);
    Object r2 = service.multiConditionalCacheAndEvict(key2);
    assertSame(r2, service.multiConditionalCacheAndEvict(key2));

    // assert the method name is used
    assertSame(r2, primary.get(key2).get());
    assertNull(secondary.get(key2));
  }
Esempio n. 17
0
 public static boolean locketTicket(
     CacheManager cacheManager, String witRewardid, String witOrderId) {
   Cache ticketindex = cacheManager.getCache(CacheConfig.CACHE_NAME_WIT_TICKET_LOCKED_INDEX);
   Cache ticketCache = cacheManager.getCache(CacheConfig.CACHE_NAME_WIT_TICKET_LOCKED);
   ticketCache.put(witOrderId, witOrderId);
   String json = ticketindex.get(witRewardid, String.class);
   List<String> tickets;
   if (json != null && !json.isEmpty()) {
     tickets = Json.fromJson(json, ArrayList.class);
   } else {
     tickets = new ArrayList<>();
   }
   tickets.add(witOrderId);
   ticketindex.put(witRewardid, Json.toJson(tickets));
   return true;
 }
  public void testMultiPut(CacheableService<?> service) {
    Object o = Integer.valueOf(1);

    Cache primary = cm.getCache("primary");
    Cache secondary = cm.getCache("secondary");

    assertNull(primary.get(o));
    assertNull(secondary.get(o));
    Object r1 = service.multiUpdate(o);
    assertSame(r1, primary.get(o).get());
    assertSame(r1, secondary.get(o).get());

    o = Integer.valueOf(2);
    assertNull(primary.get(o));
    assertNull(secondary.get(o));
    Object r2 = service.multiUpdate(o);
    assertSame(r2, primary.get(o).get());
    assertSame(r2, secondary.get(o).get());
  }
Esempio n. 19
0
  @SuppressWarnings("unchecked")
  public <T> T get(String key) {
    if (!canCache()) return null;
    ValueWrapper value = cache.get(key);
    if (value == null) return null;
    CacheElement ce = (CacheElement) value.get();

    if (!ce.isIndate()) {
      logger.info("clear cache by key: " + ce);
      return null;
    }

    if (logger.isInfoEnabled()) {
      logger.info("get from cache by key: " + ce);
    }

    return (T) ce.getValue();
  }
  @Override
  public CsrfToken loadToken(HttpServletRequest request) {

    String token = Strings.clean(request.getParameter(parameterName));

    if (token == null) {
      token = Strings.clean(request.getHeader(headerName));
    }

    if (token == null) {
      return null;
    }

    try {
      Jws<Claims> jws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token);

      // signature is valid, now let's ensure it hasn't been submitted before:

      String id = jws.getBody().getId();

      String usedNonce = null;

      Cache.ValueWrapper wrapper = nonceCache.get(id);
      if (wrapper != null) {
        Object val = wrapper.get();
        if (val != null) {
          usedNonce = val.toString();
        }
      }

      if (usedNonce == null) {
        // CSRF token hasn't been used yet, mark it as used:
        nonceCache.put(id, token);

        return new DefaultCsrfToken(headerName, parameterName, token);
      }
    } catch (Exception e) {
      log.debug(
          "CSRF token is invalid (this is likely to happen and not necessarily an error condition).",
          e);
    }

    return null;
  }
Esempio n. 21
0
  /**
   * Handles the GET request for downloading an artifact.
   *
   * @param downloadId the generated download id
   * @param response of the servlet
   * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if successful
   */
  @RequestMapping(method = RequestMethod.GET, value = RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING)
  @ResponseBody
  public ResponseEntity<Void> downloadArtifactByDownloadId(
      @PathVariable final String downloadId, final HttpServletResponse response) {
    try {
      final ValueWrapper cacheWrapper = cache.get(downloadId);
      if (cacheWrapper == null) {
        LOGGER.warn("Download Id {} could not be found", downloadId);
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
      }

      final DownloadArtifactCache artifactCache = (DownloadArtifactCache) cacheWrapper.get();
      DbArtifact artifact = null;
      switch (artifactCache.getDownloadType()) {
        case BY_SHA1:
          artifact = artifactRepository.getArtifactBySha1(artifactCache.getId());
          break;

        default:
          LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType());
          break;
      }

      if (artifact == null) {
        LOGGER.warn(
            "Artifact with cached id {} and download type {} could not be found.",
            artifactCache.getId(),
            artifactCache.getDownloadType());
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
      }
      try {
        IOUtils.copy(artifact.getFileInputStream(), response.getOutputStream());
      } catch (final IOException e) {
        LOGGER.error("Cannot copy streams", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
      }
    } finally {
      cache.evict(downloadId);
    }

    return ResponseEntity.ok().build();
  }
  public void testEvictAll(CacheableService<?> service) throws Exception {
    Object o1 = new Object();

    Object r1 = service.cache(o1);
    Object r2 = service.cache(o1);

    Object o2 = new Object();
    Object r10 = service.cache(o2);

    assertSame(r1, r2);
    assertNotSame(r1, r10);
    service.evictAll(new Object());
    Cache cache = cm.getCache("default");
    assertNull(cache.get(o1));
    assertNull(cache.get(o2));

    Object r3 = service.cache(o1);
    Object r4 = service.cache(o1);
    assertNotSame(r1, r3);
    assertSame(r3, r4);
  }
  protected CacheStatus inspectCacheables(Collection<CacheOperationContext> cacheables) {

    if (cacheables.isEmpty()) {
      return null;
    }

    Map<CacheOperationContext, Object> cUpdates =
        new LinkedHashMap<CacheOperationContext, Object>(cacheables.size());

    boolean trace = log.isTraceEnabled();
    boolean updateRequired = false;
    boolean atLeastOne = false;

    ValueWrapper valueWrapper = null;

    for (CacheOperationContext context : cacheables) {
      if (context.isConditionPassing()) {
        atLeastOne = true;
        Object key = context.generateKey();

        if (trace) {
          log.trace(
              "Computed cache key {} for operation {}", new Object[] {key, context.operation});
        }
        if (key == null) {
          throw new IllegalArgumentException(
              "Null key returned for cache operation (maybe you are using named params on classes without debug info?) "
                  + context.operation);
        }

        // add op/key (in case an update is discovered later on)
        cUpdates.put(context, key);

        boolean localCacheHit = false;

        // check whether the cache needs to be inspected or not (the method will be invoked anyway)
        if (!updateRequired) {
          for (Cache cache : context.getCaches()) {
            ValueWrapper wrapper = cache.get(key);
            if (wrapper != null) {
              valueWrapper = wrapper;
              localCacheHit = true;
              break;
            }
          }
        }

        if (!localCacheHit) {
          updateRequired = true;
        }
      } else {
        if (trace) {
          log.trace(
              "Cache condition failed on method {} for operation {}",
              new Object[] {context.method, context.operation});
        }
      }
    }

    // return a status only if at least one cacheable matched
    if (atLeastOne) {
      return new CacheStatus(cUpdates, updateRequired, valueWrapper);
    }

    return null;
  }
Esempio n. 24
0
 @Override
 public boolean checkAuthCode(String authCode) {
   return cache.get(authCode) != null;
 }
Esempio n. 25
0
 @Override
 public boolean checkAccessToken(String accessToken) {
   return cache.get(accessToken) != null;
 }
Esempio n. 26
0
 @Override
 public String getAccountByAuthCode(String authCode) {
   OAuthObject authObject = (OAuthObject) cache.get(authCode).get();
   return authObject == null ? null : authObject.getAccount();
 }
Esempio n. 27
0
 @Override
 public String getAccountByAccessToken(String accessToken) {
   OAuthObject authObject = (OAuthObject) cache.get(accessToken).get();
   return authObject == null ? null : authObject.getAccount();
 }
 @Override
 public T get(Object key) {
     Cache.ValueWrapper wrapper = cache.get(key);
     return wrapper == null ? null : (T)wrapper.get();
 }
 @Override
 public boolean contains(Object key) {
     return cache.get(key) != null;
 }