Exemplo n.º 1
0
 static {
   if (eternalCache == null) {
     eternalCache = CacheManager.getInstance().getCache("eternalCache");
   }
   if (dictCache == null) {
     dictCache = CacheManager.getInstance().getCache("dictCache");
   }
 }
 @Test
 public void getCrlFromLdapWithNoCaching() throws Exception {
   for (int i = 0; i < 10; i++) {
     CacheManager.getInstance().removeAllCaches();
     final Cache cache = new Cache("crlCache-1", 100, false, false, 20, 10);
     CacheManager.getInstance().addCache(cache);
     final CRLDistributionPointRevocationChecker checker =
         new CRLDistributionPointRevocationChecker(cache, fetcher);
     checker.setThrowOnFetchFailure(true);
     checker.setUnavailableCRLPolicy(new AllowRevocationPolicy());
     checker.init();
     final X509Certificate cert = CertUtils.readCertificate(new ClassPathResource("ldap-crl.crt"));
     checker.check(cert);
   }
 }
  @Override
  public void init(ComponentRepository repo, LinkedHashMap<String, String> configuration)
      throws Exception {
    ConfigSource redisSource =
        new NonVersionedRedisConfigSource(getRedisConnector().getJedisPool(), getRedisPrefix());
    ConfigSource source = redisSource;

    ConfigSource userSource = initUser(repo, configuration);
    Map<String, ConfigSource> map = new HashMap<String, ConfigSource>();
    if (userSource != null) {
      String scheme =
          repo.getInfo(getUserConfigMaster())
              .getAttribute(ComponentInfoAttributes.UNIQUE_ID_SCHEME);
      map.put(scheme, userSource);
      source =
          new EHCachingConfigSource(
              new DelegatingConfigSource(source, map), CacheManager.getInstance());
    }

    ComponentInfo info = new ComponentInfo(ConfigSource.class, getClassifier());
    info.addAttribute(ComponentInfoAttributes.LEVEL, userSource == null ? 1 : 2);
    info.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteConfigSource.class);
    repo.registerComponent(info, source);
    if (isPublishRest()) {
      repo.getRestComponents().publish(info, new DataConfigSourceResource(source));
    }

    info = new ComponentInfo(NonVersionedRedisConfigSource.class, getClassifier());
    info.addAttribute(ComponentInfoAttributes.LEVEL, 1);
    repo.registerComponent(info, redisSource);
  }
Exemplo n.º 4
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);
    }
  }
Exemplo n.º 5
0
 /**
  * @param config
  * @throws ServletException
  */
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   emailValidator = EmailValidator.getInstance();
   accountDAO = AccountDAO.getInstance();
   cacheManager = CacheManager.getInstance();
 }
Exemplo n.º 6
0
 /** {@inheritDoc} */
 public void destroy() {
   // Shut down the cache manager
   try {
     CacheManager.getInstance().shutdown();
   } catch (Exception e) {
     log.warn("Error on cache shutdown", e);
   }
 }
 @Override
 public void start(Settings settings, Properties properties) throws CacheException {
   this.settings = settings;
   try {
     // 返回已经存在的单例CacheManager
     manager = CacheManager.getInstance();
     mbeanRegistrationHelper.registerMBean(manager, properties);
   } catch (net.sf.ehcache.CacheException e) {
     throw new CacheException(e);
   }
 }
Exemplo n.º 8
0
 @SuppressWarnings("unchecked")
 public void init() {
   log.info("Loading ehcache");
   // log.debug("Appcontext: " + applicationContext.toString());
   try {
     // instance the manager
     CacheManager cm = CacheManager.getInstance();
     // Use the Configuration to create our caches
     Configuration configuration = new Configuration();
     // set initial default cache name
     String defaultCacheName = Cache.DEFAULT_CACHE_NAME;
     // add the configs to a configuration
     for (CacheConfiguration conf : configs) {
       // set disk expiry
       conf.setDiskExpiryThreadIntervalSeconds(diskExpiryThreadIntervalSeconds);
       // set eviction policy
       conf.setMemoryStoreEvictionPolicy(memoryStoreEvictionPolicy);
       if (null == cache) {
         // get first cache name and use as default
         defaultCacheName = conf.getName();
         configuration.addDefaultCache(conf);
       } else {
         configuration.addCache(conf);
       }
     }
     // instance the helper
     ConfigurationHelper helper = new ConfigurationHelper(cm, configuration);
     // create the default cache
     cache = helper.createDefaultCache();
     // init the default
     cache.initialise();
     cache.bootstrap();
     // create the un-init'd caches
     Set<Cache> caches = helper.createCaches();
     if (log.isDebugEnabled()) {
       log.debug(
           "Number of caches: " + caches.size() + " Default cache: " + (cache != null ? 1 : 0));
     }
     for (Cache nonDefaultCache : caches) {
       nonDefaultCache.initialise();
       nonDefaultCache.bootstrap();
       // set first cache to be main local member
       if (null == nonDefaultCache) {
         log.debug("Default cache name: {}", defaultCacheName);
         nonDefaultCache = cm.getCache(defaultCacheName);
       }
     }
   } catch (Exception e) {
     log.warn("Error on cache init", e);
   }
   if (log.isDebugEnabled()) {
     log.debug("Cache is null? {}", (null == cache));
   }
 }
Exemplo n.º 9
0
  /**
   * GET method implementation. Lists the available caches
   *
   * @return
   */
  @GET
  public Caches getCaches() {
    LOG.info("GET Caches");

    String[] cacheNames = CacheManager.getInstance().getCacheNames();

    List<Cache> cacheList = new ArrayList<Cache>();

    for (String cacheName : cacheNames) {
      URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize();
      Cache cache = new Cache(cacheName, cacheUri.toString());
      cacheList.add(cache);
    }

    return new Caches(cacheList);
  }
  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());
  }
Exemplo n.º 11
0
  private CacheEntry loadData(int sessionId, AppdefEntityID id)
      throws AppdefEntityNotFoundException {
    Cache cache = CacheManager.getInstance().getCache("AvailabilitySummary");
    Element e = cache.get(id);

    if (e != null) {
      return (CacheEntry) e.getObjectValue();
    }

    // Otherwise, load from the backend

    try {
      Measurement m = measurementBoss.findAvailabilityMetric(sessionId, id);

      CacheEntry res = new CacheEntry(m);
      cache.put(new Element(id, res));
      return res;
    } catch (Exception ex) {
      log.debug("Caught exception loading data: " + ex, ex);
      return null;
    }
  }
Exemplo n.º 12
0
 public EhCacheImpl() {
   this.cchm = CacheManager.getInstance();
   this.cchm.addCache("esi");
   this.cchm.addCache("lb");
 }
  /**
   * Gets the unit test parameters.
   *
   * @return Test parameter data.
   */
  @Parameters
  public static Collection<Object[]> getTestParameters() throws Exception {
    CacheManager.getInstance().removeAllCaches();
    final Collection<Object[]> params = new ArrayList<>();
    Cache cache;
    final ThresholdExpiredCRLRevocationPolicy defaultPolicy =
        new ThresholdExpiredCRLRevocationPolicy();
    final ThresholdExpiredCRLRevocationPolicy zeroThresholdPolicy =
        new ThresholdExpiredCRLRevocationPolicy();
    zeroThresholdPolicy.setThreshold(0);

    // Test case #0
    // Valid certificate on valid CRL data with encoded url
    cache = new Cache("crlCache-0", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    params.add(
        new Object[] {
          new CRLDistributionPointRevocationChecker(cache),
          defaultPolicy,
          new String[] {"uservalid-encoded-crl.crt"},
          "test ca.crl",
          null,
        });

    // Test case #1
    // Valid certificate on valid CRL data
    cache = new Cache("crlCache-1", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    params.add(
        new Object[] {
          new CRLDistributionPointRevocationChecker(cache, true),
          defaultPolicy,
          new String[] {"user-valid-distcrl.crt"},
          "userCA-valid.crl",
          null,
        });

    // Test case #2
    // Revoked certificate on valid CRL data
    cache = new Cache("crlCache-2", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    params.add(
        new Object[] {
          new CRLDistributionPointRevocationChecker(cache),
          defaultPolicy,
          new String[] {"user-revoked-distcrl.crt"},
          "userCA-valid.crl",
          new RevokedCertificateException(new Date(), new BigInteger("1")),
        });

    // Test case #3
    // Valid certificate on expired CRL data
    cache = new Cache("crlCache-3", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    params.add(
        new Object[] {
          new CRLDistributionPointRevocationChecker(cache),
          zeroThresholdPolicy,
          new String[] {"user-valid-distcrl.crt"},
          "userCA-expired.crl",
          new ExpiredCRLException("test", new Date()),
        });

    // Test case #4
    // Valid certificate on expired CRL data with custom expiration
    // policy to always allow expired CRL data
    cache = new Cache("crlCache-4", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    params.add(
        new Object[] {
          new CRLDistributionPointRevocationChecker(cache),
          new RevocationPolicy<X509CRL>() {
            @Override
            public void apply(final X509CRL crl) {
              /* Do nothing to allow unconditionally */
            }
          },
          new String[] {"user-valid-distcrl.crt"},
          "userCA-expired.crl",
          null,
        });

    // Test case #5
    // Valid certificate with no CRL distribution points defined but with
    // "AllowRevocationPolicy" set to allow unavailable CRL data
    cache = new Cache("crlCache-5", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    final CRLDistributionPointRevocationChecker checker5 =
        new CRLDistributionPointRevocationChecker(cache);
    checker5.setUnavailableCRLPolicy(new AllowRevocationPolicy());
    params.add(
        new Object[] {
          checker5, defaultPolicy, new String[] {"user-valid.crt"}, "userCA-expired.crl", null,
        });

    // Test case #6
    // EJBCA test case
    // Revoked certificate with CRL distribution point URI that is technically
    // not a valid URI since the issuer DN in the querystring is not encoded per
    // the escaping of reserved characters in RFC 2396.
    // Make sure we can convert given URI to valid URI and confirm it's revoked
    cache = new Cache("crlCache-6", 100, false, false, 20, 10);
    CacheManager.getInstance().addCache(cache);
    params.add(
        new Object[] {
          new CRLDistributionPointRevocationChecker(cache),
          defaultPolicy,
          new String[] {"user-revoked-distcrl2.crt"},
          "userCA-valid.crl",
          new RevokedCertificateException(new Date(), new BigInteger("1")),
        });

    return params;
  }
Exemplo n.º 14
0
  @SuppressWarnings("unchecked")
  public GameServer() throws Exception {
    _instance = this;
    _serverStarted = time();
    _listeners = new GameServerListenerList();

    new File("./log/").mkdir();

    version = new Version(GameServer.class);

    _log.info("=================================================");
    _log.info("Project Revision: ........ " + PROJECT_REVISION);
    _log.info("Build Revision: .......... " + version.getRevisionNumber());
    _log.info("Update: .................. " + UPDATE_NAME);
    _log.info("Build date: .............. " + version.getBuildDate());
    _log.info("Compiler version: ........ " + version.getBuildJdk());
    _log.info("=================================================");
    Clients.Load();
    // Initialize config
    Config.load();
    // Check binding address
    checkFreePorts();
    // Initialize database
    Class.forName(Config.DATABASE_DRIVER).newInstance();
    DatabaseFactory.getInstance().getConnection().close();

    IdFactory _idFactory = IdFactory.getInstance();
    if (!_idFactory.isInitialized()) {
      _log.error("Could not read object IDs from DB. Please Check Your Data.");
      throw new Exception("Could not initialize the ID factory");
    }

    CacheManager.getInstance();

    ThreadPoolManager.getInstance();

    LfcDAO.LoadArenas();
    LfcStatisticDAO.LoadGlobalStatistics();
    LfcStatisticDAO.LoadLocalStatistics();

    CustomStatsDAO.LoadCustomValues();

    PremiumAccountRatesHolder.loadLists();

    BotCheckManager.loadBotQuestions();

    FreePremiumAccountsDao.LoadTable();

    HidenItemsDAO.LoadAllHiddenItems();

    CustomHeroDAO.getInstance();

    HWIDBan.getInstance().load();

    Scripts.getInstance();

    GeoEngine.load();

    Strings.reload();

    GameTimeController.getInstance();

    World.init();

    Parsers.parseAll();

    ItemsDAO.getInstance();

    CrestCache.getInstance();

    ImagesCache.getInstance();

    CharacterDAO.getInstance();

    ClanTable.getInstance();

    DailyQuestsManager.EngageSystem();

    //		FakePlayersTable.getInstance();
    SkillTreeTable.getInstance();

    SubClassTable.getInstance();

    EnchantHPBonusTable.getInstance();

    PetSkillsTable.getInstance();

    ItemAuctionManager.getInstance();

    SpawnManager.getInstance().spawnAll();

    FakePlayersSpawnManager.getInstance().spawnAll();

    StaticObjectHolder.getInstance().spawnAll();

    RaidBossSpawnManager.getInstance();

    Scripts.getInstance().init();

    ItemHolder.getInstance().initItems();

    DimensionalRiftManager.getInstance();

    Announcements.getInstance();

    LotteryManager.getInstance();

    PlayerMessageStack.getInstance();

    if (Config.AUTODESTROY_ITEM_AFTER > 0) ItemsAutoDestroy.getInstance();

    MonsterRace.getInstance();

    if (Config.ENABLE_OLYMPIAD) {
      Olympiad.load();
      Hero.getInstance();
    }

    PetitionManager.getInstance();

    CursedWeaponsManager.getInstance();

    if (Config.ALLOW_WEDDING) {
      CoupleManager.getInstance();
    }

    ItemHandler.getInstance();

    AdminCommandHandler.getInstance().log();
    UserCommandHandler.getInstance().log();
    VoicedCommandHandler.getInstance().log();

    TaskManager.getInstance();

    _log.info("=[Events]=========================================");
    ResidenceHolder.getInstance().callInit();
    EventHolder.getInstance().callInit();
    _log.info("==================================================");

    BoatHolder.getInstance().spawnAll();
    CastleManorManager.getInstance();

    Runtime.getRuntime().addShutdownHook(Shutdown.getInstance());

    _log.info("IdFactory: Free ObjectID's remaining: " + IdFactory.getInstance().size());

    if (Config.ALT_FISH_CHAMPIONSHIP_ENABLED) FishingChampionShipManager.getInstance();

    HellboundManager.getInstance();

    NaiaTowerManager.getInstance();
    NaiaCoreManager.getInstance();

    SoDManager.getInstance();
    SoIManager.getInstance();
    SoHManager.getInstance();

    MiniGameScoreManager.getInstance();

    CommissionManager.getInstance().init();

    WorldStatisticsManager.getInstance();
    ArcanManager.getInstance();
    ToIManager.getInstance();
    ParnassusManager.getInstance();
    BaltusManager.getInstance();
    Shutdown.getInstance().schedule(Config.RESTART_AT_TIME, Shutdown.RESTART);

    /* CCP Guard START
    ccpGuard.Protection.Init();
    ** CCP Guard END*/

    _log.info("GameServer Started");
    _log.info("Maximum Numbers of Connected Players: " + Config.MAXIMUM_ONLINE_USERS);

    GamePacketHandler gph = new GamePacketHandler();

    InetAddress serverAddr =
        Config.GAMESERVER_HOSTNAME.equalsIgnoreCase("*")
            ? null
            : InetAddress.getByName(Config.GAMESERVER_HOSTNAME);

    _selectorThreads = new ArrayList<SelectorThread<GameClient>>(Config.PORTS_GAME.length);
    for (int i = 0; i < Config.PORTS_GAME.length; i++) {
      SelectorThread<GameClient> selectorThread =
          new SelectorThread<GameClient>(Config.SELECTOR_CONFIG, gph, gph, gph, null);
      selectorThread.openServerSocket(serverAddr, Config.PORTS_GAME[i]);
      selectorThread.start();
      _selectorThreads.add(i, selectorThread);
    }

    AuthServerCommunication.getInstance().start();

    if (Config.SERVICES_OFFLINE_TRADE_RESTORE_AFTER_RESTART)
      ThreadPoolManager.getInstance().schedule(new RestoreOfflineTraders(), 30000L);

    if (Config.ONLINE_GENERATOR_ENABLED)
      ThreadPoolManager.getInstance()
          .scheduleAtFixedRate(
              new OnlineTxtGenerator(), 5000L, Config.ONLINE_GENERATOR_DELAY * 60 * 1000L);

    getListeners().onStart();

    if (Config.IS_TELNET_ENABLED) statusServer = new TelnetServer();
    else _log.info("Telnet server is currently disabled.");

    _log.info("=================================================");
    String memUsage = new StringBuilder().append(StatsUtils.getMemUsage()).toString();
    for (String line : memUsage.split("\n")) _log.info(line);
    _log.info("=================================================");
  }
Exemplo n.º 15
0
 @Override
 protected void finalize() throws Throwable {
   CacheManager.getInstance().shutdown();
   super.finalize();
 };
Exemplo n.º 16
0
  @Action("msgpush")
  public String msgpush() throws Exception {
    BufferedReader r = ServletActionContext.getRequest().getReader();
    String ret = null;
    StringBuffer sb = new StringBuffer();
    String s;
    while ((s = r.readLine()) != null) {
      sb.append(s);
    }
    DBObject req = (DBObject) JSON.parse(sb.toString());
    DBObject head = (DBObject) req.get("head");
    timestamp = (long) head.get("timestamp");
    clientid = String.valueOf(head.get("clientid"));
    userenc = String.valueOf(head.get("userenc"));
    String touser = String.valueOf(head.get("touser"));
    DB db = MongoUtil.getInstance().getDB();
    if (checkTime(timestamp)) {
      if (checkenc(db, timestamp, clientid, userenc)) {
        if (checkmsgsum(req.get("data"), touser, userenc, String.valueOf(head.get("checksum")))) {
          Cache cache = CacheManager.getInstance().getCache("MsgCheck");
          if (cache.get(head.get("checksum")) == null) {
            cache.put(new Element(head.get("checksum"), null));
            DBObject user =
                db.getCollection("Bindings")
                    .findOne(
                        new BasicDBObject(
                            "binds",
                            new BasicDBObject("$elemMatch", new BasicDBObject("uisid", touser))));
            if (!CommonUtil.isEmpty(user) && !CommonUtil.isEmpty(user.get("openid"))) {
              // template白名单
              if (Config.getInstance()
                          .get("push.whitelist")
                          .indexOf(head.get("template").toString())
                      >= 0
                  || db.getCollection("Books")
                          .findOne(
                              new BasicDBObject("openid", user.get("openid"))
                                  .append("item", head.get("template"))
                                  .append("book", true))
                      != null) {
                String cret =
                    TemplateMessage.send(
                        String.valueOf(head.get("template")),
                        String.valueOf(user.get("openid")),
                        (DBObject) req.get("data"));
                if (cret != null && cret.startsWith("{")) {
                  DBObject retobj = (DBObject) JSON.parse(cret);
                  retobj.put("touser", touser);
                  retobj.put("timestamp", timestamp);
                  retobj.put("clientid", clientid);
                  db.getCollection("Pushmsgs").save(retobj);
                  ret = cret;
                } else errormsg = cret;
              } else {
                errormsg = "Message not booked";
              }
            } else {
              errormsg = "Touser not binded";
            }

          } else {
            errormsg = "Same message is sent too frequently";
          }
        } else {
          errormsg = "Message checksum error";
        }

      } else {
        errormsg = "User not authorized";
      }
    } else errormsg = "Timestamp outof range";

    HttpServletResponse resp = ServletActionContext.getResponse();
    resp.setCharacterEncoding("utf-8");
    resp.setContentType("application/json");
    if (!CommonUtil.isEmpty(ret)) resp.getWriter().print(ret);
    else resp.getWriter().write("{\"errcode\":50000,\"errmsg\":\"" + errormsg + "\"}");

    return NONE;
  }
 @Override
 protected CacheManager getCacheManager() {
   return CacheManager.getInstance();
 }
Exemplo n.º 18
0
/**
 * EhcacheCache configuration document available <a
 * href="http://ehcache.sourceforge.net/EhcacheUserGuide.html>EhcacheUserGuide</a>
 *
 * @author <a href="mailto:[email protected]">Joakim Erdfelt</a>
 * @version $Id$
 */
public class EhcacheCache implements org.apache.archiva.redback.components.cache.Cache {

  private Logger log = LoggerFactory.getLogger(getClass());

  class Stats implements CacheStatistics {
    public void clear() {
      ehcache.clearStatistics();
    }

    public double getCacheHitRate() {
      double hits = getCacheHits();
      double miss = getCacheMiss();

      if ((hits == 0) && (hits == 0)) {
        return 0.0;
      }

      return (double) hits / (double) (hits + miss);
    }

    public long getCacheHits() {
      return ehcache.getStatistics().getCacheHits();
    }

    public long getCacheMiss() {
      return ehcache.getStatistics().getCacheMisses();
    }

    public long getSize() {
      return ehcache.getMemoryStoreSize() + ehcache.getDiskStoreSize();
    }
  }

  /**
   * how often to run the disk store expiry thread. A large number of 120 seconds plus is
   * recommended
   */
  private long diskExpiryThreadIntervalSeconds = 600;

  /** Whether to persist the cache to disk between JVM restarts. */
  private boolean diskPersistent = true;

  /** Location on disk for the ehcache store. */
  private String diskStorePath = System.getProperty("java.io.tmpdir") + "/ehcache";

  /** */
  private boolean eternal = false;

  /** */
  private int maxElementsInMemory = 1000;

  /** */
  private String memoryEvictionPolicy = "LRU";

  /** */
  private String name = "cache";

  /** Flag indicating when to use the disk store. */
  private boolean overflowToDisk = false;

  /** */
  private int timeToIdleSeconds = 600;

  /** */
  private int timeToLiveSeconds = 300;

  /** */
  private boolean failOnDuplicateCache = false;

  private boolean statisticsEnabled = true;

  private CacheManager cacheManager = CacheManager.getInstance();

  private net.sf.ehcache.Cache ehcache;

  private Stats stats;

  public void clear() {
    ehcache.removeAll();
    stats.clear();
  }

  @PostConstruct
  public void initialize() {
    stats = new Stats();

    boolean cacheExists = cacheManager.cacheExists(getName());

    if (cacheExists) {
      if (failOnDuplicateCache) {
        throw new RuntimeException("A previous cache with name [" + getName() + "] exists.");
      } else {
        log.warn("skip duplicate cache " + getName());
        ehcache = cacheManager.getCache(getName());
      }
    }

    if (!cacheExists) {
      ehcache =
          new Cache(
              getName(),
              getMaxElementsInMemory(),
              getMemoryStoreEvictionPolicy(),
              isOverflowToDisk(),
              getDiskStorePath(),
              isEternal(),
              getTimeToLiveSeconds(),
              getTimeToIdleSeconds(),
              isDiskPersistent(),
              getDiskExpiryThreadIntervalSeconds(),
              null);

      cacheManager.addCache(ehcache);
      ehcache.setStatisticsEnabled(statisticsEnabled);
    }
  }

  public void dispose() {
    if (cacheManager.getStatus().equals(Status.STATUS_ALIVE)) {
      log.info("Disposing cache: " + ehcache);
      if (this.ehcache != null) {
        cacheManager.removeCache(this.ehcache.getName());
        ehcache = null;
      }
    } else {
      log.debug("Not disposing cache, because cacheManager is not alive: " + ehcache);
    }
  }

  public Object get(Object key) {
    if (key == null) {
      return null;
    }
    Element elem = ehcache.get(key);
    if (elem == null) {
      return null;
    }
    return elem.getObjectValue();
  }

  public long getDiskExpiryThreadIntervalSeconds() {
    return diskExpiryThreadIntervalSeconds;
  }

  public String getDiskStorePath() {
    return diskStorePath;
  }

  public int getMaxElementsInMemory() {
    return maxElementsInMemory;
  }

  public String getMemoryEvictionPolicy() {
    return memoryEvictionPolicy;
  }

  public MemoryStoreEvictionPolicy getMemoryStoreEvictionPolicy() {
    return MemoryStoreEvictionPolicy.fromString(memoryEvictionPolicy);
  }

  public String getName() {
    return name;
  }

  public CacheStatistics getStatistics() {
    return stats;
  }

  public int getTimeToIdleSeconds() {
    return timeToIdleSeconds;
  }

  public int getTimeToLiveSeconds() {
    return timeToLiveSeconds;
  }

  public boolean hasKey(Object key) {
    return ehcache.isKeyInCache(key);
  }

  public boolean isDiskPersistent() {
    return diskPersistent;
  }

  public boolean isEternal() {
    return eternal;
  }

  public boolean isOverflowToDisk() {
    return overflowToDisk;
  }

  public void register(Object key, Object value) {
    ehcache.put(new Element(key, value));
  }

  public Object put(Object key, Object value) {
    // Multiple steps done to satisfy Cache API requirement for Previous object return.
    Element elem = null;
    Object previous = null;
    elem = ehcache.get(key);
    if (elem != null) {
      previous = elem.getObjectValue();
    }
    elem = new Element(key, value);
    ehcache.put(elem);
    return previous;
  }

  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;
  }

  public void setDiskExpiryThreadIntervalSeconds(long diskExpiryThreadIntervalSeconds) {
    this.diskExpiryThreadIntervalSeconds = diskExpiryThreadIntervalSeconds;
  }

  public void setDiskPersistent(boolean diskPersistent) {
    this.diskPersistent = diskPersistent;
  }

  public void setDiskStorePath(String diskStorePath) {
    this.diskStorePath = diskStorePath;
  }

  public void setEternal(boolean eternal) {
    this.eternal = eternal;
  }

  public void setMaxElementsInMemory(int maxElementsInMemory) {
    this.maxElementsInMemory = maxElementsInMemory;
  }

  public void setMemoryEvictionPolicy(String memoryEvictionPolicy) {
    this.memoryEvictionPolicy = memoryEvictionPolicy;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setOverflowToDisk(boolean overflowToDisk) {
    this.overflowToDisk = overflowToDisk;
  }

  public void setTimeToIdleSeconds(int timeToIdleSeconds) {
    this.timeToIdleSeconds = timeToIdleSeconds;
  }

  public void setTimeToLiveSeconds(int timeToLiveSeconds) {
    this.timeToLiveSeconds = timeToLiveSeconds;
  }

  public boolean isStatisticsEnabled() {
    return statisticsEnabled;
  }

  public void setStatisticsEnabled(boolean statisticsEnabled) {
    this.statisticsEnabled = statisticsEnabled;
  }

  public boolean isFailOnDuplicateCache() {
    return failOnDuplicateCache;
  }

  public void setFailOnDuplicateCache(boolean failOnDuplicateCache) {
    this.failOnDuplicateCache = failOnDuplicateCache;
  }
}
 /**
  * Retrieve the underlying cache for this query miss cache. Presumably and Ehcache region has been
  * configured for this cacheName.
  *
  * @param cacheName the name of the cache - the ehcache region name
  * @return the underlying cache
  */
 protected Cache getCache(String cacheName) {
   if (cache == null) {
     cache = CacheManager.getInstance().getCache(cacheName);
   }
   return cache;
 }
 public void shutdownCache() {
   CacheManager.getInstance().shutdown();
   manager = null;
 }
Exemplo n.º 21
0
 @Override
 protected Cache getCache() {
   return CacheManager.getInstance().getCache("web-datasource-lv3");
 }