public void testCorrectShutdown() {
    CacheContainer cc = null;

    try {
      ConfigurationBuilder cfg = new ConfigurationBuilder();
      cfg.transaction()
          .transactionMode(TransactionMode.TRANSACTIONAL)
          .indexing()
          .index(Index.ALL)
          .addProperty("default.directory_provider", "ram")
          .addProperty("lucene_version", "LUCENE_CURRENT");
      cc = TestCacheManagerFactory.createCacheManager(cfg);
      Cache<?, ?> cache = cc.getCache();
      SearchFactoryIntegrator sfi =
          TestingUtil.extractComponent(cache, SearchFactoryIntegrator.class);

      assert !sfi.isStopped();

      cc.stop();

      assert sfi.isStopped();
    } finally {
      // proper cleanup for exceptional execution
      TestingUtil.killCacheManagers(cc);
    }
  }
 @BeforeClass
 public void createBeforeClass() {
   cacheManager = CacheTestSupport.createLocalCacheManager();
   metadataCache = cacheManager.getCache("metadata");
   chunkCache = cacheManager.getCache("chunks");
   lockCache = cacheManager.getCache("locks");
 }
示例#3
0
 public void testValuesAfterExpiryInTransaction(Method m) throws Exception {
   CacheContainer cc = createTransactionalCacheContainer();
   try {
     doValuesAfterExpiryInTransaction(m, cc);
   } finally {
     cc.stop();
   }
 }
 public void testCustomCacheManagerName(Method m) throws Exception {
   final String otherJmxDomain = getMethodSpecificJmxDomain(m, JMX_DOMAIN);
   CacheContainer otherContainer =
       TestCacheManagerFactory.createCacheManagerEnforceJmxDomain(
           otherJmxDomain, "Hibernate2LC", true, false);
   ObjectName otherName = getCacheManagerObjectName(otherJmxDomain, "Hibernate2LC");
   try {
     assert server.getAttribute(otherName, "CreatedCacheCount").equals("0");
   } finally {
     otherContainer.stop();
   }
 }
  @Test(expectedExceptions = CacheConfigurationException.class)
  public void testSyncAndAsyncElements() throws IOException {
    String xml =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<infinispan>"
            + "<global><transport /></global>"
            + "<default><clustering><sync /><async /></clustering></default></infinispan>";

    InputStream stream = new ByteArrayInputStream(xml.getBytes());
    CacheContainer cc = TestCacheManagerFactory.fromStream(stream);
    cc.getCache();
  }
示例#6
0
  @BeforeMethod(alwaysRun = true)
  public void setUp() throws Exception {
    Configuration c = new Configuration();
    c.fluent().transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
    c.setCacheMode(Configuration.CacheMode.LOCAL);
    c.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
    cm = TestCacheManagerFactory.createCacheManager(c);

    cache = cm.getCache();
    skipListenerCache = cm.getCache().getAdvancedCache().withFlags(Flag.SKIP_LISTENER_NOTIFICATION);
    mockNotifier = mock(CacheNotifier.class);
    origNotifier = TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true);
  }
  public void testInitialStateTransferInDifferentThread(Method m) throws Exception {
    testCount++;
    log.info(m.getName() + " start - " + testCount);
    CacheContainer cm1 = null, cm2 = null, cm30 = null;
    try {
      Cache<Object, Object> cache1 = null, cache2 = null, cache3 = null;
      cm1 = createCacheManager(tmpDirectory1);
      cache1 = cm1.getCache(cacheName);
      writeInitialData(cache1);

      cm2 = createCacheManager(tmpDirectory2);
      cache2 = cm2.getCache(cacheName);

      cache1.put("delay", new StateTransferFunctionalTest.DelayTransfer());

      // Pause to give caches time to see each other
      TestingUtil.blockUntilViewsReceived(60000, cache1, cache2);
      verifyInitialData(cache2);

      final CacheContainer cm3 = createCacheManager(tmpDirectory3);

      cm30 = cm3;

      Future<Void> f1 =
          Executors.newSingleThreadExecutor(
                  new ThreadFactory() {
                    public Thread newThread(Runnable r) {
                      return new Thread(r, "CacheStarter-Cache3");
                    }
                  })
              .submit(
                  new Callable<Void>() {
                    public Void call() throws Exception {
                      cm3.getCache(cacheName);
                      return null;
                    }
                  });

      f1.get();

      cache3 = cm3.getCache(cacheName);

      TestingUtil.blockUntilViewsReceived(120000, cache1, cache2, cache3);
      verifyInitialData(cache3);
      log.info("testConcurrentStateTransfer end - " + testCount);
    } finally {
      if (cm1 != null) cm1.stop();
      if (cm2 != null) cm2.stop();
      if (cm30 != null) cm30.stop();
    }
  }
  /** @return gets the registry cache */
  private Cache<Object, Object> getCache() {
    if (cache != null) {
      return cache;
    }

    try {
      InitialContext ic = new InitialContext();
      CacheContainer container = (CacheContainer) ic.lookup(cacheContainer);
      cache = container.getCache(cacheName);
      return cache;
    } catch (NamingException e) {
      throw new RuntimeException(e);
    }
  }
  @Test
  public void testReadWholeFile() throws IOException {
    final int BUFFER_SIZE = 64;

    Cache cache = cacheManager.getCache();
    InfinispanDirectory dir = new InfinispanDirectory(cache, cache, cache, INDEXNAME, BUFFER_SIZE);

    verifyOnBuffer("SingleChunk.txt", 61, BUFFER_SIZE, cache, dir, 15);

    final int VERY_BIG_FILE_SIZE = 10000;
    assert BUFFER_SIZE < VERY_BIG_FILE_SIZE;
    verifyOnBuffer("MultipleChunks.txt", VERY_BIG_FILE_SIZE, BUFFER_SIZE, cache, dir, 33);

    final int LAST_CHUNK_COMPLETELY_FILLED_FILE_SIZE = 256;
    assert (LAST_CHUNK_COMPLETELY_FILLED_FILE_SIZE % BUFFER_SIZE) == 0;
    verifyOnBuffer(
        "LastChunkFilled.txt", LAST_CHUNK_COMPLETELY_FILLED_FILE_SIZE, BUFFER_SIZE, cache, dir, 11);
    assertHasNChunks(4, cache, INDEXNAME, "LastChunkFilled.txt.bak", BUFFER_SIZE);
    DirectoryIntegrityCheck.verifyDirectoryStructure(cache, INDEXNAME);

    final int LAST_CHUNK_WITH_LONELY_BYTE_FILE_SIZE = 257;
    assert (LAST_CHUNK_WITH_LONELY_BYTE_FILE_SIZE % BUFFER_SIZE) == 1;
    verifyOnBuffer(
        "LonelyByteInLastChunk.txt",
        LAST_CHUNK_WITH_LONELY_BYTE_FILE_SIZE,
        BUFFER_SIZE,
        cache,
        dir,
        12);
    assertHasNChunks(5, cache, INDEXNAME, "LonelyByteInLastChunk.txt.bak", BUFFER_SIZE);

    dir.close();
    DirectoryIntegrityCheck.verifyDirectoryStructure(cache, INDEXNAME);
  }
 public void multipleFlushTest() throws IOException {
   final String filename = "longFile.writtenInMultipleFlushes";
   final int bufferSize = 300;
   Cache cache = cacheManager.getCache();
   cache.clear();
   Directory dir =
       DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEXNAME)
           .chunkSize(13)
           .create();
   byte[] manyBytes = fillBytes(bufferSize);
   IndexOutput indexOutput = dir.createOutput(filename);
   for (int i = 0; i < 10; i++) {
     indexOutput.writeBytes(manyBytes, bufferSize);
     indexOutput.flush();
   }
   indexOutput.close();
   IndexInput input = dir.openInput(filename);
   final int finalSize = (10 * bufferSize);
   AssertJUnit.assertEquals(finalSize, input.length());
   final byte[] resultingBuffer = new byte[finalSize];
   input.readBytes(resultingBuffer, 0, finalSize);
   int index = 0;
   for (int i = 0; i < 10; i++) {
     for (int j = 0; j < bufferSize; j++)
       AssertJUnit.assertEquals(resultingBuffer[index++], manyBytes[j]);
   }
 }
示例#11
0
  public void testKeySetAfterExpiryInPut(Method m) throws Exception {
    Cache<Integer, String> cache = cm.getCache();
    Set<Integer> keys;
    Map dataIn = new HashMap();
    dataIn.put(1, v(m, 1));
    dataIn.put(2, v(m, 2));
    Set keysIn = dataIn.keySet();

    final long startTime = System.currentTimeMillis();
    final long lifespan = EXPIRATION_TIMEOUT;
    cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);

    keys = Collections.emptySet();
    while (true) {
      keys = cache.keySet();
      if (System.currentTimeMillis() >= startTime + lifespan) break;
      assertEquals(keysIn, keys);
      Thread.sleep(100);
    }

    // Make sure that in the next 20 secs data is removed
    while (System.currentTimeMillis() < startTime + lifespan + EVICTION_CHECK_TIMEOUT) {
      keys = cache.keySet();
      if (keys.size() == 0) return;
    }

    assert keys.size() == 0;
  }
示例#12
0
  private void doTestEntrySetAfterExpiryInPut(Method m, CacheContainer cc) throws Exception {
    Cache<Integer, String> cache = cc.getCache();
    Set<Map.Entry<Integer, String>> entries;
    Map dataIn = new HashMap();
    dataIn.put(1, v(m, 1));
    dataIn.put(2, v(m, 2));
    Set entriesIn = dataIn.entrySet();

    final long startTime = System.currentTimeMillis();
    final long lifespan = EXPIRATION_TIMEOUT;
    cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);

    entries = Collections.emptySet();
    while (true) {
      entries = cache.entrySet();
      if (System.currentTimeMillis() >= startTime + lifespan) break;
      assertEquals(entriesIn, entries);
      Thread.sleep(100);
    }

    // Make sure that in the next 20 secs data is removed
    while (System.currentTimeMillis() < startTime + lifespan + EVICTION_CHECK_TIMEOUT) {
      entries = cache.entrySet();
      if (entries.size() == 0) return;
    }

    assert entries.size() == 0;
  }
 @BeforeMethod
 public void setUp() {
   cm = TestCacheManagerFactory.createCacheManager(false);
   cache = cm.getCache();
   listener = new CacheListener();
   cache.addListener(listener);
 }
  @Test
  public void testReadRandomSampleFile() throws IOException {
    final int BUFFER_SIZE = 64;

    Cache cache = cacheManager.getCache();
    InfinispanDirectory dir = new InfinispanDirectory(cache, cache, cache, INDEXNAME, BUFFER_SIZE);

    final int FILE_SIZE = 1000;
    assert BUFFER_SIZE < FILE_SIZE;
    createFileWithRepeatableContent(dir, "RandomSampleFile.txt", FILE_SIZE);

    IndexInput indexInput = dir.openInput("RandomSampleFile.txt");
    assert indexInput.length() == FILE_SIZE;
    RepeatableLongByteSequence bytesGenerator = new RepeatableLongByteSequence();

    Random r = new Random();
    long seekPoint = 0;
    // Now it reads some random byte and it compares to the expected byte
    for (int i = 0; i < FILE_SIZE; i++) {
      if (seekPoint == i) {
        byte expectedByte = bytesGenerator.nextByte();
        byte actualByte = indexInput.readByte();
        assert expectedByte == actualByte;
        seekPoint = indexInput.getFilePointer() + r.nextInt(10);
        indexInput.seek(seekPoint);
      } else {
        bytesGenerator.nextByte();
      }
    }
    indexInput.close();
    dir.close();
    DirectoryIntegrityCheck.verifyDirectoryStructure(cache, INDEXNAME);
  }
示例#15
0
  public void testValuesAfterExpiryInPut(Method m) throws Exception {
    Cache<Integer, String> cache = cm.getCache();
    // Values come as a Collection, but comparison of HashMap#Values is done
    // by reference equality, so wrap the collection around to set to make
    // testing easier, given that we know that there are dup values.
    Set<String> values;
    Map dataIn = new HashMap();
    dataIn.put(1, v(m, 1));
    dataIn.put(2, v(m, 2));
    Set valuesIn = new HashSet(dataIn.values());

    final long startTime = System.currentTimeMillis();
    final long lifespan = EXPIRATION_TIMEOUT;
    cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);

    values = Collections.emptySet();
    while (true) {
      values = new HashSet(cache.values());
      if (System.currentTimeMillis() >= startTime + lifespan) break;
      assertEquals(valuesIn, values);
      Thread.sleep(100);
    }

    // Make sure that in the next 20 secs data is removed
    while (System.currentTimeMillis() < startTime + lifespan + EVICTION_CHECK_TIMEOUT) {
      values = new HashSet(cache.values());
      if (values.size() == 0) return;
    }

    assert values.size() == 0;
  }
  @Test
  public void testRefreshAfterExternalChange() throws Exception {
    // First session factory uses a cache
    CacheContainer localManager = ClusterAwareRegionFactory.getCacheManager(DualNodeTest.LOCAL);
    localCache = localManager.getCache(Account.class.getName());
    SessionFactory localFactory = sessionFactory();

    // Second session factory doesn't; just needs a transaction manager
    SessionFactory remoteFactory = secondNodeEnvironment().getSessionFactory();

    AccountDAO dao0 = new AccountDAO(useJta, localFactory);
    AccountDAO dao1 = new AccountDAO(useJta, remoteFactory);

    Integer id = new Integer(1);
    dao0.createAccount(dao0.getSmith(), id, new Integer(5), DualNodeTest.LOCAL);

    // Basic sanity check
    Account acct1 = dao1.getAccount(id);
    assertNotNull(acct1);
    assertEquals(DualNodeTest.LOCAL, acct1.getBranch());

    // This dao's session factory isn't caching, so cache won't see this change
    dao1.updateAccountBranch(id, DualNodeTest.REMOTE);

    // dao1's session doesn't touch the cache,
    // so reading from dao0 should show a stale value from the cache
    // (we check to confirm the cache is used)
    Account acct0 = dao0.getAccount(id);
    assertNotNull(acct0);
    assertEquals(DualNodeTest.LOCAL, acct0.getBranch());
    log.debug("Contents when re-reading from local: " + TestingUtil.printCache(localCache));

    // Now call session.refresh and confirm we get the correct value
    acct0 = dao0.getAccountWithRefresh(id);
    assertNotNull(acct0);
    assertEquals(DualNodeTest.REMOTE, acct0.getBranch());
    log.debug("Contents after refreshing in remote: " + TestingUtil.printCache(localCache));

    // Double check with a brand new session, in case the other session
    // for some reason bypassed the 2nd level cache
    AccountDAO dao0A = new AccountDAO(useJta, localFactory);
    Account acct0A = dao0A.getAccount(id);
    assertNotNull(acct0A);
    assertEquals(DualNodeTest.REMOTE, acct0A.getBranch());
    log.debug("Contents after creating a new session: " + TestingUtil.printCache(localCache));
  }
  public void testJmxRegistrationAtStartupAndStop(Method m) throws Exception {
    final String otherJmxDomain = getMethodSpecificJmxDomain(m, JMX_DOMAIN);
    CacheContainer otherContainer =
        TestCacheManagerFactory.createCacheManagerEnforceJmxDomain(otherJmxDomain, true, false);
    ObjectName otherName = getCacheManagerObjectName(otherJmxDomain);
    try {
      assert server.getAttribute(otherName, "CreatedCacheCount").equals("0");
    } finally {
      otherContainer.stop();
    }

    try {
      server.getAttribute(otherName, "CreatedCacheCount").equals("0");
      assert false : "Failure expected, " + otherName + " shouldn't be registered in mbean server";
    } catch (InstanceNotFoundException e) {
    }
  }
 @Test
 public void testChunkBordersOnInfinispan() throws IOException {
   Cache cache = cacheManager.getCache();
   cache.clear();
   InfinispanDirectory dir = new InfinispanDirectory(cache, cache, cache, INDEXNAME, 13);
   testChunkBorders(dir, cache);
   cache.clear();
 }
 @Test
 public void testChunkBordersOnInfinispan() throws IOException {
   Cache cache = cacheManager.getCache();
   cache.clear();
   Directory dir =
       DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEXNAME)
           .chunkSize(13)
           .create();
   testChunkBorders(dir, cache);
   cache.clear();
 }
  public void testSharedLoader() throws Exception {
    CacheContainer cm1 = null, cm2 = null;
    try {
      sharedCacheLoader.set(true);
      cm1 = createCacheManager(tmpDirectory1);
      Cache c1 = cm1.getCache(cacheName);
      verifyNoDataOnLoader(c1);
      verifyNoData(c1);
      writeInitialData(c1);

      // starting the second cache would initialize an in-memory state transfer but not a persistent
      // one since the loader is shared
      cm2 = createCacheManager(tmpDirectory2);
      Cache c2 = cm2.getCache(cacheName);

      TestingUtil.blockUntilViewsReceived(60000, c1, c2);

      verifyInitialDataOnLoader(c1);
      verifyInitialData(c1);

      verifyNoDataOnLoader(c2);
      verifyNoData(c2);
    } finally {
      if (cm1 != null) cm1.stop();
      if (cm2 != null) cm2.stop();
      sharedCacheLoader.set(false);
    }
  }
示例#21
0
  public void testIdleExpiryInPutIfAbsent() throws InterruptedException {
    Cache<String, String> cache = cm.getCache();
    long idleTime = EXPIRATION_TIMEOUT;
    assert cache.putIfAbsent("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS) == null;
    assert cache.get("k").equals("v");

    Thread.sleep(idleTime + 100);

    assert cache.get("k") == null;

    cache.put("k", "v");
    assert cache.putIfAbsent("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS) != null;
  }
 public <K, V> Cache<K, V> getCityCache() {
   try {
     if (container != null) {
       Cache<K, V> cache = container.getCache("tspoinparamCache");
       return cache;
     } else {
       logger.error("container null");
     }
   } catch (Exception ex) {
     logger.error("Failed to get cache: " + ex.getLocalizedMessage());
     ex.printStackTrace();
   }
   return null;
 }
示例#23
0
  public void testIdleExpiryInPutAll() throws InterruptedException {
    Cache<String, String> cache = cm.getCache();
    final long idleTime = EXPIRATION_TIMEOUT;
    Map<String, String> m = new HashMap();
    m.put("k1", "v");
    m.put("k2", "v");
    cache.putAll(m, -1, MILLISECONDS, idleTime, MILLISECONDS);
    assert cache.get("k1").equals("v");
    assert cache.get("k2").equals("v");

    Thread.sleep(idleTime + 100);

    assert cache.get("k1") == null;
    assert cache.get("k2") == null;
  }
  public void testWriteChunks() throws Exception {
    final int BUFFER_SIZE = 64;

    Cache cache = cacheManager.getCache();
    Directory dir =
        DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEXNAME)
            .chunkSize(BUFFER_SIZE)
            .create();

    IndexOutput io = dir.createOutput("MyNewFile.txt");

    io.writeByte((byte) 66);
    io.writeByte((byte) 69);

    io.flush();
    io.close();

    assert dir.fileExists("MyNewFile.txt");
    assert null != cache.get(new ChunkCacheKey(INDEXNAME, "MyNewFile.txt", 0, BUFFER_SIZE));

    // test contents by reading:
    byte[] buf = new byte[9];
    IndexInput ii = dir.openInput("MyNewFile.txt");
    ii.readBytes(buf, 0, (int) ii.length());
    ii.close();

    assert new String(new byte[] {66, 69}).equals(new String(buf).trim());

    String testText =
        "This is some rubbish again that will span more than one chunk - one hopes.  Who knows, maybe even three or four chunks.";
    io = dir.createOutput("MyNewFile.txt");
    io.seek(0);
    io.writeBytes(testText.getBytes(), 0, testText.length());
    io.close();
    // now compare.
    byte[] chunk1 =
        (byte[]) cache.get(new ChunkCacheKey(INDEXNAME, "MyNewFile.txt", 0, BUFFER_SIZE));
    byte[] chunk2 =
        (byte[]) cache.get(new ChunkCacheKey(INDEXNAME, "MyNewFile.txt", 1, BUFFER_SIZE));
    assert null != chunk1;
    assert null != chunk2;

    assert testText.equals(new String(chunk1) + new String(chunk2).trim());

    dir.close();
    DirectoryIntegrityCheck.verifyDirectoryStructure(cache, INDEXNAME);
  }
示例#25
0
  public void testIdleExpiryInPut() throws InterruptedException {
    Cache<String, String> cache = cm.getCache();
    long idleTime = IDLE_TIMEOUT;
    cache.put("k", "v", -1, MILLISECONDS, idleTime, MILLISECONDS);

    DataContainer dc = cache.getAdvancedCache().getDataContainer();
    InternalCacheEntry se = dc.get("k", null);
    assert se.getKey().equals("k");
    assert se.getValue().equals("v");
    assert se.getLifespan() == -1;
    assert se.getMaxIdle() == idleTime;
    assert !se.isExpired();
    assert cache.get("k").equals("v");
    Thread.sleep(idleTime + 100);
    assert se.isExpired();
    assert cache.get("k") == null;
  }
 private void recreateCacheManager() {
   ConfigurationBuilder cfg = new ConfigurationBuilder();
   cfg.loaders()
       .preload(true)
       .passivation(true)
       .addStore()
       .cacheStore(new DummyInMemoryCacheStore())
       .purgeOnStartup(true)
       .indexing()
       .enable()
       .addProperty("default.directory_provider", "ram")
       .addProperty("lucene_version", "LUCENE_CURRENT");
   cm = TestCacheManagerFactory.createCacheManager(cfg);
   cache = cm.getCache();
   store = TestingUtil.extractComponent(cache, CacheLoaderManager.class).getCacheStore();
   search = Search.getSearchManager(cache);
 }
示例#27
0
  private void setupCacheStructures() {
    InfinispanCacheListener dialogsCacheListener = new InfinispanCacheListener(stack);

    dialogs = cm.getCache("cache.dialogs");
    appDataMap = cm.getCache("cache.appdata");
    serverTransactions = cm.getCache("cache.serverTX");
    serverTransactionsApp = cm.getCache("cache.serverTXApp");
    clientTransactions = cm.getCache("cache.clientTX");
    clientTransactionsApp = cm.getCache("cache.clientTXApp");

    dialogs.addListener(dialogsCacheListener);
  }
示例#28
0
  private void doValuesAfterExpiryInTransaction(Method m, CacheContainer cc) throws Exception {
    Cache<Integer, String> cache = cc.getCache();
    // Values come as a Collection, but comparison of HashMap#Values is done
    // by reference equality, so wrap the collection around to set to make
    // testing easier, given that we know that there are dup values.
    Set<String> values;
    Map dataIn = new HashMap();
    dataIn.put(1, v(m, 1));
    dataIn.put(2, v(m, 2));

    final long startTime = System.currentTimeMillis();
    final long lifespan = EXPIRATION_TIMEOUT;
    cache.putAll(dataIn, lifespan, TimeUnit.MILLISECONDS);

    cache.getAdvancedCache().getTransactionManager().begin();
    try {
      Map txDataIn = new HashMap();
      txDataIn.put(3, v(m, 3));
      Set allValuesIn = new HashSet(dataIn.values());
      allValuesIn.addAll(txDataIn.values());

      // Add an entry within tx
      cache.putAll(txDataIn);

      values = Collections.emptySet();
      while (true) {
        values = new HashSet(cache.values());
        if (System.currentTimeMillis() >= startTime + lifespan) break;
        assertEquals(allValuesIn, values);
        Thread.sleep(100);
      }

      // Make sure that in the next 20 secs data is removed
      while (System.currentTimeMillis() < startTime + lifespan + EVICTION_CHECK_TIMEOUT) {
        values = new HashSet(cache.values());
        if (values.size() == 1) return;
      }
    } finally {
      cache.getAdvancedCache().getTransactionManager().commit();
    }

    assert values.size() == 1;
  }
示例#29
0
  public void testLifespanExpiryInReplace() throws InterruptedException {
    Cache<String, String> cache = cm.getCache();
    final long lifespan = EXPIRATION_TIMEOUT;
    assert cache.get("k") == null;
    assert cache.replace("k", "v", lifespan, MILLISECONDS) == null;
    assert cache.get("k") == null;
    cache.put("k", "v-old");
    assert cache.get("k").equals("v-old");
    long startTime = System.currentTimeMillis();
    assert cache.replace("k", "v", lifespan, MILLISECONDS) != null;
    assert cache.get("k").equals("v");
    while (true) {
      String v = cache.get("k");
      if (System.currentTimeMillis() >= startTime + lifespan) break;
      assertEquals("v", v);
      Thread.sleep(100);
    }

    // make sure that in the next 2 secs data is removed
    while (System.currentTimeMillis() < startTime + lifespan + EVICTION_CHECK_TIMEOUT) {
      if (cache.get("k") == null) break;
      Thread.sleep(100);
    }
    assert cache.get("k") == null;

    startTime = System.currentTimeMillis();
    cache.put("k", "v");
    assert cache.replace("k", "v", "v2", lifespan, MILLISECONDS);
    while (true) {
      String v = cache.get("k");
      if (System.currentTimeMillis() >= startTime + lifespan) break;
      assertEquals("v2", v);
      Thread.sleep(100);
    }

    // make sure that in the next 2 secs data is removed
    while (System.currentTimeMillis() < startTime + lifespan + EVICTION_CHECK_TIMEOUT) {
      if (cache.get("k") == null) break;
      Thread.sleep(50);
    }
    assert cache.get("k") == null;
  }
  @Test
  public void testWriteChunksDefaultChunks() throws Exception {
    Cache cache = cacheManager.getCache();
    Directory dir = DirectoryBuilder.newDirectoryInstance(cache, cache, cache, INDEXNAME).create();

    final String testText = "This is some rubbish";
    final byte[] testTextAsBytes = testText.getBytes();

    IndexOutput io = dir.createOutput("MyNewFile.txt");

    io.writeByte((byte) 1);
    io.writeByte((byte) 2);
    io.writeByte((byte) 3);
    io.writeBytes(testTextAsBytes, testTextAsBytes.length);
    io.close();
    DirectoryIntegrityCheck.verifyDirectoryStructure(cache, INDEXNAME);

    FileCacheKey fileCacheKey = new FileCacheKey(INDEXNAME, "MyNewFile.txt");
    assert null != cache.get(fileCacheKey);
    FileMetadata metadata = (FileMetadata) cache.get(fileCacheKey);
    AssertJUnit.assertEquals(testTextAsBytes.length + 3, metadata.getSize());
    assert null
        != cache.get(
            new ChunkCacheKey(
                INDEXNAME, "MyNewFile.txt", 0, DirectoryBuilderImpl.DEFAULT_BUFFER_SIZE));

    // test contents by reading:
    IndexInput ii = dir.openInput("MyNewFile.txt");
    assert ii.readByte() == 1;
    assert ii.readByte() == 2;
    assert ii.readByte() == 3;
    byte[] buf = new byte[testTextAsBytes.length];

    ii.readBytes(buf, 0, testTextAsBytes.length);
    ii.close();

    assert testText.equals(new String(buf).trim());

    dir.close();
    DirectoryIntegrityCheck.verifyDirectoryStructure(cache, INDEXNAME);
  }