@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);
    }
  }
Exemple #2
0
 /** {@inheritDoc} */
 @Override
 public void addCache(final String context, final CacheConfig cacheConfig) {
   if (!manager.cacheExists(context)) {
     final boolean overflowToDisk = cacheConfig.shouldSerializeElements(); // don't overflow
     final net.sf.ehcache.Cache cache =
         new net.sf.ehcache.Cache(
             context,
             cacheConfig.getMaxElementsInMemory(),
             overflowToDisk,
             false, // not eternal
             cacheConfig.getTimeToLiveSeconds(),
             cacheConfig.getTimeToIdleSeconds());
     manager.addCache(cache);
     cacheConfigsPerContext.put(context, cacheConfig);
   }
 }
Exemple #3
0
  private static synchronized Cache getCache() throws CacheException {
    if (cacheManager
        == null) { // 'new CacheManager' used instead of 'CacheManager.create' to avoid overriding
      // default cache
      String cacheConfigFile = CACHE_CFG_FILE;

      String cfgFile =
          PentahoSystem.getApplicationContext()
              .getSolutionPath(DashboardDesignerContentGenerator.PLUGIN_PATH + cacheConfigFile);
      cacheManager = new CacheManager(cfgFile); // CacheManager.create(cfgFile);
    }

    enableCacheProperShutdown(true);

    if (!cacheManager.cacheExists(CACHE_NAME)) {
      cacheManager.addCache(CACHE_NAME);
    }

    return cacheManager.getCache(CACHE_NAME);
  }
  /**
   * @param cacheName
   * @param legacyMode If true always create a new Cache. If false, cache must be defined in bean
   *     factory.
   * @return
   */
  private Ehcache instantiateCache(String cacheName) {
    if (M_log.isDebugEnabled()) M_log.debug("createNewCache(String " + cacheName + ")");

    String name = cacheName;
    if (name == null || "".equals(name)) {
      name = "DefaultCache" + UUID.randomUUID().toString();
    }

    // Cache creation should all go to the cache manager and be
    // configured via the cache manager setup.

    if (cacheManager.cacheExists(name)) {
      return cacheManager.getEhcache(name);
    }

    Ehcache cache = null;

    try {
      Ehcache defaultCache = getDefaultCache();
      if (defaultCache != null) {
        cache = (Ehcache) defaultCache.clone();
        cache.setName(cacheName);

        // Not look for any custom configuration.
        // Check for old configuration properties.
        if (serverConfigurationService().getString(name) == null) {
          M_log.warn("Old cache configuration " + name + " must be changed to memory." + name);
        }
        String config = serverConfigurationService().getString("memory." + name);
        if (config != null && config.length() > 0) {
          M_log.debug("Found configuration for cache: " + name + " of: " + config);
          new CacheInitializer().configure(config).initialize(cache.getCacheConfiguration());
        }

        cacheManager.addCache(cache);
      }
    } catch (Exception ex) {
      M_log.warn("Unable to access or close default cache", ex);
    }

    if (cache == null) {
      cacheManager.addCache(name);
      cache = cacheManager.getEhcache(name);
    }

    // KNL-1292: do not set if the cache is not yet init'ed
    if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) {
      // KNL-532 - Upgraded Ehcache 2.5.1 (2.1.0+) defaults to no stats collection.
      // We may choose to allow configuration per-cache for performance tuning.
      // For now, we default everything to on, while this property allows a system-wide override.
      cache.setStatisticsEnabled(
          !(serverConfigurationService()
              .getBoolean("memory.cache.statistics.force.disabled", false)));
    }

    return cache;

    /*


    if(legacyMode)
    {
    	if (cacheManager.cacheExists(name)) {
    		M_log.warn("Cache already exists and is bound to CacheManager; creating new cache from defaults: "
    				+ name);
    		// favor creation of new caches for backwards compatibility
    		// in the future, it seems like you would want to return the same
    		// cache if it already exists
    		name = name + UUID.randomUUID().toString();
    	}
    }

    Ehcache cache = null;

    // try to locate a named cache in the bean factory
    try {
    	cache = (Ehcache) ComponentManager.get(name);
    } catch (Exception e) {
    	cache = null;
    	M_log.error("Error occurred when trying to load cache from bean factory!", e);
    }


    if(cache != null) // found the cache
    {
    	M_log.info("Loaded Named Cache " + cache);

    	return cache;
    }
    else // did not find the cache
    {
    	if(legacyMode)
    	{
    		cacheManager.addCache(name); // create a new cache
    		cache = cacheManager.getEhcache(name);
    		M_log.info("Loaded Default Cache " + cache);
    	}
    	else
    	{
    		M_log.error("Could not find named cache in the bean factory!:"
    						+ name);
    	}

    	return cache;
    }
    */
  }
  /**
   * @param cacheName
   * @param legacyMode If true always create a new Cache. If false, cache must be defined in bean
   *     factory.
   * @return
   */
  private Ehcache instantiateCache(String cacheName) {
    if (M_log.isDebugEnabled()) M_log.debug("createNewCache(String " + cacheName + ")");

    String name = cacheName;
    if (name == null || "".equals(name)) {
      name = "DefaultCache" + UUID.randomUUID().toString();
    }

    // Cache creation should all go to the cache manager and be
    // configured via the cache manager setup.

    if (cacheManager.cacheExists(name)) {
      return cacheManager.getEhcache(name);
    }
    cacheManager.addCache(name);
    return cacheManager.getEhcache(name);

    /*


    if(legacyMode)
    {
    	if (cacheManager.cacheExists(name)) {
    		M_log.warn("Cache already exists and is bound to CacheManager; creating new cache from defaults: "
    				+ name);
    		// favor creation of new caches for backwards compatibility
    		// in the future, it seems like you would want to return the same
    		// cache if it already exists
    		name = name + UUID.randomUUID().toString();
    	}
    }

    Ehcache cache = null;

    // try to locate a named cache in the bean factory
    try {
    	cache = (Ehcache) ComponentManager.get(name);
    } catch (Throwable e) {
    	cache = null;
    	M_log.error("Error occurred when trying to load cache from bean factory!", e);
    }


    if(cache != null) // found the cache
    {
    	M_log.info("Loaded Named Cache " + cache);

    	return cache;
    }
    else // did not find the cache
    {
    	if(legacyMode)
    	{
    		cacheManager.addCache(name); // create a new cache
    		cache = cacheManager.getEhcache(name);
    		M_log.info("Loaded Default Cache " + cache);
    	}
    	else
    	{
    		M_log.error("Could not find named cache in the bean factory!:"
    						+ name);
    	}

    	return cache;
    }
    */
  }
  /**
   * @param cacheName the name of the cache
   * @param configuration [OPTIONAL] a config to use when building the cache, if null then use
   *     default methods to create cache
   * @return an Ehcache
   */
  private Ehcache makeEhcache(
      String cacheName, org.sakaiproject.memory.api.Configuration configuration) {
    /** Indicates a cache is a new one and should be configured */
    boolean newCache = false;
    String name = cacheName;
    if (name == null || "".equals(name)) {
      name = "DefaultCache" + UUID.randomUUID().toString();
      log.warn("Creating cache without a name, generating dynamic name: (" + name + ")");
      newCache = true;
    }

    Ehcache cache;
    // fetch an existing cache first if possible
    if (!newCache && cacheManager.cacheExists(name)) {
      cache = cacheManager.getEhcache(name);
      if (log.isDebugEnabled()) log.debug("Retrieved existing ehcache (" + name + ")");
    } else {
      // create a new defaulted cache
      cacheManager.addCache(name);
      cache = cacheManager.getEhcache(name);
      newCache = true;
      log.info("Created ehcache (" + name + ") using defaults");
    }

    if (newCache) {
      if (log.isDebugEnabled())
        log.debug("Prepared to configure new ehcache (" + name + "): " + cache);
      // warn people if they are using an old config style
      if (serverConfigurationService.getString(name) == null) {
        log.warn(
            "Old cache configuration for cache ("
                + name
                + "), must be changed to memory."
                + name
                + " or it will be ignored");
      }

      // load the ehcache config from the Sakai config service
      String config = serverConfigurationService.getString("memory." + name);
      if (StringUtils.isNotBlank(config)) {
        log.info("Configuring ehcache (" + name + ") from Sakai config: " + config);
        try {
          // ehcache specific code here - no exceptions thrown
          //noinspection deprecation
          new CacheInitializer().configure(config).initialize(cache.getCacheConfiguration());
        } catch (Exception e) {
          // nothing to do here but proceed
          log.error("Failure configuring cache (" + name + "): " + config + " :: " + e, e);
        }
      }

      /* KNL-532 - Upgraded Ehcache 2.5.1 (2.1.0+) defaults to no stats collection.
       * We may choose to allow configuration per-cache for performance tuning.
       * For now, we default everything to on, while this property allows a system-wide override.
       */
      boolean enabled = true;
      if (serverConfigurationService != null) {
        enabled =
            !serverConfigurationService.getBoolean("memory.cache.statistics.force.disabled", false);
      }
      if (cache.isStatisticsEnabled() != enabled) {
        cache.setStatisticsEnabled(enabled);
      }
    }

    // apply config to the cache (every time)
    if (configuration != null) {
      if (configuration.getMaxEntries() >= 0) {
        cache.getCacheConfiguration().setMaxEntriesLocalHeap(configuration.getMaxEntries());
      }
      if (configuration.isEternal()) {
        cache.getCacheConfiguration().setTimeToLiveSeconds(0l);
        cache.getCacheConfiguration().setTimeToIdleSeconds(0l);
      } else {
        if (configuration.getTimeToLiveSeconds() >= 0) {
          cache.getCacheConfiguration().setTimeToLiveSeconds(configuration.getTimeToLiveSeconds());
        }
        if (configuration.getTimeToIdleSeconds() >= 0) {
          cache.getCacheConfiguration().setTimeToIdleSeconds(configuration.getTimeToIdleSeconds());
        }
      }
      cache.getCacheConfiguration().setEternal(configuration.isEternal());
      cache.setStatisticsEnabled(configuration.isStatisticsEnabled());
      log.info("Configured ehcache (" + name + ") from inputs: " + configuration);
    }

    if (log.isDebugEnabled()) log.debug("Returning initialized ehcache (" + name + "): " + cache);
    return cache;
  }