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());
  }
Beispiel #2
0
 public static boolean unLocketTicket(
     CacheManager cacheManager, String witRewardid, String witOrderId) {
   Cache ticketCache = cacheManager.getCache(CacheConfig.CACHE_NAME_WIT_TICKET_LOCKED);
   ticketCache.evict(witOrderId);
   getLockedTicketNum(cacheManager, witRewardid);
   return true;
 }
 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));
 }
 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));
 }
 /**
  * @param key
  * @throws Exception
  */
 public void deleteFromCache(String key) throws CacheOperationException {
   logger.info("delete obj from cache with key: " + key);
   Cache cache = getCache();
   if (!StringUtils.hasText(key)) {
     throw new CacheOperationException("No such key in cache. ");
   }
   cache.evict(key);
 }
 @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));
 }
  protected PageInfo buildNewPageInfo(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain,
      CacheStatus cacheStatus,
      Map<String, Collection<CacheOperationContext>> operationsByType)
      throws Exception {

    Timer timer = new Timer(getCachedUri(request));
    timer.start();

    String key = calculateKey(request);
    PageInfo pageInfo;
    try {
      // Page is not cached - build the response, cache it, and send to client
      pageInfo = buildPage(request, response, chain);
      if (pageInfo.isOk()) {
        Object noCache = pageInfo.getCacheDirectives().get("no-cache");
        if (noCache instanceof Boolean && ((Boolean) noCache)) {
          log.debug("Response ok but Cache-Control: no-cache is present, not caching");
          releaseCacheLocks(operationsByType, key);
        } else {
          Collection<Cache> caches = new ArrayList<Cache>();
          for (CacheOperationContext operationContext : operationsByType.get(UPDATE)) {
            for (Cache cache : operationContext.getCaches()) {
              caches.add(cache);
            }
          }
          update(caches, pageInfo, cacheStatus, key);
        }
      } else {
        for (CacheOperationContext operationContext : operationsByType.get(UPDATE)) {
          for (Cache cache : operationContext.getCaches()) {
            log.debug(
                "Response not ok ({}). Putting null into cache {} with key {}",
                pageInfo.getStatusCode(),
                cache.getName(),
                key);
          }
        }
        releaseCacheLocks(operationsByType, key);
      }
    } catch (Exception e) {
      if ("net.sf.ehcache.constructs.blocking.LockTimeoutException"
          .equals(e.getClass().getName())) {
        // do not release the lock, because you never acquired it
        throw e;
      }
      // Must unlock the cache if the above fails. Will be logged at Filter
      releaseCacheLocks(operationsByType, key);
      throw e;
    }

    timer.stop(false);
    response.addHeader(X_CACHED, String.valueOf(false));
    return pageInfo;
  }
 /**
  * @param key
  * @throws Exception
  */
 public void setToCache(String key, Object value) throws CacheOperationException {
   logger.info("set obj to cache with key: " + key);
   Cache cache = getCache();
   if (!StringUtils.hasText(key)) {
     logger.error("Key is empty when setToCache Operation. ");
     throw new CacheOperationException("Key is empty when setToCache Operation. ");
   }
   cache.put(key, value);
 }
  public boolean destroyCache(String name) {
    Cache cache = caches.remove(name);
    if (cache != null) {
      // TODO remove Redis backing store
      cache.clear();
    }

    return true;
  }
  @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()));
  }
Beispiel #12
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;
 }
Beispiel #13
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;
 }
 /** 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()));
     }
   }
 }
  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());
  }
 protected void update(
     Collection<Cache> caches, PageInfo pageInfo, CacheStatus cacheStatus, String key) {
   ValueWrapper element = cacheStatus == null ? null : cacheStatus.valueWrapper;
   Object maxAge = pageInfo.getCacheDirectives().get("max-age");
   int timeToLive =
       (maxAge instanceof Integer) ? ((Integer) maxAge) : (int) pageInfo.getTimeToLiveSeconds();
   for (Cache cache : caches) {
     log.debug(
         "Response ok. Adding to cache {} with key {} and ttl {}",
         cache.getName(),
         key,
         getTimeToLive(element));
     put(cache, key, pageInfo, timeToLive);
   }
 }
Beispiel #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;
 }
Beispiel #18
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();
 }
  protected boolean inspectCacheEvicts(
      Collection<CacheOperationContext> evictions, boolean beforeInvocation) {
    if (evictions.isEmpty()) {
      return false;
    }

    boolean trace = log.isTraceEnabled();

    boolean atLeastOne = false;
    for (CacheOperationContext operationContext : evictions) {
      CacheEvictOperation evict = (CacheEvictOperation) operationContext.operation;

      if (beforeInvocation == evict.isBeforeInvocation()) {
        if (operationContext.isConditionPassing()) {
          atLeastOne = true;
          // for each cache
          // lazy key initialization
          Object key = null;

          for (Cache cache : operationContext.getCaches()) {
            // cache-wide flush
            if (evict.isCacheWide()) {
              cache.clear();
              logRequestDetails(operationContext.request, getContext(), "Flushing request");
            } else {
              // check key
              if (key == null) {
                key = operationContext.generateKey();
              }
              if (trace) {
                log.trace(
                    "Invalidating cache key {} for operation {} on method {}",
                    key,
                    evict,
                    operationContext.method);
              }
              cache.evict(key);
            }
          }
        } else {
          logRequestDetails(operationContext.request, getContext(), "Not flushing request");
        }
      }
    }
    return atLeastOne;
  }
Beispiel #20
0
  public void put(String key, Object value, int expire) {
    if (!canCache() || value == null) return;
    CacheElement ce = CacheElement.create(key, value, expire);
    cache.put(key, ce);

    if (logger.isInfoEnabled()) {
      logger.info("put into cache: " + ce);
    }
  }
  @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;
  }
  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());
  }
 /**
  * Add the agent system data model share request on cache.
  *
  * @param id agent id in db.
  */
 @Override
 public void requestShareAgentSystemDataModel(Long id) {
   AgentInfo agent = getAgent(id, false);
   if (agent == null) {
     return;
   }
   agentRequestCache.put(
       extractRegionFromAgentRegion(agent.getRegion()) + "|" + createAgentKey(agent),
       new ClustedAgentRequest(agent.getIp(), agent.getName(), SHARE_AGENT_SYSTEM_DATA_MODEL));
 }
 /**
  * Stop agent. In cluster mode, it queues the agent stop request to agentRequestCache.
  *
  * @param id agent id in db
  */
 @Override
 public void stopAgent(Long id) {
   AgentInfo agent = getAgent(id, false);
   if (agent == null) {
     return;
   }
   agentRequestCache.put(
       extractRegionFromAgentRegion(agent.getRegion()) + "|" + createAgentKey(agent),
       new ClustedAgentRequest(agent.getIp(), agent.getName(), STOP_AGENT));
 }
  /**
   * 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();
  }
  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;
  }
Beispiel #27
0
  public static void main(String... args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    ClassroomService classroomService = context.getBean(ClassroomService.class);

    Teacher teacher = new Teacher(1, "Mert");
    Student student1 = new Student(2, "Tugce");

    Person personFetch1 = classroomService.getPerson(teacher);
    System.out.println(personFetch1);

    Person personFetch2 = classroomService.getPerson(student1);
    System.out.println(personFetch2);

    CacheManager cacheManager = context.getBean(CacheManager.class);
    Cache students = cacheManager.getCache("students");
    System.out.println(
        "students cache storage: " + ((ConcurrentHashMap) students.getNativeCache()).values());
    Cache teachers = cacheManager.getCache("teachers");
    System.out.println(
        "teachers cache storage: " + ((ConcurrentHashMap) teachers.getNativeCache()).values());
  }
  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);
  }
  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());
  }