org.ehcache.Status Java Examples

The following examples show how to use org.ehcache.Status. 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: ArbitraryCacheManagerTest.java    From ehcache-shiro with Apache License 2.0 6 votes vote down vote up
/**
 * Test showing issues:
 * <p>
 * https://github.com/ehcache/ehcache-shiro/issues/12
 * https://github.com/ehcache/ehcache-shiro/issues/13
 *
 * @throws Exception
 */
@Test
public void testArbitraryCacheManager() throws Exception {
  ehcacheShiroManager.init();
  CacheManager firstCacheManager = ehcacheShiroManager.getCacheManager();
  Assert.assertNotNull(firstCacheManager);

  ehcacheShiroManager.setCacheManager(cacheManager);
  CacheManager secondCacheManager = ehcacheShiroManager.getCacheManager();
  Assert.assertNotSame(firstCacheManager, secondCacheManager);
  Assert.assertNotEquals(firstCacheManager, secondCacheManager);

  ehcacheShiroManager.destroy();

  Assert.assertEquals(Status.UNINITIALIZED, firstCacheManager.getStatus());
  Assert.assertEquals(Status.AVAILABLE, secondCacheManager.getStatus());
}
 
Example #2
Source File: DefaultStatisticsService.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public void stateTransition(Status from, Status to) {
  LOGGER.debug("Moving from " + from + " to " + to);
  switch (to) {
    case AVAILABLE:
      registerAllCaches();
      break;
    case UNINITIALIZED:
      cacheManager.deregisterListener(this);
      cacheStatistics.clear();
      break;
    case MAINTENANCE:
      throw new IllegalStateException("Should not be started in maintenance mode");
    default:
      throw new AssertionError("Unsupported state: " + to);
  }
}
 
Example #3
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransitionDuringFailures() {
  StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  assertThat(transitioner.currentStatus(), CoreMatchers.is(Status.UNINITIALIZED));
  StatusTransitioner.Transition st = transitioner.init();
  st.failed(new Throwable());
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));
  try {
    st.failed(new Throwable());
    fail();
  } catch (AssertionError err) {
    assertThat(err.getMessage(), is("Throwable cannot be thrown if Transition is done."));
  }

  st.failed(null);
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));

  StatusTransitioner.Transition st1 = transitioner.init();
  assertThat(transitioner.currentStatus(), is(Status.AVAILABLE));
  st1.failed(null);
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));

}
 
Example #4
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckAvailableAccountsForThreadLease() throws InterruptedException {
  final StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  transitioner.maintenance().succeeded();
  transitioner.checkAvailable();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        transitioner.checkAvailable();
        fail();
      } catch (IllegalStateException e) {
        assertThat(e.getMessage().contains(Status.MAINTENANCE.name()), is(true));
        assertThat(e.getMessage().contains("own"), is(true));
      }
    }
  };
  thread.start();
  thread.join();
  transitioner.close();
}
 
Example #5
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaintenanceOnlyOwningThreadCanClose() throws InterruptedException {
  final StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  transitioner.maintenance().succeeded();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        transitioner.close();
        fail();
      } catch (IllegalStateException e) {
        assertThat(e.getMessage().contains(Status.MAINTENANCE.name()), is(true));
        assertThat(e.getMessage().contains("own"), is(true));
      }
    }
  };
  thread.start();
  thread.join();
  transitioner.close();
}
 
Example #6
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaintenanceOnlyLetsTheOwningThreadInteract() throws InterruptedException {
  final StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  transitioner.maintenance().succeeded();
  transitioner.checkMaintenance();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        transitioner.checkMaintenance();
        fail();
      } catch (IllegalStateException e) {
        assertThat(e.getMessage().contains(Status.MAINTENANCE.name()), is(true));
        assertThat(e.getMessage().contains("own"), is(true));
      }
    }
  };
  thread.start();
  thread.join();
}
 
Example #7
Source File: CacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailingTransitionGoesToLowestStatus() throws Exception {
  final LifeCycled mock = mock(LifeCycled.class);
  InternalCache ehcache = getCache(mock(Store.class));
  doThrow(new Exception()).when(mock).init();
  ehcache.addHook(mock);
  try {
    ehcache.init();
    fail();
  } catch (StateTransitionException e) {
    assertThat(ehcache.getStatus(), is(Status.UNINITIALIZED));
  }

  reset(mock);
  ehcache.init();
  assertThat(ehcache.getStatus(), is(Status.AVAILABLE));
  ehcache.close();
}
 
Example #8
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseCacheManagerMultipleClients() {
  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)) {

    Cache<Long, String> cache = persistentCacheManager1.getCache("test", Long.class, String.class);
    cache.put(1L, "One");

    assertThat(cache.get(1L), is("One"));

    persistentCacheManager1.close();
    assertThat(persistentCacheManager1.getStatus(), is(Status.UNINITIALIZED));

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

    assertThat(cache2.get(1L), is("One"));
  }
}
 
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: DefaultClusteringManagementService.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public void stateTransition(Status from, Status to) {
  // we are only interested when cache manager is initializing (but at the end of the initialization)
  switch (to) {

    case AVAILABLE: {
      nmsAgentService = createNmsAgentService();
      nmsAgentService.sendStates();
      nmsAgentService.setTags(managementRegistryService.getConfiguration().getTags());
      break;
    }

    case UNINITIALIZED: {
      this.cacheManager.deregisterListener(this);
      break;
    }

    case MAINTENANCE:
      // in case we need management capabilities in maintenance mode
      break;

    default:
      throw new AssertionError("Unsupported state: " + to);
  }
}
 
Example #11
Source File: TestTransportFormat.java    From javamelody with Apache License 2.0 6 votes vote down vote up
/** Test.
 * @throws IOException e
 * @throws ClassNotFoundException e */
@Test
public void testReadSerializable() throws IOException, ClassNotFoundException {
	final Counter counter = createCounter();
	final Counter after = (Counter) serialize(counter);
	assertEquals("counter", counter.toString(), after.toString());

	assertNull("null", serialize(null));

	final String[][] array = {};
	assertArrayEquals("array", array, (String[][]) serialize(array));
	final boolean[] barray = {};
	assertArrayEquals("boolean", barray, (boolean[]) serialize(barray));
	final File file = new File("test");
	assertEquals("file", file, serialize(file));
	try {
		// objects from not white-listed packages should not be deserialized
		assertNull("should not return a result", serialize(Status.UNINITIALIZED));
	} catch (final ClassNotFoundException e) {
		assertNotNull("e", e);
	}
}
 
Example #12
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyCacheManagerWithMultipleClients() throws CachePersistenceException {
  PersistentCacheManager persistentCacheManager1 = clusteredCacheManagerBuilder.build(true);
  try (PersistentCacheManager persistentCacheManager2 = clusteredCacheManagerBuilder.build(true)) {

    persistentCacheManager1.close();

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

    assertThat(persistentCacheManager1.getStatus(), is(Status.UNINITIALIZED));

    assertThat(persistentCacheManager2.getStatus(), is(Status.AVAILABLE));

    Cache<Long, String> cache = persistentCacheManager2.createCache("test", newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))));

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

    assertThat(cache.get(1L), is("One"));
  }
}
 
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 testDestroyCacheWithCacheManagerStopped() throws CachePersistenceException {
  PersistentCacheManager persistentCacheManager = clusteredCacheManagerBuilder.build(true);
  persistentCacheManager.close();
  persistentCacheManager.destroyCache(CLUSTERED_CACHE);
  assertThat(persistentCacheManager.getStatus(), is(Status.UNINITIALIZED));
}
 
Example #15
Source File: EhcacheBasicIteratorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an initialized {@link InternalCache Ehcache} instance using a
 * mock {@link CacheLoaderWriter} instance which throws for any method called.
 *
 * @return a new {@code Ehcache} instance
 */
@SuppressWarnings("unchecked")
protected InternalCache<String, String> getEhcache() throws Exception {
  final Ehcache<String, String> ehcache = new Ehcache<>(CACHE_CONFIGURATION, this.store, resilienceStrategy, cacheEventDispatcher, LoggerFactory
    .getLogger(Ehcache.class + "-" + "EhcacheBasicIteratorTest"));
  ehcache.init();
  assertThat("cache not initialized", ehcache.getStatus(), Matchers.is(Status.AVAILABLE));
  return ehcache;
}
 
Example #16
Source File: BasicClusteredCacheOpsReplicationMultiThreadedTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
  List<Runnable> unprocessed = executorService.shutdownNow();
  if(!unprocessed.isEmpty()) {
    log.warn("Tearing down with {} unprocess task", unprocessed);
  }
  if(cacheManager1 != null && cacheManager1.getStatus() != Status.UNINITIALIZED) {
    cacheManager1.close();
  }
  if(cacheManager2 != null && cacheManager2.getStatus() != Status.UNINITIALIZED) {
    cacheManager2.close();
  }
}
 
Example #17
Source File: AbstractClusteringManagementTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private static void tearDownCacheManagerAndStatsCollector() throws Exception {
  if (cacheManager != null && cacheManager.getStatus() == Status.AVAILABLE) {

    readTopology().getClient(ehcacheClientIdentifier)
      .ifPresent(client -> {
        try {
          CLUSTER.getNmsService().stopStatisticCollector(client.getContext().with("cacheManagerName", "my-super-cache-manager")).waitForReturn();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      });

    cacheManager.close();
  }
}
 
Example #18
Source File: CMClosedEventSentTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60_000)
public void test_CACHE_MANAGER_CLOSED() throws Exception {
  try (CacheManager cacheManager = newCacheManagerBuilder().with(cluster(CLUSTER.getCluster().getConnectionURI().resolve("/my-server-entity-1"))
    .autoCreate(server -> server
      .defaultServerResource("primary-server-resource")
      .resourcePool("resource-pool-a", 10, MemoryUnit.MB, "secondary-server-resource") // <2>
      .resourcePool("resource-pool-b", 10, MemoryUnit.MB))) // will take from primary-server-resource
    // management config
    .using(new DefaultManagementRegistryConfiguration()
      .addTags("webapp-1", "server-node-1")
      .setCacheManagerAlias("my-super-cache-manager"))
    // cache config
    .withCache("dedicated-cache-1", newCacheConfigurationBuilder(
      String.class, String.class,
      newResourcePoolsBuilder()
        .heap(10, EntryUnit.ENTRIES)
        .offheap(1, MemoryUnit.MB)
        .with(clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB)))
      .build())
    .build(true)) {

    assertThat(cacheManager.getStatus(), equalTo(Status.AVAILABLE));
    waitFor("CACHE_MANAGER_AVAILABLE");

  }
  waitFor("CACHE_MANAGER_CLOSED");
}
 
Example #19
Source File: EHCacheIdentityCache.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(KEY);
        cacheManager.close();

        if (super.getBus() != null) {
            super.getBus().getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
        }
    }
}
 
Example #20
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 #21
Source File: EHCacheSPStateManager.java    From cxf with Apache License 2.0 5 votes vote down vote up
public synchronized void close() throws IOException {
    if (requestCacheManager.getStatus() == Status.AVAILABLE) {
        requestCacheManager.removeCache(REQUEST_CACHE_KEY);
        requestCacheManager.close();
    }
    if (responseCacheManager.getStatus() == Status.AVAILABLE) {
        responseCacheManager.removeCache(RESPONSE_CACHE_KEY);
        responseCacheManager.close();
    }
}
 
Example #22
Source File: ArbitraryCacheManagerTest.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultCacheManager() throws Exception {
  ehcacheShiroManager.init();
  CacheManager cacheManager = ehcacheShiroManager.getCacheManager();

  Assert.assertNotNull(cacheManager);
  Assert.assertEquals(Status.AVAILABLE, cacheManager.getStatus());

  ehcacheShiroManager.destroy();
  Assert.assertEquals(Status.UNINITIALIZED, cacheManager.getStatus());
}
 
Example #23
Source File: EhcacheBasicClearTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an initialized {@link Ehcache Ehcache}
 *
 * @return a new {@code Ehcache} instance
 */
private Ehcache<String, String> getEhcache()
    throws Exception {
  final Ehcache<String, String> ehcache =
    new Ehcache<>(CACHE_CONFIGURATION, this.store, resilienceStrategy, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBasicClearTest"));
  ehcache.init();
  assertThat("cache not initialized", ehcache.getStatus(), Matchers.is(Status.AVAILABLE));
  return ehcache;
}
 
Example #24
Source File: EhcacheBasicPutIfAbsentTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an initialized {@link Ehcache Ehcache} instance
 *
 * @return a new {@code Ehcache} instance
 */
private Ehcache<String, String> getEhcache() {
  final Ehcache<String, String> ehcache = new Ehcache<>(CACHE_CONFIGURATION, this.store, resilienceStrategy, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBasicPutIfAbsentTest"));
  ehcache.init();
  assertThat("cache not initialized", ehcache.getStatus(), Matchers.is(Status.AVAILABLE));
  return ehcache;
}
 
Example #25
Source File: EhCacheIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    if (cacheManager != null) {
        if (!cacheManager.getStatus().equals(Status.UNINITIALIZED)) {
            cacheManager.close();
        }
        context.unbind("cacheManager");
    }
}
 
Example #26
Source File: EhcacheBasicPutAllTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an initialized {@link Ehcache Ehcache} instance
 *
 * @return a new {@code Ehcache} instance
 */
private Ehcache<String, String> getEhcache() {
  final Ehcache<String, String> ehcache = new Ehcache<>(CACHE_CONFIGURATION, this.store, resilienceStrategy, cacheEventDispatcher, LoggerFactory
    .getLogger(Ehcache.class + "-" + "EhcacheBasicPutAllTest"));
  ehcache.init();
  assertThat("cache not initialized", ehcache.getStatus(), Matchers.is(Status.AVAILABLE));
  return ehcache;
}
 
Example #27
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFinishesTransitionOnListenerThrowing() {
  StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  final StateChangeListener listener = mock(StateChangeListener.class);
  final RuntimeException runtimeException = new RuntimeException();
  doThrow(runtimeException).when(listener).stateTransition(Status.UNINITIALIZED, Status.AVAILABLE);
  transitioner.registerListener(listener);
  try {
    transitioner.init().succeeded();
    fail();
  } catch (RuntimeException e) {
    assertThat(e, is(runtimeException));
  }
  assertThat(transitioner.currentStatus(), is(Status.AVAILABLE));
}
 
Example #28
Source File: EhcacheBasicRemoveTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an initialized {@link Ehcache Ehcache} instance
 *
 * @return a new {@code Ehcache} instance
 */
@SuppressWarnings("unchecked")
private Ehcache<String, String> getEhcache() {
  final Ehcache<String, String> ehcache = new Ehcache<>(CACHE_CONFIGURATION, this.store, resilienceStrategy, cacheEventDispatcher, LoggerFactory
    .getLogger(Ehcache.class + "-" + "EhcacheBasicRemoveTest"));
  ehcache.init();
  assertThat("cache not initialized", ehcache.getStatus(), CoreMatchers.is(Status.AVAILABLE));
  return ehcache;
}
 
Example #29
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFiresListeners() {
  StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  final StateChangeListener listener = mock(StateChangeListener.class);
  transitioner.registerListener(listener);
  transitioner.init().succeeded();
  verify(listener).stateTransition(Status.UNINITIALIZED, Status.AVAILABLE);
  reset(listener);
  transitioner.deregisterListener(listener);
  transitioner.close().succeeded();
  verify(listener, never()).stateTransition(Status.AVAILABLE, Status.UNINITIALIZED);
}
 
Example #30
Source File: StatusTransitionerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransitionsToLowestStateOnFailure() {
  StatusTransitioner transitioner = new StatusTransitioner(LoggerFactory.getLogger(StatusTransitionerTest.class));
  assertThat(transitioner.currentStatus(), CoreMatchers.is(Status.UNINITIALIZED));
  transitioner.init().failed(new Throwable());
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));
  transitioner.init().succeeded();
  assertThat(transitioner.currentStatus(), is(Status.AVAILABLE));
  transitioner.close().failed(new Throwable());
  assertThat(transitioner.currentStatus(), is(Status.UNINITIALIZED));
}