org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration Java Examples

The following examples show how to use org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestUserManagedCache.java    From jframe with Apache License 2.0 6 votes vote down vote up
public void persistenceServiceTest() {
    LocalPersistenceService persistenceService = new DefaultLocalPersistenceService(
            new DefaultPersistenceConfiguration(new File("", "myUserData")));

    PersistentUserManagedCache<Long, String> cache = UserManagedCacheBuilder
            .newUserManagedCacheBuilder(Long.class, String.class)
            .with(new UserManagedPersistenceContext<Long, String>("cache-name", persistenceService))
            .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES).disk(10L,
                    MemoryUnit.MB, true))
            .build(true);

    // Work with the cache
    cache.put(42L, "The Answer!");
    // assertThat(cache.get(42L), is("The Answer!"));

    cache.close();
    try {
        cache.destroy();
    } catch (CachePersistenceException e) {
        e.printStackTrace();
    }

    persistenceService.stop();
}
 
Example #2
Source File: DefaultLocalPersistenceServiceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPhysicalDestroy() throws IOException, CachePersistenceException {
  final File f = folder.newFolder("testPhysicalDestroy");
  final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(f));
  service.start(null);

  assertThat(service.getLockFile().exists(), is(true));
  assertThat(f, isLocked());

  LocalPersistenceService.SafeSpaceIdentifier id = service.createSafeSpaceIdentifier("test", "test");
  service.createSafeSpace(id);

  assertThat(f, containsCacheDirectory("test", "test"));

  // try to destroy the physical space without the logical id
  LocalPersistenceService.SafeSpaceIdentifier newId = service.createSafeSpaceIdentifier("test", "test");
  service.destroySafeSpace(newId, false);

  assertThat(f, not(containsCacheDirectory("test", "test")));

  service.stop();

  assertThat(f, not(isLocked()));
}
 
Example #3
Source File: JCacheCalculationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  CachingProvider cachingProvider = Caching.getCachingProvider();
  EhcacheCachingProvider ehcacheProvider = (EhcacheCachingProvider) cachingProvider;

  DefaultConfiguration configuration = new DefaultConfiguration(ehcacheProvider.getDefaultClassLoader(),
    new DefaultPersistenceConfiguration(diskPath.newFolder()));

  CacheConfiguration<Integer, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, resources).build();
  configuration.addCacheConfiguration("cache", cacheConfiguration);

  cacheManager = ehcacheProvider.getCacheManager(ehcacheProvider.getDefaultURI(), configuration);

  EhcacheManager ehcacheManager = cacheManager.unwrap(EhcacheManager.class);
  Field field = EhcacheManager.class.getDeclaredField("serviceLocator");
  field.setAccessible(true);
  @SuppressWarnings("unchecked")
  ServiceProvider<Service> serviceProvider = (ServiceProvider<Service>)field.get(ehcacheManager);
  StatisticsService statisticsService = serviceProvider.getService(StatisticsService.class);

  cache = cacheManager.getCache("cache", Integer.class, String.class);

  cacheStatistics = statisticsService.getCacheStatistics("cache");
}
 
Example #4
Source File: TierCalculationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  CacheConfiguration<Integer, String> cacheConfiguration =
    CacheConfigurationBuilder
      .newCacheConfigurationBuilder(Integer.class, String.class, resources)
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics
      .build();

  StatisticsService statisticsService = new DefaultStatisticsService();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("cache", cacheConfiguration)
    .using(new DefaultPersistenceConfiguration(diskPath.newFolder()))
    .using(statisticsService)
    .using(new TimeSourceConfiguration(timeSource))
    .build(true);

  cache = cacheManager.getCache("cache", Integer.class, String.class);

  // Get the tier statistic.
  tierStatistics = statisticsService.getCacheStatistics("cache")
    .getTierStatistics().get(tierName);
}
 
Example #5
Source File: CacheCalculationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  CacheConfiguration<Integer, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, resources).build();

  StatisticsService statisticsService = new DefaultStatisticsService();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("cache", cacheConfiguration)
    .using(new DefaultPersistenceConfiguration(diskPath.newFolder()))
    .using(statisticsService)
    .build(true);

  cache = cacheManager.getCache("cache", Integer.class, String.class);

  cacheStatistics = statisticsService.getCacheStatistics("cache");
}
 
Example #6
Source File: DefaultLocalPersistenceServiceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailsIfDirectoryDoesNotExistsAndIsNotCreated() throws IOException {
  assumeTrue(testFolder.setWritable(false));
  try {
    File f = new File(testFolder, "notallowed");
    try {
      final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(f));
      service.start(null);
      fail("Expected IllegalArgumentException");
    } catch(IllegalArgumentException e) {
      assertThat(e.getMessage(), equalTo("Directory couldn't be created: " + f.getAbsolutePath()));
    }
  } finally {
    testFolder.setWritable(true);
  }
}
 
Example #7
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateServiceCreation() {
  @SuppressWarnings("unchecked")
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withService(new DefaultPersistenceConfiguration(new File("temp")))
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::updateServiceCreation[]
  Configuration withUpdatedPersistence = configuration.derive()
    .updateServices(DefaultPersistenceConfiguration.class,
      existing -> new File("/var/persistence/path"))
    .build();
  //end::updateServiceCreation[]

  DefaultPersistenceConfiguration initialPersistenceConfiguration = ServiceUtils.findSingletonAmongst(DefaultPersistenceConfiguration.class, configuration.getServiceCreationConfigurations());
  Assert.assertThat(initialPersistenceConfiguration.getRootDirectory(), Is.is(new File("temp")));

  DefaultPersistenceConfiguration revisedPersistenceConfiguration = ServiceUtils.findSingletonAmongst(DefaultPersistenceConfiguration.class, withUpdatedPersistence.getServiceCreationConfigurations());
  Assert.assertThat(revisedPersistenceConfiguration.getRootDirectory(), Is.is(new File("/var/persistence/path")));
}
 
Example #8
Source File: UserManagedCaches.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void userManagedDiskCache() throws Exception {
  // tag::persistentUserManagedCache[]
  LocalPersistenceService persistenceService = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(new File(getStoragePath(), "myUserData"))); // <1>

  PersistentUserManagedCache<Long, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Long.class, String.class)
      .with(new UserManagedPersistenceContext<>("cache-name", persistenceService)) // <2>
      .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES)
          .disk(10L, MemoryUnit.MB, true)) // <3>
      .build(true);

  // Work with the cache
  cache.put(42L, "The Answer!");
  assertThat(cache.get(42L), is("The Answer!"));

  cache.close(); // <4>
  cache.destroy(); // <5>

  persistenceService.stop(); // <6>
  // end::persistentUserManagedCache[]
}
 
Example #9
Source File: DefaultLocalPersistenceService.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new service instance using the provided configuration.
 *
 * @param persistenceConfiguration the configuration to use
 */
public DefaultLocalPersistenceService(final DefaultPersistenceConfiguration persistenceConfiguration) {
  if(persistenceConfiguration != null) {
    rootDirectory = persistenceConfiguration.getRootDirectory();
  } else {
    throw new NullPointerException("DefaultPersistenceConfiguration cannot be null");
  }
  lockFile = new File(rootDirectory, ".lock");
}
 
Example #10
Source File: TieredStoreFlushWhileShutdownTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private ServiceLocator getServiceLocator(File location) throws Exception {
  DefaultPersistenceConfiguration persistenceConfiguration = new DefaultPersistenceConfiguration(location);
  DefaultLocalPersistenceService fileService = new DefaultLocalPersistenceService(persistenceConfiguration);
  DefaultDiskResourceService diskResourceService = new DefaultDiskResourceService();
  ServiceLocator.DependencySet dependencySet = dependencySet();
  dependencySet.with(fileService);
  dependencySet.with(diskResourceService);
  dependencySet.with(new OnHeapStore.Provider());
  dependencySet.with(new OffHeapDiskStore.Provider());
  dependencySet.with(Mockito.mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS));
  return dependencySet.build();
}
 
Example #11
Source File: DefaultLocalPersistenceServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testExclusiveLock() throws IOException {
  DefaultLocalPersistenceService service1 = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
  DefaultLocalPersistenceService service2 = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
  service1.start(null);

  // We should not be able to lock the same directory twice
  // And we should receive a meaningful exception about it
  expectedException.expectMessage("Persistence directory already locked by this process: " + testFolder.getAbsolutePath());
  service2.start(null);
}
 
Example #12
Source File: DefaultLocalPersistenceServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocksDirectoryAndUnlocks() throws IOException {
  final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
  service.start(null);
  assertThat(service.getLockFile().exists(), is(true));
  service.stop();
  assertThat(service.getLockFile().exists(), is(false));
}
 
Example #13
Source File: DefaultLocalPersistenceServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailsIfFileExistsButIsNotDirectory() throws IOException {
  File f = folder.newFile("testFailsIfFileExistsButIsNotDirectory");
  try {
    final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(f));
    service.start(null);
    fail("Expected IllegalArgumentException");
  } catch(IllegalArgumentException e) {
    assertThat(e.getMessage(), equalTo("Location is not a directory: " + f.getAbsolutePath()));
  }
}
 
Example #14
Source File: DefaultLocalPersistenceServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailsIfDirectoryExistsButNotWritable() throws IOException {
  assumeTrue(testFolder.setWritable(false));
  try {
    try {
      final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
      service.start(null);
      fail("Expected IllegalArgumentException");
    } catch(IllegalArgumentException e) {
      assertThat(e.getMessage(), equalTo("Location isn't writable: " + testFolder.getAbsolutePath()));
    }
  } finally {
    testFolder.setWritable(true);
  }
}
 
Example #15
Source File: CacheConfiguration.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
private org.ehcache.config.Configuration createConfig(final ClassLoader cl) {
    ResourcePoolsBuilder pools = ResourcePoolsBuilder.newResourcePoolsBuilder()
            .heap(1000L, EntryUnit.ENTRIES);
    // If needed, but will need to register serializers for the objects being stored
    // .offheap(10L, MemoryUnit.MB)
    // .disk(20, MemoryUnit.MB, false);

    DefaultCacheEventListenerConfiguration cacheLogging = new DefaultCacheEventListenerConfiguration(EnumSet.allOf(EventType.class), CacheLogger.class);

    return ConfigurationBuilder.newConfigurationBuilder()
            .withService(new DefaultPersistenceConfiguration(SettingsService.getAirsonicHome().resolve("cache").toFile()))
            .withCache("userCache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class, pools)
                            .withClassLoader(cl)
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(2)))
                            .withService(cacheLogging))
            .withCache("userSettingsCache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Object.class, pools)
                            .withClassLoader(cl)
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(2)))
                            .withService(cacheLogging))
            .withCache("mediaFileMemoryCache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(Path.class, Object.class, pools)
                            .withClassLoader(cl)
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(10)))
                            .withService(cacheLogging))
            .withCache("playlistCache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Object.class, pools)
                            .withClassLoader(cl)
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(10)))
                            .withService(cacheLogging))
            .withCache("playlistUsersCache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Object.class, pools)
                            .withClassLoader(cl)
                            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofDays(10)))
                            .withService(cacheLogging))
            .build();
}
 
Example #16
Source File: ResourceCombinationsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicCacheOperation() throws IOException, URISyntaxException {
  Configuration config = new DefaultConfiguration(ResourceCombinationsTest.class.getClassLoader(),
          new DefaultPersistenceConfiguration(diskPath.newFolder()));
  try (CacheManager cacheManager = new EhcacheCachingProvider().getCacheManager(URI.create("dummy"), config)) {
    Cache<String, String> cache = cacheManager.createCache("test", fromEhcacheCacheConfiguration(
      newCacheConfigurationBuilder(String.class, String.class, resources)));
    cache.put("foo", "bar");
    assertThat(cache.get("foo"), is("bar"));
  }
}
 
Example #17
Source File: EhCache107ConfigurationIntegrationDocTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheManagerLevelConfiguration() throws Exception {
  // tag::ehcacheCacheManagerConfigurationExample[]
  CachingProvider cachingProvider = Caching.getCachingProvider();
  EhcacheCachingProvider ehcacheProvider = (EhcacheCachingProvider) cachingProvider; // <1>

  DefaultConfiguration configuration = new DefaultConfiguration(ehcacheProvider.getDefaultClassLoader(),
    new DefaultPersistenceConfiguration(getPersistenceDirectory())); // <2>

  CacheManager cacheManager = ehcacheProvider.getCacheManager(ehcacheProvider.getDefaultURI(), configuration); // <3>
  // end::ehcacheCacheManagerConfigurationExample[]

  assertThat(cacheManager, notNullValue());
}
 
Example #18
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSysPropReplace() {
  System.getProperties().setProperty("ehcache.match", Number.class.getName());
  XmlConfiguration xmlConfig = new XmlConfiguration(XmlConfigurationTest.class.getResource("/configs/systemprops.xml"));

  assertThat(xmlConfig.getCacheConfigurations().get("bar").getKeyType(), sameInstance((Class)Number.class));

  DefaultPersistenceConfiguration persistenceConfiguration = (DefaultPersistenceConfiguration)xmlConfig.getServiceCreationConfigurations().iterator().next();
  assertThat(persistenceConfiguration.getRootDirectory(), is(new File(System.getProperty("user.home") + "/ehcache")));
}
 
Example #19
Source File: XmlConfigurationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistenceConfig() throws Exception {
  final URL resource = XmlConfigurationTest.class.getResource("/configs/persistence-config.xml");
  XmlConfiguration xmlConfig = new XmlConfiguration(new XmlConfiguration(resource));

  ServiceCreationConfiguration<?, ?> serviceConfig = xmlConfig.getServiceCreationConfigurations().iterator().next();
  assertThat(serviceConfig, instanceOf(DefaultPersistenceConfiguration.class));

  DefaultPersistenceConfiguration persistenceConfiguration = (DefaultPersistenceConfiguration)serviceConfig;
  assertThat(persistenceConfiguration.getRootDirectory(), is(new File("   \n\t/my/caching/persistence  directory\r\n      ")));
}
 
Example #20
Source File: EhcacheBaseTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private CacheManagerBuilder<CacheManager> baseCacheManagerConfig() {
  try {
    return CacheManagerBuilder.newCacheManagerBuilder()
      .using(new DefaultPersistenceConfiguration(diskPath.newFolder()))
      .using(statisticsService)
      .using(new TimeSourceConfiguration(timeSource));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #21
Source File: EhcacheBaseTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private void createNotAtomicCacheManager() throws IOException {
  Configuration config = ConfigurationBuilder.newConfigurationBuilder()
    .withService(new TimeSourceConfiguration(timeSource))
    .withService(new DefaultPersistenceConfiguration(diskPath.newFolder()))
    .build();

  Collection<Service> services = Collections.singleton(statisticsService);
  cacheManager = new EhcacheManager(config, services, false);
  cacheManager.init();
}
 
Example #22
Source File: DefaultLocalPersistenceServiceFactory.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Override
public DefaultLocalPersistenceService create(final ServiceCreationConfiguration<LocalPersistenceService, ?> serviceConfiguration) {
  return new DefaultLocalPersistenceService((DefaultPersistenceConfiguration) serviceConfiguration);
}
 
Example #23
Source File: StandardEhCacheStatisticsQueryTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws IOException {

  DefaultManagementRegistryConfiguration registryConfiguration = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCacheManager");
  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(registryConfiguration);

  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, resources)
    .withEvictionAdvisor((key, value) -> key.equals(2L))
    .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics to make sure they are there even when using only one tier
    .build();

  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("myCache", cacheConfiguration)
    .using(managementRegistry)
    .using(new DefaultPersistenceConfiguration(diskPath.newFolder()))
    .build(true)) {

    Context context = StatsUtil.createContext(managementRegistry);

    Cache<Long, String> cache = cacheManager.getCache("myCache", Long.class, String.class);

    cache.put(1L, "1");//put in lowest tier
    cache.put(2L, "2");//put in lowest tier
    cache.put(3L, "3");//put in lowest tier


    cache.get(1L);//HIT lowest tier
    cache.get(2L);//HIT lowest tier
    cache.get(2L);//HIT highest tier

    cache.get(1L);//HIT middle/highest tier. Depends on tier configuration.

    long tierHitCountSum = 0;
    for (int i = 0; i < statNames.size(); i++) {
      tierHitCountSum += getAndAssertExpectedValueFromCounter(statNames.get(i), context, managementRegistry, tierExpectedValues.get(i));
    }

    long cacheHitCount = getAndAssertExpectedValueFromCounter("Cache:HitCount", context, managementRegistry, cacheExpectedValue);
    Assert.assertThat(tierHitCountSum, is(cacheHitCount));

  }
}
 
Example #24
Source File: EhcacheSettingsProviderTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_standalone_ehcache() throws IOException {
  CacheConfiguration<String, String> cacheConfiguration1 = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(2, MemoryUnit.MB, true))
      .withExpiry(ExpiryPolicyBuilder.noExpiration())
      .build();

  CacheConfiguration<String, String> cacheConfiguration2 = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(2, MemoryUnit.MB, true))
      .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofHours(2)))
      .build();

  // ehcache cache manager
  DefaultManagementRegistryConfiguration serviceConfiguration = new DefaultManagementRegistryConfiguration()
    .setCacheManagerAlias("my-cm-1")
    .addTag("boo")
    .addTags("foo", "baz");

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(sharedManagementService)
      .using(new DefaultPersistenceConfiguration(ROOT.newFolder("test_standalone_ehcache")))
    .using(serviceConfiguration)
      .withCache("cache-1", cacheConfiguration1)
      .withCache("cache-2", cacheConfiguration2)
      .build(false);

  cacheManager.init();

  String expected = read("/settings-capability.json")
    .replaceAll("instance-id", serviceConfiguration.getInstanceId());
  String actual = mapper.writeValueAsString(getSettingsCapability())
    .replaceAll("\\\"cacheManagerDescription\\\":\\\".*\\\",\\\"instanceId\\\"", "\\\"cacheManagerDescription\\\":\\\"\\\",\\\"instanceId\\\"");

  // assertThat for formatted string comparison: ide support is bad
  assertEquals(expected, actual);
}