org.ehcache.CachePersistenceException Java Examples

The following examples show how to use org.ehcache.CachePersistenceException. 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: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDestroyCacheManagerDoesNotAffectsExistingCacheWithExistingClientsConnected() throws CachePersistenceException {

  CacheManagerBuilder<PersistentCacheManager> cacheManagerBuilder = clusteredCacheManagerBuilder
      .withCache("test", newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))));

  PersistentCacheManager persistentCacheManager1 = cacheManagerBuilder.build(true);
  try (PersistentCacheManager persistentCacheManager2 = cacheManagerBuilder.build(true)) {

    persistentCacheManager1.close();
    try {
      persistentCacheManager1.destroy();
      fail("StateTransitionException expected");
    } catch (StateTransitionException e) {
      assertThat(e.getMessage(), is("Couldn't acquire cluster-wide maintenance lease"));
    }

    Cache<Long, String> cache = persistentCacheManager2.getCache("test", Long.class, String.class);

    cache.put(1L, "One");

    assertThat(cache.get(1L), is("One"));
  }
}
 
Example #2
Source File: DefaultSerializationProviderTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private DefaultSerializationProvider getStartedProvider() throws CachePersistenceException {
  DefaultSerializationProvider defaultProvider = new DefaultSerializationProvider(null);

  @SuppressWarnings("unchecked")
  ServiceProvider<Service> serviceProvider = mock(ServiceProvider.class);
  DiskResourceService diskResourceService = mock(DiskResourceService.class);
  when(diskResourceService.createPersistenceContextWithin(any(PersistableResourceService.PersistenceSpaceIdentifier.class), anyString()))
        .thenReturn(() -> {
          try {
            return tempFolder.newFolder();
          } catch (IOException e) {
            fail("unable to create persistence ");
            return null;
          }
        });
  when(serviceProvider.getService(DiskResourceService.class)).thenReturn(diskResourceService);
  defaultProvider.start(serviceProvider);
  return defaultProvider;
}
 
Example #3
Source File: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoExpirationPropagatedToHigherTiers() throws CachePersistenceException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicyBuilder.noExpiration());

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

    Map<String, TierStatistics> tierStatistics = statisticsService.getCacheStatistics(CLUSTERED_CACHE).getTierStatistics();
    TierStatistics onheap = tierStatistics.get("OnHeap");
    TierStatistics offheap = tierStatistics.get("OffHeap");

    Cache<Long, String> cache = cacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);
    for (long i = 0; i < 30; i++) {
      cache.put(i, "value"); // store on the cluster
      cache.get(i); // push it up on heap and offheap tier
    }

    assertThat(onheap.getMappings()).isEqualTo(10);
    assertThat(offheap.getMappings()).isEqualTo(20);
  }
}
 
Example #4
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 #5
Source File: DefaultDiskResourceService.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public StateRepository getStateRepositoryWithin(PersistenceSpaceIdentifier<?> identifier, String name)
    throws CachePersistenceException {

  PersistenceSpace persistenceSpace = getPersistenceSpace(identifier);
  if(persistenceSpace == null) {
    throw newCachePersistenceException(identifier);
  }

  FileBasedStateRepository stateRepository = new FileBasedStateRepository(
      FileUtils.createSubDirectory(persistenceSpace.identifier.persistentSpaceId.getRoot(), name));
  FileBasedStateRepository previous = persistenceSpace.stateRepositories.putIfAbsent(name, stateRepository);
  if (previous != null) {
    return previous;
  }
  return stateRepository;
}
 
Example #6
Source File: DefaultDiskResourceService.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public void releasePersistenceSpaceIdentifier(PersistenceSpaceIdentifier<?> identifier) throws CachePersistenceException {
  String name = null;
  for (Map.Entry<String, PersistenceSpace> entry : knownPersistenceSpaces.entrySet()) {
    if (entry.getValue().identifier.equals(identifier)) {
      name = entry.getKey();
    }
  }
  if (name == null) {
    throw newCachePersistenceException(identifier);
  }
  PersistenceSpace persistenceSpace = knownPersistenceSpaces.remove(name);
  if (persistenceSpace != null) {
    for (FileBasedStateRepository stateRepository : persistenceSpace.stateRepositories.values()) {
      try {
        stateRepository.close();
      } catch (IOException e) {
        LOGGER.warn("StateRepository close failed - destroying persistence space {} to prevent corruption", identifier, e);
        persistenceService.destroySafeSpace(((DefaultPersistenceSpaceIdentifier)identifier).persistentSpaceId, true);
      }
    }
  }
}
 
Example #7
Source File: DefaultClusteringService.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public StateRepository getStateRepositoryWithin(PersistenceSpaceIdentifier<?> identifier, String name) throws CachePersistenceException {
  ClusteredCacheIdentifier clusterCacheIdentifier = (ClusteredCacheIdentifier) identifier;
  ClusteredSpace clusteredSpace = knownPersistenceSpaces.get(clusterCacheIdentifier.getId());
  if (clusteredSpace == null) {
    throw new PerpetualCachePersistenceException("Clustered space not found for identifier: " + clusterCacheIdentifier);
  }
  ConcurrentMap<String, ClusterStateRepository> stateRepositories = clusteredSpace.stateRepositories;
  ClusterStateRepository currentRepo = stateRepositories.get(name);
  if(currentRepo != null) {
    return currentRepo;
  } else {
    ClusterStateRepository newRepo = new ClusterStateRepository(clusterCacheIdentifier, name,
            connectionState.getClusterTierClientEntity(clusterCacheIdentifier.getId()));
    currentRepo = stateRepositories.putIfAbsent(name, newRepo);
    if (currentRepo == null) {
      return newRepo;
    } else {
      return currentRepo;
    }
  }
}
 
Example #8
Source File: EhcacheManager.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
/**
 * Perform cache closure actions specific to a cache manager implementation.
 * This method is called <i>after</i> the {@code InternalCache} instance is closed.
 *
 * @param alias the cache alias
 * @param ehcache the {@code InternalCache} instance for the cache to close
 */
protected void closeEhcache(final String alias, final InternalCache<?, ?> ehcache) {
  for (ResourceType<?> resourceType : ehcache.getRuntimeConfiguration().getResourcePools().getResourceTypeSet()) {
    if (resourceType.isPersistable()) {
      ResourcePool resourcePool = ehcache.getRuntimeConfiguration()
          .getResourcePools()
          .getPoolForResource(resourceType);
      if (!resourcePool.isPersistent()) {
        PersistableResourceService persistableResourceService = getPersistableResourceService(resourceType);
        try {
          persistableResourceService.destroy(alias);
        } catch (CachePersistenceException e) {
          LOGGER.warn("Unable to clear persistence space for cache {}", alias, e);
        }
      }
    }
  }
}
 
Example #9
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDestroyCacheFailsAndStopIfStartingServicesFails() throws CachePersistenceException, InterruptedException {
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  List<Service> services = minimumCacheManagerServices();
  MaintainableService service = mock(MaintainableService.class);
  doThrow(new RuntimeException("failed")).when(service)
    .startForMaintenance(Mockito.<ServiceProvider<MaintainableService>>any(), eq(MaintainableService.MaintenanceScope.CACHE));
  services.add(service);

  EhcacheManager manager = new EhcacheManager(config, services);

  expectedException.expect(StateTransitionException.class);
  expectedException.expectMessage("failed");

  manager.destroyCache("test");

  assertThat(manager.getStatus(), equalTo(Status.UNINITIALIZED));
}
 
Example #10
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 #11
Source File: ClusteredCacheDestroyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyCacheWithCacheManagerStopped() throws CachePersistenceException {
  PersistentCacheManager persistentCacheManager = clusteredCacheManagerBuilder.build(true);
  persistentCacheManager.close();
  persistentCacheManager.destroyCache(CLUSTERED_CACHE);
  assertThat(persistentCacheManager.getStatus(), is(Status.UNINITIALIZED));
}
 
Example #12
Source File: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutIfAbsentExpirationPropagatedToHigherTiers() throws CachePersistenceException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = cacheManagerBuilder(oneSecondExpiration());

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {
    Cache<Long, String> cache = cacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);
    cache.put(1L, "value"); // store on the cluster
    cache.putIfAbsent(1L, "newvalue"); // push it up on heap tier
    timeSource.advanceTime(1500); // go after expiration
    assertThat(cache.get(1L)).isEqualTo(null); // the value should have expired
  }
}
 
Example #13
Source File: ClusteredCacheDestroyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyNonExistentCacheWithCacheManagerStopped() throws CachePersistenceException {
  PersistentCacheManager persistentCacheManager = clusteredCacheManagerBuilder.build(true);
  persistentCacheManager.close();
  persistentCacheManager.destroyCache("this-is-not-the-cache-you-are-looking-for");
  assertThat(persistentCacheManager.getStatus(), is(Status.UNINITIALIZED));
}
 
Example #14
Source File: ClusteredCacheDestroyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyCacheWhenSingleClientIsConnected() throws CachePersistenceException {
  try (PersistentCacheManager persistentCacheManager = clusteredCacheManagerBuilder.build(true)) {

    persistentCacheManager.destroyCache(CLUSTERED_CACHE);

    final Cache<Long, String> cache = persistentCacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);

    assertThat(cache, nullValue());
  }
}
 
Example #15
Source File: FileBasedStateRepository.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
FileBasedStateRepository(File directory) throws CachePersistenceException {
  if (directory == null) {
    throw new NullPointerException("directory must be non null");
  }
  if (!directory.isDirectory()) {
    throw new IllegalArgumentException(directory + " is not a directory");
  }
  this.dataDirectory = directory;
  knownHolders = new ConcurrentHashMap<>();
  loadMaps();
}
 
Example #16
Source File: ClusterTierManagerClientEntityFactory.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public void destroyClusteredStoreEntity(String clusterTierManagerIdentifier, String storeIdentifier) throws EntityNotFoundException, CachePersistenceException {
  EntityRef<InternalClusterTierClientEntity, ClusterTierEntityConfiguration, Void> entityRef;
  try {
    entityRef = connection.getEntityRef(InternalClusterTierClientEntity.class, ENTITY_VERSION, entityName(clusterTierManagerIdentifier, storeIdentifier));
    if (!entityRef.destroy()) {
      throw new CachePersistenceException("Cannot destroy cluster tier '" + storeIdentifier + "': in use by other client(s)");
    }
  } catch (EntityNotProvidedException | PermanentEntityException e) {
    throw new AssertionError(e);
  }
}
 
Example #17
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test @SuppressWarnings("try")
public void testAllClientsNeedToHaveLoaderWriterConfigured() {
  TestCacheLoaderWriter loaderWriter = new TestCacheLoaderWriter();
  CacheConfiguration<Long, String> cacheConfiguration = getCacheConfiguration(loaderWriter);

  try (CacheManager cacheManager = CacheManagerBuilder
          .newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("cache-1", cacheConfiguration)
          .build(true)) {

    CacheConfiguration<Long, String> withoutLoaderWriter = newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder
        .newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(1, MemoryUnit.MB)
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
      .withResilienceStrategy(new ThrowingResilienceStrategy<>())
      .build();

    try (CacheManager anotherManager = CacheManagerBuilder
        .newCacheManagerBuilder()
        .with(cluster(CLUSTER_URI).autoCreate(c -> c))
        .withCache("cache-1", withoutLoaderWriter)
        .build(true)) {
    } catch (RuntimeException e) {
      assertThat(e.getCause().getCause().getCause().getCause(), instanceOf(CachePersistenceException.class));
      assertThat(e.getCause().getCause().getCause().getCause().getCause(), instanceOf(ClusterTierValidationException.class));
    }
  }
}
 
Example #18
Source File: ClusteredStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
synchronized void setStoreProxy(ServerStoreProxy storeProxy) throws CachePersistenceException {
  if (storeProxy != null && listenerCounter > 0) {
    try {
      storeProxy.enableEvents(true);
    } catch (TimeoutException te) {
      throw new CachePersistenceException("Error enabling events", te);
    }
  }
  this.storeProxy = storeProxy;
}
 
Example #19
Source File: EHCacheXKMSClientCache.java    From cxf with Apache License 2.0 5 votes vote down vote up
public synchronized void close() {
    if (cacheManager.getStatus() == Status.AVAILABLE) {
        cacheManager.removeCache(cacheKey);
        cacheManager.close();

        if (!persistent && cacheManager instanceof PersistentCacheManager) {
            try {
                ((PersistentCacheManager) cacheManager).destroy();
            } catch (CachePersistenceException e) {
                LOG.debug("Error in shutting down persistent cache", e);
            }

            // As we're not using a persistent disk store, just delete it - it should be empty after calling
            // destroy above
            if (diskstorePath != null) {
                File file = diskstorePath.toFile();
                if (file.exists() && file.canWrite()) {
                    file.delete();
                }
            }
        }

        if (bus != null) {
            bus.getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
        }
    }
}
 
Example #20
Source File: TieredStoreWith3TiersSPITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws CachePersistenceException {
  try {
    for (Map.Entry<Store<String, String>, String> entry : createdStores.entrySet()) {
      provider.releaseStore(entry.getKey());
      diskResourceService.destroy(entry.getValue());
    }
  } finally {
    diskResourceService.stop();
  }
}
 
Example #21
Source File: ClusteredStore.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public void initStore(Store<?, ?> resource) {
  try {
    initStoreInternal(resource);
  } catch (CachePersistenceException e) {
    throw new RuntimeException(e);
  }
}
 
Example #22
Source File: OffHeapDiskStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private FileBasedPersistenceContext getPersistenceContext() {
  try {
    CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);
    when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MB, false).build());
    PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration);
    return diskResourceService.createPersistenceContextWithin(space, "store");
  } catch (CachePersistenceException e) {
    throw new AssertionError(e);
  }
}
 
Example #23
Source File: OffHeapDiskStoreSPITest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws CachePersistenceException, IOException {
  try {
    for (Map.Entry<Store<String, String>, String> entry : createdStores.entrySet()) {
      OffHeapDiskStore.Provider.close((OffHeapDiskStore<String, String>) entry.getKey());
      diskResourceService.destroy(entry.getValue());
    }
  } finally {
    diskResourceService.stop();
  }
}
 
Example #24
Source File: PersistentUserManagedEhcache.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
   * {@inheritDoc}
   */
  @Override
  public void destroy() throws CachePersistenceException {
    StatusTransitioner.Transition st = statusTransitioner.maintenance();
    try {
      st.succeeded();
    } catch (Throwable t) {
      throw st.failed(t);
    }
    destroyInternal();
    // Exit maintenance mode once #934 is solved
//    statusTransitioner.exitMaintenance().succeeded();
  }
 
Example #25
Source File: PersistentUserManagedEhcache.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
void create() {
  statusTransitioner.checkMaintenance();
  try {
    if (!getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent()) {
      destroy();
    }
    diskPersistenceService.getPersistenceSpaceIdentifier(id, cache.getRuntimeConfiguration());
  } catch (CachePersistenceException e) {
    throw new RuntimeException("Unable to create persistence space for user managed cache " + id, e);
  }
}
 
Example #26
Source File: PersistentUserManagedEhcache.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void close() {
  cache.close();
  if (!getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent()) {
    try {
      diskPersistenceService.destroy(id);
    } catch (CachePersistenceException e) {
      logger.debug("Unable to clear persistence space for user managed cache {}", id, e);
    }
  }
}
 
Example #27
Source File: DefaultClusteringService.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public void releasePersistenceSpaceIdentifier(PersistenceSpaceIdentifier<?> identifier) throws CachePersistenceException {
  ClusteredCacheIdentifier clusterCacheIdentifier = (ClusteredCacheIdentifier) identifier;
  if (knownPersistenceSpaces.remove(clusterCacheIdentifier.getId()) == null) {
    throw new PerpetualCachePersistenceException("Unknown identifier: " + clusterCacheIdentifier);
  }
}
 
Example #28
Source File: DefaultClusteringService.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyAll() throws CachePersistenceException {
  if (!inMaintenance) {
    throw new IllegalStateException("Maintenance mode required");
  }
  connectionState.destroyAll();
}
 
Example #29
Source File: EhcacheManager.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
void destroyInternal() throws CachePersistenceException {
  statusTransitioner.checkMaintenance();
  Collection<PersistableResourceService> services = serviceLocator.getServicesOfType(PersistableResourceService.class);
  for (PersistableResourceService service : services) {
    service.destroyAll();
  }
}
 
Example #30
Source File: DefaultClusteringServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetStateRepositoryWithinWithNonExistentPersistenceSpaceIdentifier() throws Exception {
  expectedException.expect(CachePersistenceException.class);
  expectedException.expectMessage("Clustered space not found for identifier");
  ClusteringServiceConfiguration configuration =
    ClusteringServiceConfigurationBuilder.cluster(URI.create(CLUSTER_URI_BASE))
      .autoCreate(s -> s)
      .build();
  DefaultClusteringService service = new DefaultClusteringService(configuration);
  ClusteredCacheIdentifier cacheIdentifier = mock(ClusteredCacheIdentifier.class);
  doReturn("foo").when(cacheIdentifier).getId();
  service.getStateRepositoryWithin(cacheIdentifier, "myRepo");
}