/** {@inheritDoc} */
  @Override
  public boolean validateToken(TokenKey tokenKey, String token) throws TokenException {

    for (Object key : tokenCache.getKeys()) {
      logger.debug("KEY = " + key.toString());
      Element element = tokenCache.get(key);
      if (element != null) {
        logger.debug("Value = " + element.getObjectValue().toString());
      } else {
        logger.debug("No value found for  key: {}", key.toString());
      }
    }

    boolean foundMatch = false;
    Element element = tokenCache.get(tokenKey);
    if (element != null) {
      logger.debug("Cache hit for {} : {}", tokenKey);

      String value = (String) element.getObjectValue();

      if (value != null && value.equals(token)) {
        logger.debug("Cached token = {}", token);

        foundMatch = true;
      }
    } else {
      logger.debug("No Cache hit for {} : {}", tokenKey);
    }

    return foundMatch;
  }
Beispiel #2
0
  @Around("simplePointcut()")
  public Object aroundLogCalls(ProceedingJoinPoint joinPoint) throws Throwable {
    String targetName = joinPoint.getTarget().getClass().toString();
    String methodName = joinPoint.getSignature().getName();
    Object[] arguments = joinPoint.getArgs();

    // 试图得到标注的Ehcache类
    @SuppressWarnings("unused")
    Method[] methods = joinPoint.getTarget().getClass().getMethods();
    Ehcache flag = null;
    for (Method m : methods) {
      if (m.getName().equals(methodName)) {
        Class[] tmpCs = m.getParameterTypes();
        if (tmpCs.length == arguments.length) {
          flag = m.getAnnotation(Ehcache.class);
          break;
        }
      }
    }
    if (flag == null) {
      return null;
    }
    // Ehcache flag
    // =joinPoint.getTarget().getClass().getMethod(methodName).getAnnotation(Ehcache.class);
    Object result;
    String cacheKey = getCacheKey(targetName, methodName, arguments);

    Element element = null;
    if (flag.eternal()) {
      // 永久缓存
      element = dictCache.get(cacheKey);
    } else {
      // 临时缓存
      element = eternalCache.get(cacheKey);
    }

    if (element == null) {
      if ((arguments != null) && (arguments.length != 0)) {
        result = joinPoint.proceed(arguments);
      } else {
        result = joinPoint.proceed();
      }

      element = new Element(cacheKey, (Serializable) result);
      if (flag.eternal()) {
        // 永久缓存
        dictCache.put(element);
      } else {
        // 临时缓存
        eternalCache.put(element);
      }
    }
    return element.getValue();
  }
  @Test
  public void whenNotifiedOfLogInThenTopUpResultStatusShouldBeRemovedFromCache() {
    Element element =
        new Element(
            PLAYER_ID, new TopUpResultService.TopUpStatusCacheEntry(ACKNOWLEDGED, new DateTime()));
    topUpStatusCache.put(element);
    assertNotNull(topUpStatusCache.get(PLAYER_ID));

    underTest.clearTopUpStatus(PLAYER_ID);

    assertNull(topUpStatusCache.get(PLAYER_ID));
  }
  /** 主方法 如果某方法可被缓存就缓存其结果 方法结果必须是可序列化的(serializable) */
  public Object invoke(MethodInvocation invocation) throws Throwable {

    String targetName = invocation.getThis().getClass().getName();

    String methodName = invocation.getMethod().getName();

    Object[] arguments = invocation.getArguments();

    Object result;

    logger.info("在缓存中查找方法返回的对象!");

    String cacheKey = getCacheKey(targetName, methodName, arguments);

    Element element = cache.get(cacheKey);

    if (element == null) {

      logger.info("正在拦截方法!");

      result = invocation.proceed();

      logger.info("正在缓存对象!");

      element = new Element(cacheKey, (Serializable) result);

      cache.put(element);
    }

    return element.getValue();
  }
  @Override
  protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
    int size = cache.getSize();
    assertEquals(0, size);
    System.out.println("Client populating cache.");
    for (int i = 0; i < 7000; i++) {
      cache.put(new Element("key-" + i, "value-" + i));
    }
    System.out.println("Cache populate. Size: " + cache.getSize());
    // assert range as some may already have got evicted while populating
    // eviction is aggressive with new impl based on "evictUnexpiredEntries" with true by default
    assertRange(5000, 7000, cache);

    System.out.println("Sleeping for 3 mins (now=" + new Date() + ") ... ");
    // Sleep for TTI to kick in:
    Thread.sleep(3 * 60 * 1000);

    System.out.println("After sleeping 3 mins. Size: " + cache);
    // Now size should be equal to capacity
    assertRange(3000, 6000, cache);

    System.out.println("Trying to get on all elements, inline eviction should happen");
    // all others should be evicted inline
    for (int i = 0; i < 7000; i++) {
      Element element = cache.get("key-" + i);
      Assert.assertNull("Element should be null of key-" + i, element);
    }

    Thread.sleep(5 * 1000);

    System.out.println("After inline eviction. Size: " + cache.getSize());
    // Now size should be equal to 0
    assertEquals(0, cache.getSize());
  }
Beispiel #6
0
  @Test
  public void testConfigFileHonorsClusteringOff() {
    final CacheManager cacheManager =
        new CacheManager(
            CacheManager.class.getResourceAsStream("/terracotta/ehcache-event-replication.xml"));
    try {
      final Cache cache = cacheManager.getCache("replication");
      assertThat(cache, notNullValue());
      final TerracottaConfiguration terracottaConfiguration =
          cache.getCacheConfiguration().getTerracottaConfiguration();
      assertThat(terracottaConfiguration, notNullValue());
      assertThat(terracottaConfiguration.isClustered(), is(false));
      final List eventListenerConfigurations =
          cache.getCacheConfiguration().getCacheEventListenerConfigurations();
      assertThat(eventListenerConfigurations, notNullValue());
      assertThat(eventListenerConfigurations.size(), is(1));
      assertThat(
          ((CacheConfiguration.CacheEventListenerFactoryConfiguration)
                  eventListenerConfigurations.get(0))
              .getFullyQualifiedClassPath(),
          equalTo(TerracottaCacheEventReplicationFactory.class.getName()));
      cache.put(new Element("key", "value"));
      assertThat((String) cache.get("key").getValue(), equalTo("value"));

    } finally {
      cacheManager.shutdown();
    }
  }
  /**
   * Gets a parsed query for the passed in parameters. If the ParsedQuery requested has already been
   * created on this app node, it will retrieve it from a cache instead of recreating it. Use this
   * method instead of parseQuery if a cached copy is acceptable (almost always).
   *
   * @param db Database that the query will run against
   * @param toParse Query to be parsed.
   * @param session Database session.
   * @return a PreparedStatement to use.
   */
  public static ParsedQuery getParsedQuery(String db, Query toParse, Session session)
      throws FieldNotIndexedException {

    if (db == null || db.trim().equals("")) {
      throw new IllegalArgumentException("Query must be populated.");
    }
    if (toParse == null) {
      throw new IllegalArgumentException("Query cannot be null.");
    }
    final String key = db + ":" + toParse.getTable() + ":" + toParse.getWhere();
    // StopWatch pull = new StopWatch();
    // pull.start();
    Cache c = CacheFactory.getCache("parsedQuery");
    //        synchronized (CacheSynchronizer.getLockingObject(key, ParsedQuery.class))
    //        {
    Element e = c.get(key);
    // pull.stop();
    // logger.debug("Time to pull a parsed query from cache: " + pull.getTime());
    if (e == null) {
      logger.debug("Creating new ParsedQuery for: " + key);
      // StopWatch sw = new StopWatch();
      // sw.start();
      e = new Element(key, parseQuery(db, toParse, session));
      c.put(e);
      // sw.stop();
      // logger.debug("Time to create a new parsed query: " + sw.getTime());
    } else {
      logger.trace("Pulling ParsedQuery from Cache: " + e.getObjectValue().toString());
    }
    return (ParsedQuery) e.getObjectValue();
    // }
  }
  @Around("findTurmaEfetiva()")
  public Object findTurmaEfetivaMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = null;
    CacheManager cacheManager =
        CacheManager.create(new ClassPathResource("echache.xml").getInputStream());
    Cache cache = cacheManager.getCache("turmas-efetivas-cache");

    Object[] args = joinPoint.getArgs();

    Long turmaId = (Long) args[0];

    Element element = cache.get(turmaId);

    if (element == null) {
      result = joinPoint.proceed();
      cache.put(new Element(turmaId, result));

    } else {
      Logger.getLogger(this.getClass().getName())
          .log(
              Level.INFO,
              "Dados presentes no cache de turmas, não foi necessário acesso ao banco de dados");
      result = element.getValue();
    }
    return result;
  }
  @Override
  public Task getTask(TaskID taskID, boolean loadCompletely, boolean forceAPICall) {
    if (taskID == null) {
      throw new NullPointerException();
    }

    Task task;

    if (cacheActivated) {
      if (!forceAPICall) {
        Element element = cache.get(taskID);

        if (element != null) {
          task = (Task) element.getObjectValue();

          if (loadCompletely && !((Cachable) task).isCompletelyLoaded()) {
            task = getDataFactory().getTask(taskID, loadCompletely);
          }
        } else {
          task = getDataFactory().getTask(taskID, loadCompletely);
        }
      } else {
        task = getDataFactory().getTask(taskID, loadCompletely);
      }

      if (task != null) {
        cache.put(new Element(task.getID(), task));
      }
    } else {
      task = getDataFactory().getTask(taskID, loadCompletely);
    }

    return task;
  }
Beispiel #10
0
 public <T extends ISocioObject> void saveObject(T object) throws DuplicateMySocioObjectException {
   if (object instanceof IUniqueObject) {
     IUniqueObject uniqueObject = (IUniqueObject) object;
     Cache cache = cm.getCache("Objects");
     String key = uniqueObject.getUniqueFieldName() + uniqueObject.getUniqueFieldValue();
     Element element = cache.get(key);
     if (element != null) {
       ((SocioObject) object).setId((ObjectId) element.getValue());
       return;
     }
     @SuppressWarnings("unchecked")
     Query<T> q =
         (Query<T>)
             ds.createQuery(object.getClass())
                 .field(uniqueObject.getUniqueFieldName())
                 .equal(uniqueObject.getUniqueFieldValue());
     T objectT = (T) q.get();
     if (objectT != null) {
       ((SocioObject) object).setId(objectT.getId());
       element = new Element(key, objectT.getId());
       cache.put(element);
       logger.info(
           "Duplicate object of type: " + object.getClass() + " for query: " + q.toString());
       throw new DuplicateMySocioObjectException(
           "Duplicate object of type: " + object.getClass() + " for query: " + q.toString());
     }
   }
   ds.save(object);
 }
  /** 拦截 Service/DAO 的方法,并查找该结果是否存在,如果存在就返回 cache 中的值, 否则,返回数据库查询结果,并将查询结果放入 cache */
  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {

    String targetName = invocation.getThis().getClass().getName();

    String methodName = invocation.getMethod().getName();

    Object[] arguments = invocation.getArguments();

    Object result;

    String cacheKey = getCacheKey(targetName, methodName, arguments);

    logger.info("从[" + cache.getName() + "]查询key:[" + cacheKey + "]的缓存]");

    //    System.out.println("从["+cache.getName()+"]查询key:["+cacheKey+"]的缓存]");

    Element element = cache.get(cacheKey);

    if (element == null) {

      result = invocation.proceed();

      logger.info("key:[" + cacheKey + "]无缓存,创建缓存为[" + result + "]");

      //      System.out.println("key:["+cacheKey+"]无缓存,创建缓存为["+result+"]");

      element = new Element(cacheKey, (Serializable) result);

      cache.put(element);
    }

    return element.getObjectValue();
  }
Beispiel #12
0
 @Override
 public <T extends GeneralMessage> boolean isNewMessage(String userId, T message, Class<T> T) {
   Cache cache = cm.getCache("Messages");
   String key = message.getUniqueFieldValue() + userId;
   Element element = cache.get(key);
   if (element != null) {
     return (Boolean) element.getValue();
   }
   Query<UnreaddenMessage> isUnread =
       ds.createQuery(UnreaddenMessage.class)
           .field("userId")
           .equal(userId)
           .field("message")
           .equal(new Key<T>(T, message.getId()));
   Query<ReaddenMessage> isRead =
       ds.createQuery(ReaddenMessage.class)
           .field("userId")
           .equal(userId)
           .field("messageUniqueId")
           .equal(message.getUniqueFieldValue().toString());
   Boolean newMessage = isUnread.countAll() <= 0 && isRead.countAll() <= 0;
   element = new Element(key, new Boolean(false));
   cache.put(element);
   return newMessage;
 }
Beispiel #13
0
  /**
   * Test.
   *
   * @throws IOException e
   */
  @Test
  public void testCache() throws IOException {
    final String cacheName = "test 1";
    final CacheManager cacheManager = CacheManager.getInstance();
    cacheManager.addCache(cacheName);
    final String cacheName2 = "test 2";
    try {
      final Cache cache = cacheManager.getCache(cacheName);
      cache.put(new Element(1, Math.random()));
      cache.get(1);
      cache.get(0);
      cacheManager.addCache(cacheName2);
      final Cache cache2 = cacheManager.getCache(cacheName2);
      cache2.getCacheConfiguration().setOverflowToDisk(false);
      cache2.getCacheConfiguration().setEternal(true);
      cache2.getCacheConfiguration().setMaxElementsInMemory(0);

      // JavaInformations doit être réinstancié pour récupérer les caches
      final List<JavaInformations> javaInformationsList2 =
          Collections.singletonList(new JavaInformations(null, true));
      final HtmlReport htmlReport =
          new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer);
      htmlReport.toHtml(null, null);
      assertNotEmptyAndClear(writer);
      setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "false");
      htmlReport.toHtml(null, null);
      assertNotEmptyAndClear(writer);
    } finally {
      setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, null);
      cacheManager.removeCache(cacheName);
      cacheManager.removeCache(cacheName2);
    }
  }
 @Override
 public void doResponse() {
   // TODO Auto-generated method stub
   try {
     String platform = request.getParameter("p");
     platform = platform == null ? "android" : platform;
     String cacheIndex = REQUEST_TYPE + ",p:" + platform;
     UtilFunctions.serverLog("cacheIndex:" + cacheIndex);
     String responseData = null;
     Element element = null;
     if ((element = cache.get(cacheIndex)) != null /*cache.isKeyInCache(cacheIndex)*/) {
       responseData = (String) element.getValue();
       // System.out.println(REQUEST_TYPE+":缓存数据");
       UtilFunctions.serverLog(REQUEST_TYPE + CACHE_DATA);
     } else {
       VersionService versionService = (VersionService) context.getBean("versionService");
       Version version =
           versionService.getLatestVersion(
               platform == null ? VersionService.PLATFORM_ANDROID : platform);
       if (version == null) {
         UtilFunctions.serverLog(REQUEST_TYPE + "version is null");
         return;
       }
       responseData = version.getJSONObject().toString();
       cache.put(new Element(cacheIndex, responseData));
       // System.out.println(REQUEST_TYPE+":非缓存数据");
       UtilFunctions.serverLog(REQUEST_TYPE + NOT_CACHE_DATA);
     }
     PrintWriter pw = response.getWriter();
     pw.write(responseData);
     pw.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  @Around("findAllComPendendias()")
  public Object findAllTurmasComPendenciasMethodInterceptor(ProceedingJoinPoint joinPoint)
      throws Throwable {
    Object result = null;
    CacheManager cacheManager =
        CacheManager.create(new ClassPathResource("echache.xml").getInputStream());
    Cache cache = cacheManager.getCache("turmas-pendencias-cache");

    Object[] args = joinPoint.getArgs();

    if (args[0] == null || args[1] == null) {
      result = joinPoint.proceed();
      return result;
    }
    SimpleDateFormat df = new SimpleDateFormat("yyyy");
    String exercicio = df.format((Date) args[0]);
    String organizacao = ((Long) args[1]).toString();

    String key = exercicio + "-" + organizacao;
    Element element = cache.get(key);

    if (element == null) {
      result = joinPoint.proceed();
      cache.put(new Element(key, result));
    } else {
      Logger.getLogger(this.getClass().getName())
          .log(Level.INFO, "Dados presentes no cache, não foi necessário acesso ao banco de dados");
      result = element.getValue();
    }
    return result;
  }
  public static void main(String args[]) {

    Map<Object, Element> map = new HashMap<Object, Element>();
    List<String> list = new ArrayList<String>();

    // Create a cache manager
    CacheManager cacheManager = CacheManager.getInstance();

    // Creates a cache called newCache
    cacheManager.addCache("newCache");

    // Get cache called newCache
    Cache cache = cacheManager.getCache("newCache");
    StatisticsGateway stats = cache.getStatistics();

    // put into cache
    cache.put(new Element("1", "Monday"));
    list.add("1");
    cache.put(new Element("2", "Tuesday"));
    list.add("2");
    cache.put(new Element("3", "Wednesday"));
    list.add("3");
    cache.put(new Element("4", "Thursday"));
    list.add("4");

    // Displaying all elements
    System.out.println("All elements");
    map = cache.getAll(list);
    Iterator it = map.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      System.out.println(pair.getKey() + " = " + pair.getValue());
    }

    // Displaying elements and size of cache
    Element element = cache.get("1");
    System.out.println("Value of key 1 :" + element.getObjectValue().toString());
    System.out.println("Cache Size " + cache.getSize());
    element = cache.get("2");
    System.out.println("Value of key 2 :" + element.getObjectValue().toString());
    System.out.println("Cache Size " + cache.getSize());
    cache.removeElement(element);
    System.out.println("Cache Size after removing an element : " + cache.getSize());
    cache.flush();
    System.out.println("Removed Cache with key 3 :" + cache.remove("3"));
    System.out.println("Size after remove : " + cache.getSize());
  }
Beispiel #17
0
  /*
   * (non-Javadoc)
   *
   * @see net.jawr.web.cache.AbstractCacheManager#remove(java.lang.String)
   */
  public Object remove(String key) {

    Element element = cache.get(key);
    if (element != null) {
      cache.remove(key);
    }
    return element;
  }
 public void replace(String key, Object value, int expiration) {
   if (cache.get(key) == null) {
     return;
   }
   Element element = new Element(key, value);
   element.setTimeToLive(expiration);
   cache.put(element);
 }
Beispiel #19
0
  /*
   * (non-Javadoc)
   *
   * @see net.jawr.web.cache.AbstractCacheManager#get(java.lang.String)
   */
  public Object get(String key) {

    Element element = cache.get(key);
    if (element != null) {
      return element.getObjectValue();
    }
    return null;
  }
 @SuppressWarnings("unchecked")
 @Override
 public V getValue(K key) {
   Element element = cache.get(key);
   if (element != null) {
     return (V) element.getObjectValue();
   }
   return null;
 }
 protected void cacheIdentifiers(
     final UniqueId uniqueId, final Pair<ExternalIdBundle, VersionCorrection> key) {
   synchronized (_eidToUidCache) {
     final Element e = _eidToUidCache.get(key);
     if (e == null) {
       _eidToUidCache.put(new Element(key, uniqueId));
     }
   }
 }
Beispiel #22
0
  protected Dashboard getDashboardFromCache(DashboardCacheKey key) {
    Dashboard dashboard;

    RepositoryAccess repository = RepositoryAccess.getRepository();

    try {
      Cache cache = getCache();
      Element cacheElement = cache.get(key);
      if (cacheElement == null) {
        return null;
      } else {
        dashboard = (Dashboard) cacheElement.getValue();
      }
      logger.info("Got dashboard from cache");
      ISolutionFile dash =
          repository.getSolutionFile(key.getCdfde(), FileAccess.READ); // was NO_PERM=0;
      if (dash == null) {
        logger.error(key.getCdfde() + " not found.");
        return null;
      }

      ISolutionFile templ;
      if (key.getTemplate() == null) {
        templ = null;
      } else {
        templ = repository.getSolutionFile(key.getTemplate(), FileAccess.READ);
      }

      /* Cache is invalidated if the dashboard or template have changed since
       * the cache was loaded, or at midnight every day, because of dynamic
       * generation of date parameters.
       */
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, 00);
      cal.set(Calendar.MINUTE, 00);
      cal.set(Calendar.SECOND, 1);
      boolean
          cacheInvalid =
              dash.getLastModified() > dashboard.getLoaded().getTime()
                  || (templ != null && templ.getLastModified() > dashboard.getLoaded().getTime()),
          cacheExpired = cal.getTime().after(dashboard.getLoaded());

      if (cacheExpired) {
        logger.info("Dashboard expired, re-rendering");
        return null;
      } else if (cacheInvalid) {
        logger.info("Dashboard cache invalidated, re-rendering");
        return null;
      } else {
        return dashboard;
      }
    } catch (CacheException ce) {
      logger.info("Dashboard cache invalidated, re-rendering");
      return null;
    }
  }
 public Object get(Object key) {
   if (key == null) {
     return null;
   }
   Element elem = ehcache.get(key);
   if (elem == null) {
     return null;
   }
   return elem.getObjectValue();
 }
 @Override
 public Client get(String ref) {
   // TODO Auto-generated method stub
   Client client = null;
   if (cache.isKeyInCache(ref)) {
     Element elem = cache.get(ref);
     client = (Client) elem.getObjectValue();
   }
   return client;
 }
 private Entity getFromCache(Integer id) {
   if (id == null) {
     return null;
   }
   Element element = entityDefinitionCache.get(id);
   if (element == null) {
     return null;
   }
   return (Entity) element.getObjectValue();
 }
  @Override
  public boolean containsBounceProxy(String bpId) {

    if (log.isTraceEnabled()) {
      log.trace("containsBounceProxy {} in cache {}", bpId, cacheName);
      tracePeers();
    }
    Cache cache = manager.getCache(cacheName);
    return cache.get(bpId) != null;
  }
 public synchronized long incr(String key, int by) {
   Element e = cache.get(key);
   if (e == null) {
     return -1;
   }
   long newValue = ((Number) e.getValue()).longValue() + by;
   Element newE = new Element(key, newValue);
   newE.setTimeToLive(e.getTimeToLive());
   cache.put(newE);
   return newValue;
 }
 @Override
 public List<Client> searchAll() {
   List<Client> clients = new ArrayList<Client>();
   for (Object key : cache.getKeys()) {
     Element element = cache.get(key);
     if (element != null) {
       clients.add((Client) element.getObjectValue());
     }
   }
   return clients;
 }
Beispiel #29
0
    @Override
    protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
      cache.getCacheEventNotificationService().registerListener(new ThrowingListener());
      for (int i = 0; i < 5000; i++) {
        cache.put(new Element(i, i));
        if (i % 1000 == 0) {
          // Force flush the RemoteObjectManager by faulting some stuff in.
          for (int j = 0; j < 200 && j < i; j++) {
            cache.get(j);
          }
        }
      }

      for (int i = 0; i < 10000; i++) {
        Element e = cache.get(i);
        if (e != null) {
          assertEquals(Integer.valueOf(i), e.getObjectValue());
        }
      }
    }
  public Object remove(Object key) {
    Element elem = null;
    Object previous = null;
    elem = ehcache.get(key);
    if (elem != null) {
      previous = elem.getObjectValue();
      ehcache.remove(key);
    }

    return previous;
  }