method2testcases
stringlengths 118
6.63k
|
---|
### Question:
CopyStrategyHandler { public Element copyElementForReadIfNeeded(Element element) { if (element == null) { return null; } if (copyOnRead && copyOnWrite) { return copyStrategy.copyForRead(element); } else if (copyOnRead) { return copyStrategy.copyForRead(copyStrategy.copyForWrite(element)); } else { return element; } } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy); Element copyElementForReadIfNeeded(Element element); }### Answer:
@Test public void given_no_copy_when_copyElementForReadIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(element), sameInstance(element)); }
@Test public void given_no_copy_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); }
@Test public void given_copy_on_read_when_copyElementForReadIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element)).thenReturn(serial); when(copyStrategy.copyForRead(serial)).thenReturn(new Element("key", "value")); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(element), allOf(not(sameInstance(element)), is(element))); verify(copyStrategy).copyForWrite(element); verify(copyStrategy).copyForRead(serial); }
@Test public void given_copy_on_read_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); }
@Test public void given_copy_on_write_when_copyElementForReadIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(element), sameInstance(element)); }
@Test public void given_copy_on_write_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); }
@Test public void given_copy_on_read_and_write_when_copyElementForReadIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForRead(serial)).thenReturn(new Element("key", "value")); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(serial), is(element)); verify(copyStrategy).copyForRead(serial); }
@Test public void given_copy_on_read_and_write_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); } |
### Question:
CopyStrategyHandler { Element copyElementForWriteIfNeeded(Element element) { if (element == null) { return null; } if (copyOnRead && copyOnWrite) { return copyStrategy.copyForWrite(element); } else if (copyOnWrite) { return copyStrategy.copyForRead(copyStrategy.copyForWrite(element)); } else { return element; } } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy); Element copyElementForReadIfNeeded(Element element); }### Answer:
@Test public void given_no_copy_when_copyElementForWriteIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), sameInstance(element)); }
@Test public void given_no_copy_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); }
@Test public void given_copy_on_read_when_copyElementForWriteIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), sameInstance(element)); }
@Test public void given_copy_on_read_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); }
@Test public void given_copy_on_write_when_copyElementForWriteIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element)).thenReturn(serial); when(copyStrategy.copyForRead(serial)).thenReturn(new Element("key", "value")); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), allOf(not(sameInstance(element)), equalTo(element))); verify(copyStrategy).copyForWrite(element); verify(copyStrategy).copyForRead(serial); }
@Test public void given_copy_on_write_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); }
@Test public void given_copy_on_read_and_write_when_copyElementForWriteIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element)).thenReturn(new Element("key", new byte[] { })); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), is(serial)); verify(copyStrategy).copyForWrite(element); }
@Test public void given_copy_on_read_and_write_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); } |
### Question:
CopyStrategyHandler { Element copyElementForRemovalIfNeeded(Element element) { if (element == null) { return null; } if (copyOnRead && copyOnWrite) { return copyStrategy.copyForWrite(element); } else { return element; } } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy); Element copyElementForReadIfNeeded(Element element); }### Answer:
@Test public void given_no_copy_when_copyElementForRemovalIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), sameInstance(element)); }
@Test public void given_no_copy_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); }
@Test public void given_copy_on_read_when_copyElementForRemovalIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), sameInstance(element)); }
@Test public void given_copy_on_read_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); }
@Test public void given_copy_on_write_when_copyElementForRemovalIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), sameInstance(element)); }
@Test public void given_copy_on_write_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); }
@Test public void given_copy_on_read_and_write_when_copyElementForRemovalIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element)).thenReturn(new Element("key", new byte[] { })); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), is(serial)); verify(copyStrategy).copyForWrite(element); }
@Test public void given_copy_on_read_and_write_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); } |
### Question:
Element implements Serializable, Cloneable { @Override public final boolean equals(final Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testEquals() { Element element = new Element("key", "value"); assertTrue(element.equals(element)); assertTrue(element.equals(new Element("key", "hat"))); assertFalse(element.equals("dog")); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); }
@Test public void testEqualsCharacterizationTestWithWhichWeDoNotAgree() { Element element = new Element(null, "value"); assertFalse(element.equals(new Element(null, "hat"))); assertFalse(element.equals(element)); }
@Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); } |
### Question:
Element implements Serializable, Cloneable { public final long getCreationTime() { return creationTime; } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testSetsCreationTimeAtConstruction() throws InterruptedException { final long initialValue = new Random().nextLong(); final AtomicLong now = new AtomicLong(initialValue); Element element = new Element("", "") { @Override long getCurrentTime() { return now.get(); } }; assertThat(element.getCreationTime(), is(initialValue)); } |
### Question:
Element implements Serializable, Cloneable { public final long getLatestOfCreationAndUpdateTime() { if (0 == lastUpdateTime) { return creationTime; } else { return lastUpdateTime; } } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testGetLatestOfCreationAndUpdateTimeReturnsCreationWhenNotUpdated() { final long initialValue = new Random().nextLong(); final AtomicLong now = new AtomicLong(initialValue); Element element = new Element("", "") { @Override long getCurrentTime() { return now.get(); } }; assertThat(element.getLatestOfCreationAndUpdateTime(), is(initialValue)); } |
### Question:
Element implements Serializable, Cloneable { public long getExpirationTime() { if (!isLifespanSet() || isEternal()) { return Long.MAX_VALUE; } long expirationTime = 0; long ttlExpiry = creationTime + TimeUtil.toMillis(getTimeToLive()); long mostRecentTime = Math.max(creationTime, lastAccessTime); long ttiExpiry = mostRecentTime + TimeUtil.toMillis(getTimeToIdle()); if (getTimeToLive() != 0 && (getTimeToIdle() == 0 || lastAccessTime == 0)) { expirationTime = ttlExpiry; } else if (getTimeToLive() == 0) { expirationTime = ttiExpiry; } else { expirationTime = Math.min(ttlExpiry, ttiExpiry); } return expirationTime; } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testExpirationTimeWhenNotSet() { final Element element = new Element("foo", "bar"); assertThat(element.getExpirationTime(), is(Long.MAX_VALUE)); } |
### Question:
Element implements Serializable, Cloneable { public boolean isEternal() { return (0 == timeToIdle) && (0 == timeToLive); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testDoesNotDefaultToEternal() { final Element element = new Element("key", "bar"); assertThat(element.isEternal(), is(false)); } |
### Question:
Element implements Serializable, Cloneable { boolean hasId() { return id != NOT_SET_ID; } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testIdNotSetByDefault() { Element e = new Element("foo", "bar"); assertThat(e.hasId(), is(false)); } |
### Question:
MValue implements ModelElement<T> { public T asJavaObject() { return javaObject; } MValue(Token tok, String typeName, Message errMessage, String value); T asJavaObject(); T asEhcacheObject(); @Override String toString(); String getTypeName(); String getValue(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testEnumValue() throws CustomParseException { MEnum<Foo> enumVal = new MValue.MEnum<Foo>(null, Foo.class.getName(), "Bar"); Enum<Foo> obj = enumVal.asJavaObject(); Assert.assertEquals(Foo.Bar, obj); try { new MValue.MEnum<Foo>(null, Foo.class.getName(), "Barr"); Assert.fail(); } catch (Exception e) { } } |
### Question:
Element implements Serializable, Cloneable { void setId(final long id) { if (id == NOT_SET_ID) { throw new IllegalArgumentException("Id cannot be set to " + id); } this.id = id; } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final int timeToIdleSeconds, final int timeToLiveSeconds); Element(final Object key, final Object value, final boolean eternal); @Deprecated Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testSetIdThrowsWhenSetToZero() { Element e = new Element("foo", "bar"); try { e.setId(0); fail(); } catch (IllegalArgumentException _) { } } |
### Question:
QueryManagerBuilder { public static QueryManagerBuilder newQueryManagerBuilder() { return new QueryManagerBuilder(); } private QueryManagerBuilder(); QueryManagerBuilder(Class<? extends QueryManager> implementationClass); static QueryManagerBuilder newQueryManagerBuilder(); QueryManagerBuilder addCache(Ehcache cache); QueryManagerBuilder addAllCachesCurrentlyIn(CacheManager cacheManager); QueryManager build(); }### Answer:
@Test public void testDefaultsToProperDefaultClass() { try { newQueryManagerBuilder(); } catch (CacheException e) { Assert.assertTrue(e.getCause().getClass() == ClassNotFoundException.class); } } |
### Question:
PayloadUtil { public static byte[] gzip(byte[] ungzipped) { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); gzipOutputStream.write(ungzipped); gzipOutputStream.close(); } catch (IOException e) { LOG.error("Could not gzip " + Arrays.toString(ungzipped)); } return bytes.toByteArray(); } private PayloadUtil(); static List<byte[]> createCompressedPayloadList(final List<CachePeer> localCachePeers, final int maximumPeersPerSend); static byte[] assembleUrlList(List localCachePeers); static byte[] gzip(byte[] ungzipped); static byte[] ungzip(final byte[] gzipped); static final int MTU; static final String URL_DELIMITER; }### Answer:
@Test public void testMaximumDatagram() throws IOException { String payload = createReferenceString(); final byte[] compressed = PayloadUtil.gzip(payload.getBytes()); int length = compressed.length; LOG.info("gzipped size: " + length); assertTrue("Heartbeat too big for one Datagram " + length, length <= 1500); } |
### Question:
PayloadUtil { public static List<byte[]> createCompressedPayloadList(final List<CachePeer> localCachePeers, final int maximumPeersPerSend) { List<byte[]> rv = new ArrayList<byte[]>(); int iters = (int) Math.ceil((double) localCachePeers.size() / maximumPeersPerSend); for (int i = 0; i < iters; i++) { int fromIndex = maximumPeersPerSend * i; int toIndex = Math.min(maximumPeersPerSend * (i + 1), localCachePeers.size()); List<CachePeer> subList = localCachePeers.subList(fromIndex, toIndex); rv.addAll(createCompressedPayload(subList, MTU)); } return rv; } private PayloadUtil(); static List<byte[]> createCompressedPayloadList(final List<CachePeer> localCachePeers, final int maximumPeersPerSend); static byte[] assembleUrlList(List localCachePeers); static byte[] gzip(byte[] ungzipped); static byte[] ungzip(final byte[] gzipped); static final int MTU; static final String URL_DELIMITER; }### Answer:
@Test public void testBigPayload() throws RemoteException { List<CachePeer> bigPayloadList = new ArrayList<CachePeer>(); int peers = 5000; int minCacheNameSize = 50; int maxCacheNameSize = 500; for (int i = 0; i < peers; i++) { bigPayloadList.add(new PayloadUtilTestCachePeer(getRandomName(minCacheNameSize, maxCacheNameSize))); } doTestBigPayLoad(bigPayloadList, 5); doTestBigPayLoad(bigPayloadList, 10); doTestBigPayLoad(bigPayloadList, 50); doTestBigPayLoad(bigPayloadList, 100); doTestBigPayLoad(bigPayloadList, 150); doTestBigPayLoad(bigPayloadList, 300); doTestBigPayLoad(bigPayloadList, 500); doTestBigPayLoad(bigPayloadList, 1000000); bigPayloadList.clear(); bigPayloadList.add(new PayloadUtilTestCachePeer(getRandomName(3000, 3001))); List<byte[]> compressedList = PayloadUtil.createCompressedPayloadList(bigPayloadList, 150); assertEquals(0, compressedList.size()); } |
### Question:
EventMessage implements Serializable { public final Serializable getSerializableKey() { return key; } EventMessage(Ehcache cache, Serializable key); final Ehcache getEhcache(); final Serializable getSerializableKey(); }### Answer:
@Test public void testSerialization() throws IOException, ClassNotFoundException { RmiEventMessage eventMessage = new RmiEventMessage(null, RmiEventType.PUT, "key", new Element("key", "element")); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bout); oos.writeObject(eventMessage); byte[] serializedValue = bout.toByteArray(); oos.close(); RmiEventMessage eventMessage2 = null; ByteArrayInputStream bin = new ByteArrayInputStream(serializedValue); ObjectInputStream ois = new ObjectInputStream(bin); eventMessage2 = (RmiEventMessage) ois.readObject(); ois.close(); assertEquals("key", eventMessage2.getSerializableKey()); assertEquals("element", eventMessage2.getElement().getObjectValue()); assertEquals(RmiEventType.PUT, eventMessage2.getType()); } |
### Question:
RegisteredEventListeners { public final boolean registerListener(CacheEventListener cacheEventListener) { return registerListener(cacheEventListener, NotificationScope.ALL); } RegisteredEventListeners(Cache cache); RegisteredEventListeners(Ehcache cache, CacheStoreHelper helper); final void notifyElementUpdatedOrdered(Element oldElement, Element newElement); final void notifyElementRemovedOrdered(Element element); final void notifyElementPutOrdered(Element element); final void notifyElementRemoved(Element element, boolean remoteEvent); final void notifyElementRemoved(ElementCreationCallback callback, boolean remoteEvent); final void notifyElementPut(Element element, boolean remoteEvent); final void notifyElementPut(ElementCreationCallback callback, boolean remoteEvent); final void notifyElementUpdated(Element element, boolean remoteEvent); final void notifyElementUpdated(ElementCreationCallback callback, boolean remoteEvent); final void notifyElementExpiry(Element element, boolean remoteEvent); final void notifyElementExpiry(ElementCreationCallback callback, boolean remoteEvent); final boolean hasCacheEventListeners(); final void notifyElementEvicted(Element element, boolean remoteEvent); final void notifyElementEvicted(ElementCreationCallback callback, boolean remoteEvent); final void notifyRemoveAll(boolean remoteEvent); final boolean registerListener(CacheEventListener cacheEventListener); final boolean registerListener(CacheEventListener cacheEventListener, NotificationScope scope); final boolean unregisterListener(CacheEventListener cacheEventListener); final boolean hasCacheReplicators(); final Set<CacheEventListener> getCacheEventListeners(); final void dispose(); @Override final String toString(); }### Answer:
@Test public void testNotifyTerracottaStoreOfListenerChangeOnRegister() throws Exception { TerracottaStore store = mock(TerracottaStore.class); RegisteredEventListeners registeredEventListeners = createRegisteredEventListeners(store); CacheEventListener listener = mock(CacheEventListener.class); registeredEventListeners.registerListener(listener); verify(store).notifyCacheEventListenersChanged(); } |
### Question:
MValue implements ModelElement<T> { public T asEhcacheObject(ClassLoader loader) { return javaObject; } MValue(Token tok, String typeName, Message errMessage, String value); T asEhcacheObject(ClassLoader loader); @Override String toString(); String getTypeName(); String getValue(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testEnumValue() throws CustomParseException { MEnum<Foo> enumVal = new MValue.MEnum<Foo>(null, Foo.class.getName(), "Bar"); Enum<Foo> obj = enumVal.asEhcacheObject(getClass().getClassLoader()); Assert.assertEquals(Foo.Bar, obj); try { MEnum<Foo> mEnum = new MValue.MEnum<Foo>(null, Foo.class.getName(), "Barr"); mEnum.asEhcacheObject(getClass().getClassLoader()); Assert.fail(); } catch (Exception e) { } }
@Test public void testNonEnumValue() throws CustomParseException { try { MEnum<Foo> mEnum = new MValue.MEnum<Foo>(null, Boolean.class.getName(), "TRUE"); mEnum.asEhcacheObject(getClass().getClassLoader()); Assert.fail(); } catch (Exception e) { } } |
### Question:
ClusteredInstanceFactoryAccessor { public static ClusteredInstanceFactory getClusteredInstanceFactory(CacheManager cacheManager) { try { Field field = CacheManager.class.getDeclaredField("terracottaClient"); field.setAccessible(true); TerracottaClient terracottaClient = (TerracottaClient)field.get(cacheManager); return terracottaClient.getClusteredInstanceFactory(); } catch (NoSuchFieldException nsfe) { throw new CacheException(nsfe); } catch (IllegalAccessException iae) { throw new CacheException(iae); } } static ClusteredInstanceFactory getClusteredInstanceFactory(CacheManager cacheManager); static void setTerracottaClient(CacheManager cacheManager, TerracottaClient terracottaClient); }### Answer:
@Test public void testAccessorDoesNotThrowException() throws Exception { CacheManager cm = new CacheManager(); try { ClusteredInstanceFactoryAccessor.getClusteredInstanceFactory(cm); } finally { cm.shutdown(); } } |
### Question:
DfltSamplerRepositoryService extends AbstractRemoteAgentEndpointImpl implements SamplerRepositoryService, EntityResourceFactory, CacheManagerService, CacheService, AgentService,
DfltSamplerRepositoryServiceMBean { @Override public Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> sampleNames) { CacheStatisticSampleEntityBuilder builder = CacheStatisticSampleEntityBuilder.createWith(sampleNames); cacheManagerSamplerRepoLock.readLock().lock(); List<SamplerRepoEntry> disabledSamplerRepoEntries = new ArrayList<SamplerRepoEntry>(); try { if (cacheManagerNames == null) { for (Map.Entry<String, SamplerRepoEntry> entry : cacheManagerSamplerRepo.entrySet()) { enableNonStopFor(entry.getValue(), false); disabledSamplerRepoEntries.add(entry.getValue()); for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) { builder.add(sampler, entry.getKey()); } } } else { for (String cmName : cacheManagerNames) { SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName); if (entry != null) { enableNonStopFor(entry, false); disabledSamplerRepoEntries.add(entry); for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) { builder.add(sampler, cmName); } } } } return builder.build(); } finally { for (SamplerRepoEntry samplerRepoEntry : disabledSamplerRepoEntries) { enableNonStopFor(samplerRepoEntry, true); } cacheManagerSamplerRepoLock.readLock().unlock(); } } DfltSamplerRepositoryService(String clientUUID, ManagementRESTServiceConfiguration configuration); @Override final synchronized void registerMBean(String clientUUID); @Override void dispose(); @Override byte[] invoke(RemoteCallDescriptor remoteCallDescriptor); @Override String getVersion(); @Override String getAgency(); @Override void register(CacheManager cacheManager); void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override Collection<CacheManagerEntity> createCacheManagerEntities(Set<String> cacheManagerNames,
Set<String> attributes); @Override Collection<CacheManagerConfigEntity> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override Collection<CacheEntity> createCacheEntities(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> attributes); @Override Collection<CacheConfigEntity> createCacheConfigEntities(Set<String> cacheManagerNames,
Set<String> cacheNames); @Override Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName,
String cacheName,
CacheEntity resource); @Override void clearCache(String cacheManagerName,
String cacheName); @Override void updateCacheManager(String cacheManagerName,
CacheManagerEntity resource); @Override Collection<QueryResultsEntity> executeQuery(String cacheManagerName, String queryString); @Override Collection<AgentEntity> getAgents(Set<String> ids); @Override Collection<AgentMetadataEntity> getAgentsMetadata(Set<String> ids); static final String MBEAN_NAME_PREFIX; static final String AGENCY; }### Answer:
@Test public void testCreateCacheStatisticSampleEntityDisablesNonStop() throws Exception { repositoryService.createCacheStatisticSampleEntity(Collections.singleton("testCacheManager"), Collections.singleton("testCache1"), Collections.singleton("Size")); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); }
@Test public void testCreateCacheStatisticSampleEntityDisablesNonStop() throws Exception { repositoryService.createCacheStatisticSampleEntity(singleton("testCacheManager"), singleton("testCache1"), singleton("Size")); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } |
### Question:
DfltSamplerRepositoryService extends AbstractRemoteAgentEndpointImpl implements SamplerRepositoryService, EntityResourceFactory, CacheManagerService, CacheService, AgentService,
DfltSamplerRepositoryServiceMBean { @Override public void clearCache(String cacheManagerName, String cacheName) { cacheManagerSamplerRepoLock.readLock().lock(); SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName); try { enableNonStopFor(entry, false); if (entry != null) entry.clearCache(cacheName); } finally { enableNonStopFor(entry, true); cacheManagerSamplerRepoLock.readLock().unlock(); } } DfltSamplerRepositoryService(String clientUUID, ManagementRESTServiceConfiguration configuration); @Override final synchronized void registerMBean(String clientUUID); @Override void dispose(); @Override byte[] invoke(RemoteCallDescriptor remoteCallDescriptor); @Override String getVersion(); @Override String getAgency(); @Override void register(CacheManager cacheManager); void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override Collection<CacheManagerEntity> createCacheManagerEntities(Set<String> cacheManagerNames,
Set<String> attributes); @Override Collection<CacheManagerConfigEntity> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override Collection<CacheEntity> createCacheEntities(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> attributes); @Override Collection<CacheConfigEntity> createCacheConfigEntities(Set<String> cacheManagerNames,
Set<String> cacheNames); @Override Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName,
String cacheName,
CacheEntity resource); @Override void clearCache(String cacheManagerName,
String cacheName); @Override void updateCacheManager(String cacheManagerName,
CacheManagerEntity resource); @Override Collection<QueryResultsEntity> executeQuery(String cacheManagerName, String queryString); @Override Collection<AgentEntity> getAgents(Set<String> ids); @Override Collection<AgentMetadataEntity> getAgentsMetadata(Set<String> ids); static final String MBEAN_NAME_PREFIX; static final String AGENCY; }### Answer:
@Test public void testClearCacheDisablesNonStop() throws Exception { repositoryService.clearCache("testCacheManager", "testCache1"); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } |
### Question:
ApplicationEhCache extends DefaultApplication { public Set<Class<?>> getClasses() { Set<Class<?>> s = new HashSet<Class<?>>(super.getClasses()); s.add(net.sf.ehcache.management.resource.services.ElementsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheStatisticSamplesResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CachesResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheManagersResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheManagerConfigsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheConfigsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.AgentsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.QueryResourceServiceImpl.class); return s; } Set<Class<?>> getClasses(); }### Answer:
@Test public void testGetClasses() throws Exception { List<String> classpathElements = getClasspathElements(); ApplicationEhCache applicationEhCache = new ApplicationEhCache(); Set<Class<?>> applicationClasses = applicationEhCache.getClasses(); Set<Class<?>> allClassesFound = new HashSet<Class<?>>(); for (String cpElement : classpathElements) { if (cpElement.endsWith(".jar")) { if (pathOfJarNotFiltered(cpElement)) { System.out.println("last scanned path : " + cpElement); allClassesFound.addAll(getAllClassesFromJar(cpElement)); } } else { System.out.println("last scanned path : " + cpElement); allClassesFound.addAll(getAllClassesFromDirectory(cpElement)); } } Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); for (Class<?> aClass : allClassesFound) { if (aClass.isAnnotationPresent(javax.ws.rs.ext.Provider.class) || aClass.isAnnotationPresent(javax.ws.rs.Path.class)) { annotatedClasses.add(aClass); } } Assert.assertThat(annotatedClasses, equalTo(applicationClasses)); } |
### Question:
ClusteredStore implements TerracottaStore, StoreListener { @Override public Element putIfAbsent(Element element) throws NullPointerException { if (isEventual && !EVENTUAL_CAS_ENABLED) { throw new UnsupportedOperationException("CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getObjectKey()); ElementData value = valueModeHandler.createElementData(element); Serializable data = backend.putIfAbsent(pKey, value); return data == null ? null : this.valueModeHandler.createElement(element.getKey(), data); } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void clusteredStore_putIfAbsent_throw_in_eventual_consistency() { clusteredStore.putIfAbsent(new Element("key", "value")); } |
### Question:
ClusteredStore implements TerracottaStore, StoreListener { @Override public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { if (isEventual) { return removeElementEventual(element, comparator); } String pKey = generatePortableKeyFor(element.getKey()); ToolkitReadWriteLock lock = backend.createLockForKey(pKey); lock.writeLock().lock(); try { Element oldElement = getQuiet(element.getKey()); if (comparator.equals(oldElement, element)) { return remove(element.getKey()); } } finally { lock.writeLock().unlock(); } return null; } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void clusteredStore_removeElement_throw_in_eventual_consistency() { clusteredStore.removeElement(new Element("key", "value"), new DefaultElementValueComparator(cacheConfiguration)); } |
### Question:
AsyncWriteBehind implements WriteBehind { @Override public void start(CacheWriter writer) throws CacheException { async.start(new CacheWriterProcessor(writer), concurrency, POLICY); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer:
@SuppressWarnings("unchecked") @Test public void testPassesConcurrencyToAsyncCoordinatorOnStart() { asyncWriteBehind.start(null); verify(asyncCoordinator).start(any(CacheWriterProcessor.class), eq(CONCURRENCY), any(ItemScatterPolicy.class)); }
@Test public void testPassesItemScatterPolicyToAsyncCoordinatorOnStart() { asyncWriteBehind.start(null); verify(asyncCoordinator).start(any(CacheWriterProcessor.class), eq(CONCURRENCY), same(AsyncWriteBehind.POLICY)); }
@Test public void testPassesWrappedWriterToAsyncCoordinatorOnStart() { final CacheWriter writer = mock(CacheWriter.class); asyncWriteBehind.start(writer); ArgumentCaptor<CacheWriterProcessor> captor = ArgumentCaptor.forClass(CacheWriterProcessor.class); verify(asyncCoordinator).start(captor.capture(), eq(CONCURRENCY), same(AsyncWriteBehind.POLICY)); assertThat(captor.getAllValues().size(), is(1)); assertThat(captor.getValue().getCacheWriter(), sameInstance(writer)); } |
### Question:
DfltSamplerRepositoryService implements ManagementServerLifecycle,
EntityResourceFactory, CacheManagerService, CacheService, AgentService { @Override public void clearCache(String cacheManagerName, String cacheName) { cacheManagerSamplerRepoLock.readLock().lock(); SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName); try { enableNonStopFor(entry, false); if (entry != null) { entry.clearCache(cacheName); } } finally { enableNonStopFor(entry, true); cacheManagerSamplerRepoLock.readLock().unlock(); } } DfltSamplerRepositoryService(ManagementRESTServiceConfiguration configuration,
RemoteAgentEndpointImpl remoteAgentEndpoint); @Override void dispose(); @Override void register(CacheManager cacheManager); @Override void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override Collection<CacheManagerEntity> createCacheManagerEntities(Set<String> cacheManagerNames,
Set<String> attributes); @Override Collection<CacheManagerConfigEntity> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override Collection<CacheEntity> createCacheEntities(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> attributes); @Override Collection<CacheConfigEntity> createCacheConfigEntities(Set<String> cacheManagerNames,
Set<String> cacheNames); @Override Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName,
String cacheName,
CacheEntity resource); @Override void clearCache(String cacheManagerName,
String cacheName); @Override void updateCacheManager(String cacheManagerName,
CacheManagerEntity resource); @Override Collection<QueryResultsEntity> executeQuery(String cacheManagerName, String queryString); @Override Collection<AgentEntity> getAgents(Set<String> ids); @Override Collection<AgentMetadataEntity> getAgentsMetadata(Set<String> ids); static final String AGENCY; }### Answer:
@Test public void testClearCacheDisablesNonStop() throws Exception { repositoryService.clearCache("testCacheManager", "testCache1"); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } |
### Question:
TerracottaBootstrapCacheLoader extends MemoryLimitedCacheLoader implements Disposable { public void load(final Ehcache cache) throws CacheException { if (!cache.getCacheConfiguration().isTerracottaClustered()) { LOG.error("You're trying to bootstrap a non Terracotta clustered cache with a TerracottaBootstrapCacheLoader! Cache " + "'{}' will not be bootstrapped and no keySet snapshot will be recorded...", cache.getName()); return; } if (cache.getStatus() != Status.STATUS_ALIVE) { throw new CacheException("Cache '" + cache.getName() + "' isn't alive yet: " + cache.getStatus()); } if (isAsynchronous()) { BootstrapThread thread = new BootstrapThread(cache); thread.start(); } else { doLoad(cache); } } private TerracottaBootstrapCacheLoader(final boolean doKeySnapshot, final boolean aSynchronous,
final String directory, final long interval, final boolean doKeySnapshotOnDedicatedThread); TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, boolean doKeySnapshots); TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, long interval); TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, long interval, boolean onDedicatedThread); boolean isImmediateShutdown(); void setImmediateShutdown(final boolean immediateShutdown); void load(final Ehcache cache); boolean isAsynchronous(); void dispose(); void doLocalKeySnapshot(); @Override Object clone(); void setSnapshotOnDispose(final boolean doKeySnapshotOnDispose); static final long DEFAULT_INTERVAL; static final boolean DEFAULT_DEDICATED_THREAD; }### Answer:
@Test public void testComplainsOnNonTcClusteredCacheButDoesNotFail() { cacheLoader.load(new Cache(new CacheConfiguration("test", 0))); }
@Test(expected = CacheException.class) public void testFailsWhenCacheIsNotAlive() { cacheLoader.load(new Cache(new CacheConfiguration("test", 0).terracotta(new TerracottaConfiguration()))); }
@Test public void testBootstrapsWhenNoSnapshotPresent() { final Ehcache cache = mockCacheToBootStrap(); cacheLoader.load(cache); verify(cache, never()).get(Matchers.anyObject()); }
@Test public void testBootstrapsWhenSnapshotPresent() throws IOException { RotatingSnapshotFile file = new RotatingSnapshotFile(DIRECTORY, MOCKED_CACHE_NAME); final List<Integer> localKeys = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9); file.writeAll(localKeys); final Ehcache cache = mockCacheToBootStrap(); cacheLoader.load(cache); verify(cache, times(new HashSet<Integer>(localKeys).size())).get(Matchers.anyObject()); for (Integer localKey : localKeys) { verify(cache, times(1)).get((Object) localKey); } file.currentSnapshotFile().delete(); } |
### Question:
BlockingCache extends EhcacheDecoratorAdapter { @Override public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); @Override Element get(final Object key); @Override void put(final Element element); @Override void put(final Element element, final boolean doNotNotifyCacheReplicators); @Override void putQuiet(final Element element); @Override void putWithWriter(final Element element); @Override Element putIfAbsent(final Element element); @Override Element putIfAbsent(final Element element, final boolean doNotNotifyCacheReplicators); @Override Element get(Serializable key); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); @Override void registerCacheLoader(CacheLoader cacheLoader); @Override void unregisterCacheLoader(CacheLoader cacheLoader); @Override Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); @Override Map getAllWithLoader(Collection keys, Object loaderArgument); @Override void load(Object key); @Override void loadAll(Collection keys, Object argument); }### Answer:
@Override @Test public void testGetWithLoader() { super.testGetWithLoader(); } |
### Question:
LruMemoryStore extends AbstractStore { public final boolean containsKey(Object key) { return map.containsKey(key); } LruMemoryStore(Ehcache cache, Store diskStore); synchronized void unpinAll(); synchronized boolean isPinned(Object key); synchronized void setPinned(Object key, boolean pinned); final boolean put(Element element); final boolean putWithWriter(Element element, CacheWriterManager writerManager); final synchronized Element get(Object key); final synchronized Element getQuiet(Object key); final Element remove(Object key); final Element removeWithWriter(Object key, CacheWriterManager writerManager); final synchronized void removeAll(); final synchronized void dispose(); final void flush(); final Status getStatus(); final synchronized List getKeys(); final int getSize(); final int getTerracottaClusteredSize(); final boolean containsKey(Object key); final synchronized long getSizeInBytes(); void expireElements(); boolean bufferFull(); Object getMBean(); Policy getEvictionPolicy(); void setEvictionPolicy(Policy policy); Object getInternalContext(); boolean containsKeyInMemory(Object key); boolean containsKeyOffHeap(Object key); boolean containsKeyOnDisk(Object key); Policy getInMemoryEvictionPolicy(); int getInMemorySize(); long getInMemorySizeInBytes(); int getOffHeapSize(); long getOffHeapSizeInBytes(); int getOnDiskSize(); long getOnDiskSizeInBytes(); void setInMemoryEvictionPolicy(Policy policy); Element putIfAbsent(Element element); Element removeElement(Element element, ElementValueComparator comparator); boolean replace(Element old, Element element, ElementValueComparator comparator); Element replace(Element element); }### Answer:
@Test public void testContainsKey() { final Object key = new Object(); assertThat(store.containsKey(key), is(false)); store.setPinned(key, true); assertThat(store.get(key), nullValue()); assertThat(store.containsKey(key), is(false)); } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); return singleton; } synchronized (CacheManager.class) { if (singleton == null) { singleton = newInstance(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); Ehcache ehcache = ehcaches.get(name); return ehcache instanceof Cache ? (Cache) ehcache : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); } |
### Question:
CacheManager { public synchronized void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.removeCache(null); singletonManager.removeCache(""); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public synchronized void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.addCache("test"); singletonManager.addCache("test2"); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public synchronized Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { singletonManager = CacheManager.create(); singletonManager.addCache("present"); assertTrue(singletonManager.getCache("present") == singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000)))); Cache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = singletonManager.addCacheIfAbsent(theCache); assertNotNull(cache); assertTrue(theCache == cache); assertEquals("absent", cache.getName()); Cache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(other); assertNotNull(actualCacheRegisteredWithManager); assertFalse(other == actualCacheRegisteredWithManager); assertTrue(cache == actualCacheRegisteredWithManager); Cache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); singletonManager.removeCache(actualCacheRegisteredWithManager.getName()); actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(newCache); assertNotNull(actualCacheRegisteredWithManager); assertFalse(cache == actualCacheRegisteredWithManager); assertTrue(newCache == actualCacheRegisteredWithManager); assertTrue(singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000))) == actualCacheRegisteredWithManager); assertNull(singletonManager.addCacheIfAbsent((Ehcache) null)); } |
### Question:
AsyncWriteBehind implements WriteBehind { @Override public void delete(CacheEntry entry) { async.add(new DeleteAsyncOperation(entry.getKey(), entry.getElement())); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer:
@Test public void testDelegatesDeleteToAsyncCoordinator() { final Element element = new Element("foo", "bar"); asyncWriteBehind.delete(new CacheEntry(element.getObjectKey(), element)); ArgumentCaptor<SingleAsyncOperation> captor = ArgumentCaptor.forClass(SingleAsyncOperation.class); verify(asyncCoordinator).add(captor.capture()); assertThat(captor.getAllValues().size(), is(1)); final SingleAsyncOperation value = captor.getValue(); assertThat(value, instanceOf(DeleteAsyncOperation.class)); assertThat(value.getKey(), sameInstance(element.getObjectKey())); assertThat(value.getElement(), sameInstance(element)); } |
### Question:
AsyncWriteBehind implements WriteBehind { @Override public void write(Element element) { async.add(new WriteAsyncOperation(element)); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer:
@Test public void testDelegatesWriteToAsyncCoordinator() { final Element element = new Element("foo", "bar"); asyncWriteBehind.write(element); ArgumentCaptor<SingleAsyncOperation> captor = ArgumentCaptor.forClass(SingleAsyncOperation.class); verify(asyncCoordinator).add(captor.capture()); assertThat(captor.getAllValues().size(), is(1)); final SingleAsyncOperation value = captor.getValue(); assertThat(value, instanceOf(WriteAsyncOperation.class)); assertThat(value.getElement(), sameInstance(element)); } |
### Question:
CacheWriterConfiguration implements Cloneable { public CacheWriterConfiguration writeMode(String writeMode) { setWriteMode(writeMode); return this; } @Override CacheWriterConfiguration clone(); void setWriteMode(String writeMode); CacheWriterConfiguration writeMode(String writeMode); CacheWriterConfiguration writeMode(WriteMode writeMode); WriteMode getWriteMode(); void setNotifyListenersOnException(boolean notifyListenersOnException); CacheWriterConfiguration notifyListenersOnException(boolean notifyListenersOnException); boolean getNotifyListenersOnException(); void setMinWriteDelay(int minWriteDelay); CacheWriterConfiguration minWriteDelay(int minWriteDelay); int getMinWriteDelay(); void setMaxWriteDelay(int maxWriteDelay); CacheWriterConfiguration maxWriteDelay(int maxWriteDelay); int getMaxWriteDelay(); void setRateLimitPerSecond(int rateLimitPerSecond); CacheWriterConfiguration rateLimitPerSecond(int rateLimitPerSecond); int getRateLimitPerSecond(); void setWriteCoalescing(boolean writeCoalescing); CacheWriterConfiguration writeCoalescing(boolean writeCoalescing); boolean getWriteCoalescing(); void setWriteBatching(boolean writeBatching); CacheWriterConfiguration writeBatching(boolean writeBatching); boolean getWriteBatching(); void setWriteBatchSize(int writeBatchSize); CacheWriterConfiguration writeBatchSize(int writeBatchSize); int getWriteBatchSize(); void setRetryAttempts(int retryAttempts); CacheWriterConfiguration retryAttempts(int retryAttempts); int getRetryAttempts(); void setRetryAttemptDelaySeconds(int retryAttemptDelaySeconds); CacheWriterConfiguration retryAttemptDelaySeconds(int retryAttemptDelaySeconds); int getRetryAttemptDelaySeconds(); final void addCacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactoryConfiguration); CacheWriterConfiguration cacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactory); CacheWriterFactoryConfiguration getCacheWriterFactoryConfiguration(); @Override int hashCode(); @Override boolean equals(Object obj); static final WriteMode DEFAULT_WRITE_MODE; static final boolean DEFAULT_NOTIFY_LISTENERS_ON_EXCEPTION; static final int DEFAULT_MIN_WRITE_DELAY; static final int DEFAULT_MAX_WRITE_DELAY; static final int DEFAULT_RATE_LIMIT_PER_SECOND; static final boolean DEFAULT_WRITE_COALESCING; static final boolean DEFAULT_WRITE_BATCHING; static final int DEFAULT_WRITE_BATCH_SIZE; static final int DEFAULT_RETRY_ATTEMPTS; static final int DEFAULT_RETRY_ATTEMPT_DELAY_SECONDS; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testNullWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode((CacheWriterConfiguration.WriteMode) null); }
@Test(expected = IllegalArgumentException.class) public void testInvalidWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode("invalid"); } |
### Question:
ConfigurationFactory { static Set extractPropertyTokens(String sourceDocument) { Set propertyTokens = new HashSet(); Pattern pattern = Pattern.compile("\\$\\{.+?\\}"); Matcher matcher = pattern.matcher(sourceDocument); while (matcher.find()) { String token = matcher.group(); propertyTokens.add(token); } return propertyTokens; } private ConfigurationFactory(); static Configuration parseConfiguration(final File file); static Configuration parseConfiguration(final URL url); static Configuration parseConfiguration(); static Configuration parseConfiguration(final InputStream inputStream); }### Answer:
@Test public void testMatchPropertyTokensProperlyFormedUrl() { String example="<terracottaConfig url=\"${serverAndPort}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${serverAndPort}", firstPropertyToken); }
@Test public void testMatchPropertyTokensProperlyFormed() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress}, " + "multicastGroupPort=4446, timeToLive=1\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${multicastAddress}", firstPropertyToken); }
@Test public void testMatchPropertyTokensProperlyFormedUrl() { String example = "<terracottaConfig url=\"${serverAndPort}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${serverAndPort}", firstPropertyToken); }
@Test public void testMatchPropertyTokensProperlyFormedTwo() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress}\n, " + "multicastGroupPort=4446, timeToLive=${multicastAddress}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${multicastAddress}", firstPropertyToken); }
@Test public void testMatchPropertyTokensProperlyFormedTwoUnique() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress}\n, " + "multicastGroupPort=4446, timeToLive=${multicastAddress1}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(2, propertyTokens.size()); }
@Test public void testMatchPropertyTokensNotClosed() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress\n, " + "multicastGroupPort=4446, timeToLive=${multicastAddress\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(0, propertyTokens.size()); } |
### Question:
SelfPopulatingCache extends BlockingCache { protected void refreshElement(final Element element, Ehcache backingCache) throws Exception { refreshElement(element, backingCache, true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer:
@Test public void testRefreshElement() throws Exception { final IncrementingCacheEntryFactory factory = new IncrementingCacheEntryFactory(); selfPopulatingCache = new SelfPopulatingCache(cache, factory); Element e1 = selfPopulatingCache.get("key1"); Element e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(2, factory.getCount()); assertEquals(Integer.valueOf(1), e1.getValue()); assertEquals(Integer.valueOf(2), e2.getValue()); selfPopulatingCache.refresh(); e1 = selfPopulatingCache.get("key1"); e2 = selfPopulatingCache.get("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(4, factory.getCount()); int e1i = ((Integer) e1.getValue()).intValue(); int e2i = ((Integer) e2.getValue()).intValue(); assertTrue(((e1i == 3) && (e2i == 4)) || ((e1i == 4) && (e2i == 3))); selfPopulatingCache.get("key2"); Element e2r = selfPopulatingCache.refresh("key2"); assertEquals(2, selfPopulatingCache.getSize()); assertEquals(5, factory.getCount()); assertNotNull(e2r); assertEquals("key2", e2r.getKey()); assertEquals(Integer.valueOf(5), e2r.getValue()); Element e3 = selfPopulatingCache.get("key3"); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(6, factory.getCount()); assertNotNull(e3); assertEquals("key3", e3.getKey()); assertEquals(Integer.valueOf(6), e3.getValue()); selfPopulatingCache.refresh(); assertEquals(3, selfPopulatingCache.getSize()); assertEquals(9, factory.getCount()); } |
### Question:
XATransactionalStore extends AbstractStore { public Element removeElement(Element element) throws NullPointerException { TransactionContext context = getOrCreateTransactionContext(); Element previous = getCurrentElement(element.getKey(), context); if (previous != null && previous.getValue().equals(element.getValue())) { context.addCommand(new StoreRemoveElementCommand(element), element); return previous; } return null; } XATransactionalStore(Ehcache cache, EhcacheXAStore ehcacheXAStore,
TransactionManagerLookup transactionManagerLookup, TransactionManager txnManager); boolean put(final Element element); boolean putWithWriter(final Element element, final CacheWriterManager writerManager); Element get(final Object key); Element getQuiet(final Object key); final List getKeys(); Element remove(final Object key); Element removeWithWriter(final Object key, final CacheWriterManager writerManager); void removeAll(); void dispose(); int getSize(); int getOnDiskSize(); int getOffHeapSize(); int getInMemorySize(); int getTerracottaClusteredSize(); long getInMemorySizeInBytes(); long getOffHeapSizeInBytes(); long getOnDiskSizeInBytes(); Status getStatus(); boolean containsKey(final Object key); boolean containsKeyInMemory(final Object key); boolean containsKeyOffHeap(final Object key); boolean containsKeyOnDisk(final Object key); void expireElements(); void flush(); boolean bufferFull(); Policy getInMemoryEvictionPolicy(); void setInMemoryEvictionPolicy(final Policy policy); Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); Element putIfAbsent(Element element); Element removeElement(Element element); boolean replace(Element old, Element element); Element replace(Element element); EhcacheXAResource getOrCreateXAResource(); Object getMBean(); }### Answer:
@Test public void testRemoveElement() throws Exception { transactionManager.begin(); assertEquals("Cache should be empty to start", 0, cache.getSize()); assertEquals("Cach1 should be empty to start", 0, cach1.getSize()); assertFalse(cache.removeElement(new Element("blah", "someValue"))); cache.put(new Element("blah", "value")); assertFalse(cache.removeElement(new Element("blah", "someValue"))); transactionManager.commit(); transactionManager.begin(); assertNotNull(cache.get("blah")); assertTrue(cache.removeElement(new Element("blah", "value"))); transactionManager.commit(); transactionManager.begin(); assertNull(cache.get("blah")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); Transaction tx1 = transactionManager.suspend(); transactionManager.begin(); assertTrue(cache.removeElement(new Element("key", "value"))); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element is deleted already"); } catch (RollbackException e) { } transactionManager.begin(); assertNull(cache.get("key")); transactionManager.commit(); transactionManager.begin(); cache.put(new Element("key", "value")); transactionManager.commit(); transactionManager.begin(); cach1.put(new Element("random", "things")); cache.removeElement(new Element("key", "value")); tx1 = transactionManager.suspend(); transactionManager.begin(); cache.put(new Element("key", "newValue")); transactionManager.commit(); transactionManager.resume(tx1); try { transactionManager.commit(); fail("Transaction should have failed, element has changed in the meantime!"); } catch (RollbackException e) { } transactionManager.begin(); assertNotNull(cache.get("key")); assertEquals("newValue", cache.get("key").getValue()); transactionManager.commit(); } |
### Question:
CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } if (terracottaClusteredInstanceFactory != null) { terracottaClusteredInstanceFactory.shutdown(); } removeShutdownHook(); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); }
@Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); } |
### Question:
CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); configuration.getCacheConfigurations().remove(cacheName); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.removeCache(null); singletonManager.removeCache(""); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { singletonManager = CacheManager.create(); singletonManager.addCache("present"); assertTrue(singletonManager.getCache("present") == singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000)))); Cache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = singletonManager.addCacheIfAbsent(theCache); assertNotNull(cache); assertTrue(theCache == cache); assertEquals("absent", cache.getName()); Cache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(other); assertNotNull(actualCacheRegisteredWithManager); assertFalse(other == actualCacheRegisteredWithManager); assertTrue(cache == actualCacheRegisteredWithManager); Cache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); singletonManager.removeCache(actualCacheRegisteredWithManager.getName()); actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(newCache); assertNotNull(actualCacheRegisteredWithManager); assertFalse(cache == actualCacheRegisteredWithManager); assertTrue(newCache == actualCacheRegisteredWithManager); assertTrue(singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000))) == actualCacheRegisteredWithManager); assertNull(singletonManager.addCacheIfAbsent((Ehcache) null)); } |
### Question:
AsyncWriteBehind implements WriteBehind { @Override public void stop() throws CacheException { async.stop(); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer:
@Test public void testDelegatesStopToAsyncCoordinator() { asyncWriteBehind.stop(); verify(asyncCoordinator).stop(); } |
### Question:
AsyncWriteBehind implements WriteBehind { @Override public long getQueueSize() { return async.getQueueSize(); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer:
@Test public void testDelegatesGetQueueSizeToAsyncCoordinator() { asyncWriteBehind.getQueueSize(); verify(asyncCoordinator).getQueueSize(); } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); return singleton; } synchronized (CacheManager.class) { if (singleton == null) { singleton = newInstance(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); Ehcache ehcache = ehcaches.get(name); return ehcache instanceof Cache ? (Cache) ehcache : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); } |
### Question:
CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.removeCache(null); singletonManager.removeCache(""); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.addCache("test"); singletonManager.addCache("test2"); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { singletonManager = CacheManager.create(); singletonManager.addCache("present"); assertTrue(singletonManager.getCache("present") == singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000)))); Cache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = singletonManager.addCacheIfAbsent(theCache); assertNotNull(cache); assertTrue(theCache == cache); assertEquals("absent", cache.getName()); Cache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(other); assertNotNull(actualCacheRegisteredWithManager); assertFalse(other == actualCacheRegisteredWithManager); assertTrue(cache == actualCacheRegisteredWithManager); Cache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); singletonManager.removeCache(actualCacheRegisteredWithManager.getName()); actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(newCache); assertNotNull(actualCacheRegisteredWithManager); assertFalse(cache == actualCacheRegisteredWithManager); assertTrue(newCache == actualCacheRegisteredWithManager); assertTrue(singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000))) == actualCacheRegisteredWithManager); assertNull(singletonManager.addCacheIfAbsent((Ehcache) null)); } |
### Question:
ResourceClassLoader extends ClassLoader { @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class c = findLoadedClass(name); if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; } ResourceClassLoader(String prefix, ClassLoader parent); @Override synchronized Class<?> loadClass(String name, boolean resolve); @Override URL getResource(String name); @Override /** * very similar to what OracleJDK classloader does, * except the first resources (more important) are the ones found with our ResourceClassLoader */ Enumeration<URL> getResources(String resourceName); }### Answer:
@Test(expected = ClassNotFoundException.class) public void contentOfTheJarNotVisibleWithNormalClassLoaderTest() throws ClassNotFoundException { Class<?> simpleClass = testCaseClassLoader.loadClass("pof.Simple"); }
@Test public void workingWithClassFromPrivateClassPathTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { ResourceClassLoader resourceClassLoader = new ResourceClassLoader("private-classpath", testCaseClassLoader); Class<?> simpleClass = resourceClassLoader.loadClass("pof.Simple"); Constructor<?> simpleClassConstructor = simpleClass.getConstructor(new Class[] {}); Object simpleObject = simpleClassConstructor.newInstance(new Object[] {}); Method sayHelloMethod = simpleClass.getMethod("sayHello", new Class[] {}); Object sayHello = sayHelloMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("hello!", sayHello); Method printVersionMethod = simpleClass.getMethod("printVersion", new Class[] {}); Object printVersion = printVersionMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("2.6.0-SNAPSHOT", printVersion); Method getMessageInTextFileMethod = simpleClass.getMethod("getMessageInTextFile", new Class[] {}); Object message = getMessageInTextFileMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("Congratulations ! You could read a file from a hidden resource location !", message); } |
### Question:
UpdateChecker extends TimerTask { public void checkForUpdate() { try { if (!Boolean.getBoolean("net.sf.ehcache.skipUpdateCheck")) { doCheck(); } } catch (Throwable t) { LOG.debug("Update check failed: ", t); } } @Override void run(); void checkForUpdate(); }### Answer:
@Test public void testErrorNotBubleUp() { System.setProperty("net.sf.ehcache.skipUpdateCheck", "false"); System.setProperty("ehcache.update-check.url", "this is a bad url"); UpdateChecker uc = new UpdateChecker(); uc.checkForUpdate(); } |
### Question:
AsyncWriteBehind implements WriteBehind { @Override public void setOperationsFilter(OperationsFilter filter) { OperationsFilterWrapper filterWrapper = new OperationsFilterWrapper(filter); async.setOperationsFilter(filterWrapper); } AsyncWriteBehind(final AsyncCoordinator async, final int writeBehindConcurrency); @Override void start(CacheWriter writer); @Override void write(Element element); @Override void delete(CacheEntry entry); @Override void setOperationsFilter(OperationsFilter filter); @Override void stop(); @Override long getQueueSize(); static final ItemScatterPolicy<SingleAsyncOperation> POLICY; }### Answer:
@Test public void testDelegatesSetOperationsFilterToAsyncCoordinator() { final CoalesceKeysFilter filter = new CoalesceKeysFilter(); asyncWriteBehind.setOperationsFilter(filter); ArgumentCaptor<OperationsFilterWrapper> captor = ArgumentCaptor.forClass(OperationsFilterWrapper.class); verify(asyncCoordinator).setOperationsFilter(captor.capture()); assertThat(captor.getAllValues().size(), is(1)); assertThat(captor.getValue().getDelegate(), CoreMatchers.<OperationsFilter<KeyBasedOperation>>sameInstance(filter)); } |
### Question:
SelectableConcurrentHashMap { public Element get(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).get(key, hash); } SelectableConcurrentHashMap(PoolAccessor poolAccessor, boolean elementPinningEnabled, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService); SelectableConcurrentHashMap(PoolAccessor poolAccessor, boolean elementPinningEnabled, int initialCapacity, float loadFactor, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService); void setMaxSize(final long maxSize); Element[] getRandomValues(final int size, Object keyHint); Object storedObject(Element e); int quickSize(); boolean isEmpty(); int size(); int pinnedSize(); ReentrantReadWriteLock lockFor(Object key); ReentrantReadWriteLock[] locks(); Element get(Object key); boolean containsKey(Object key); boolean containsValue(Object value); Element put(Object key, Element element, long sizeOf); Element putIfAbsent(Object key, Element element, long sizeOf); Element remove(Object key); boolean remove(Object key, Object value); void clear(); void unpinAll(); void setPinned(Object key, boolean pinned); boolean isPinned(Object key); Set<Object> keySet(); Collection<Element> values(); Set<Entry<Object, Element>> entrySet(); boolean evict(); void recalculateSize(Object key); Set pinnedKeySet(); }### Answer:
@Test public void testReturnsPinnedKeysThatArePresent() { assertThat(map.get(1), notNullValue()); assertThat(map.get(2), notNullValue()); assertThat(map.get(3), notNullValue()); assertThat(map.get(4), notNullValue()); }
@Test public void testDoesNotReturnsPinnedKeysThatAreNotPresent() { assertThat(map.get(0), nullValue()); assertThat(map.get(5), nullValue()); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { Configuration config = new Configuration().cache(new CacheConfiguration("foo", 100)); CacheManager manager = new CacheManager(config); try { assertEquals(1, manager.getConfiguration().getCacheConfigurations().size()); assertNotNull(manager.getCache("foo")); manager.removeCache("foo"); assertNull(manager.getCache("foo")); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxEntriesLocalHeap(0)); CacheManager manager = new CacheManager(config); try { assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.addCache("test"); manager.addCache("test2"); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = manager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = manager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); manager.addCache(""); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxEntriesLocalHeap(100)); CacheManager manager = new CacheManager(config); try { manager.addCache("present"); assertThat(manager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000))), sameInstance(manager.getEhcache("present"))); Ehcache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = manager.addCacheIfAbsent(theCache); assertNotNull(cache); assertThat(cache, sameInstance(theCache)); assertThat(cache.getName(), is("absent")); Ehcache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actual = manager.addCacheIfAbsent(other); assertThat(actual, notNullValue()); assertThat(actual, not(sameInstance(other))); assertThat(actual, sameInstance(cache)); Ehcache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); manager.removeCache(actual.getName()); actual = manager.addCacheIfAbsent(newCache); assertThat(actual, notNullValue()); assertThat(actual, not(sameInstance(cache))); assertThat(actual, sameInstance(newCache)); assertThat(manager.addCacheIfAbsent(new Cache(new CacheConfiguration(actual.getName(), 1000))), sameInstance(actual)); assertThat(manager.addCacheIfAbsent((Ehcache) null), nullValue()); } finally { manager.shutdown(); } } |
### Question:
Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null) && elementEvictionData.canParticipateInSerialization(); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); } |
### Question:
Element implements Serializable, Cloneable { @Override public final boolean equals(final Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version,
final long creationTime, final long lastAccessTime,
final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime,
final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value,
final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); ElementEvictionData getElementEvictionData(); void setElementEvictionData(ElementEvictionData elementEvictionData); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer:
@Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); } |
### Question:
Watchdog { public void watch(final Watchable watchable) { registry.add(watchable); LOGGER.debug("Watchable cache '{}' registered", watchable.name()); } private Watchdog(final ScheduledExecutorService scheduler); static Watchdog create(); void watch(final Watchable watchable); void unwatch(final Watchable watchable); void init(); }### Answer:
@Test public void testMustProbeAllRegisteredWatchables() { watchdog.watch(cache1); watchdog.watch(cache2); scheduler.trigger(); verify(cache1).probeLiveness(); verify(cache2).probeLiveness(); } |
### Question:
ScheduledRefreshCacheExtension implements CacheExtension { static Collection<ScheduledRefreshCacheExtension> findExtensionsFromCache(Ehcache cache) { LinkedList<ScheduledRefreshCacheExtension> exts=new LinkedList<ScheduledRefreshCacheExtension>(); for (CacheExtension ce : cache.getRegisteredCacheExtensions()) { if (ce instanceof ScheduledRefreshCacheExtension) { exts.add((ScheduledRefreshCacheExtension)ce); } } return exts; } ScheduledRefreshCacheExtension(ScheduledRefreshConfiguration config, Ehcache cache); @Override void init(); @Override void dispose(); @Override CacheExtension clone(Ehcache cache); @Override Status getStatus(); @org.terracotta.statistics.Statistic(name = "refresh", tags = "scheduledrefresh") long getRefreshCount(); @org.terracotta.statistics.Statistic(name = "job", tags = "scheduledrefresh") long getJobCount(); @org.terracotta.statistics.Statistic(name = "keysprocessed", tags = "scheduledrefresh") long getKeysProcessedCount(); static Set<ExtendedStatistics.Statistic<Number>> findRefreshStatistics(Ehcache cache); static Set<ExtendedStatistics.Statistic<Number>> findJobStatistics(Ehcache cache); static Set<ExtendedStatistics.Statistic<Number>> findKeysProcessedStatistics(Ehcache cache); static ExtendedStatistics.Statistic<Number> findRefreshStatistic(Ehcache cache); static ExtendedStatistics.Statistic<Number> findJobStatistic(Ehcache cache); static ExtendedStatistics.Statistic<Number> findKeysProcessedStatistic(Ehcache cache); }### Answer:
@Test public void testSimpleCaseXML() throws InterruptedException { CacheManager manager = new CacheManager(getClass().getResourceAsStream("/ehcache-scheduled-refresh.xml")); try { Cache cache = manager.getCache("sr-test"); for (int i = 0; i < 10; i++) { cache.put(new Element(i, i + "")); } waitOnExtensionState(ScheduledRefreshCacheExtension.findExtensionsFromCache(cache).iterator().next(), TIMED_WAIT_IN_SECS,2); for (Object key : cache.getKeys()) { Element val = cache.get(key); int iVal = ((Number) key).intValue(); if ((iVal & 0x01) == 0) { Assert.assertEquals(iVal + 20000, Long.parseLong((String) val.getObjectValue())); } else { Assert.assertEquals(iVal + 10000, Long.parseLong((String) val.getObjectValue())); } } } finally { manager.shutdown(); } } |
### Question:
CacheManager { public static CacheManager create() throws CacheException { return create(ConfigurationFactory.parseConfiguration(), "Creating new CacheManager with default config"); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return ehcaches.get(name) instanceof Cache ? (Cache) ehcaches.get(name) : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); } |
### Question:
CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.removeCache(null); singletonManager.removeCache(""); assertEquals(14, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.addCache("test"); singletonManager.addCache("test2"); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); } |
### Question:
CacheManager { public Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); SoftLockFactory getSoftLockFactory(String cacheName); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { singletonManager = CacheManager.create(); singletonManager.addCache("present"); assertTrue(singletonManager.getCache("present") == singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000)))); Cache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = singletonManager.addCacheIfAbsent(theCache); assertNotNull(cache); assertTrue(theCache == cache); assertEquals("absent", cache.getName()); Cache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(other); assertNotNull(actualCacheRegisteredWithManager); assertFalse(other == actualCacheRegisteredWithManager); assertTrue(cache == actualCacheRegisteredWithManager); Cache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); singletonManager.removeCache(actualCacheRegisteredWithManager.getName()); actualCacheRegisteredWithManager = singletonManager.addCacheIfAbsent(newCache); assertNotNull(actualCacheRegisteredWithManager); assertFalse(cache == actualCacheRegisteredWithManager); assertTrue(newCache == actualCacheRegisteredWithManager); assertTrue(singletonManager.addCacheIfAbsent(new Cache(new CacheConfiguration(actualCacheRegisteredWithManager.getName(), 1000))) == actualCacheRegisteredWithManager); assertNull(singletonManager.addCacheIfAbsent((Ehcache) null)); } |
### Question:
ResourceClassLoader extends ClassLoader { @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("java.")) { return getParent().loadClass(name); } Class c = findLoadedClass(name); if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; } ResourceClassLoader(String prefix, ClassLoader parent); @Override synchronized Class<?> loadClass(String name, boolean resolve); @Override URL getResource(String name); @Override /** * very similar to what OracleJDK classloader does, * except the first resources (more important) are the ones found with our ResourceClassLoader */ Enumeration<URL> getResources(String resourceName); }### Answer:
@Test(expected = ClassNotFoundException.class) public void contentOfTheJarNotVisibleWithNormalClassLoaderTest() throws ClassNotFoundException { Class<?> simpleClass = testCaseClassLoader.loadClass("pof.Simple"); } |
### Question:
OnHeapCachingTier implements CachingTier<K, V> { @Override public V get(final K key, final Callable<V> source, final boolean updateStats) { if (updateStats) { getObserver.begin(); } Object cachedValue = backEnd.get(key); if (cachedValue == null) { if (updateStats) { getObserver.end(GetOutcome.MISS); } Fault<V> f = new Fault<V>(source); cachedValue = backEnd.putIfAbsent(key, f); if (cachedValue == null) { try { V value = f.get(); putObserver.begin(); if (value == null) { backEnd.remove(key, f); } else if (backEnd.replace(key, f, value)) { putObserver.end(PutOutcome.ADDED); } else { V p = getValue(backEnd.remove(key)); return p == null ? value : p; } return value; } catch (Throwable e) { backEnd.remove(key, f); if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new CacheException(e); } } } } else { if (updateStats) { getObserver.end(GetOutcome.HIT); } } return getValue(cachedValue); } OnHeapCachingTier(final HeapCacheBackEnd<K, Object> backEnd); static OnHeapCachingTier<Object, Element> createOnHeapCache(final Ehcache cache, final Pool onHeapPool); @Override boolean loadOnPut(); @Override V get(final K key, final Callable<V> source, final boolean updateStats); @Override V remove(final K key); @Override void clear(); @Override void addListener(final Listener<K, V> listener); @Statistic(name = "size", tags = "local-heap") @Override int getInMemorySize(); @Override int getOffHeapSize(); @Override boolean contains(final K key); @Statistic(name = "size-in-bytes", tags = "local-heap") @Override long getInMemorySizeInBytes(); @Override long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override void recalculateSize(final K key); @Override Policy getEvictionPolicy(); @Override void setEvictionPolicy(final Policy policy); }### Answer:
@Test public void testOnlyPopulatesOnce() throws InterruptedException, BrokenBarrierException { final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CachingTier<String, String> cache = new OnHeapCachingTier<String, String>(new CountBasedBackEnd<String, Object>(threadCount * 2)); final AtomicBoolean failure = new AtomicBoolean(); final AtomicInteger invocationCounter = new AtomicInteger(); final AtomicInteger valuesRead = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { try { final int await = barrier.await(); cache.get(KEY, new Callable<String>() { @Override public String call() throws Exception { invocationCounter.incrementAndGet(); return "0x" + Integer.toHexString(await); } }, false); valuesRead.getAndIncrement(); } catch (Exception e) { e.printStackTrace(); failure.set(true); } } }; threads[i].start(); } barrier.await(); for (Thread thread : threads) { thread.join(); } assertThat(failure.get(), is(false)); assertThat(invocationCounter.get(), is(1)); assertThat(valuesRead.get(), is(threadCount)); } |
### Question:
DfltSamplerRepositoryService implements ManagementServerLifecycle,
EntityResourceFactory, CacheManagerService, CacheService, AgentService { @Override public Collection<CacheEntity> createCacheEntities(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> attributes) { CacheEntityBuilder builder = null; Collection<CacheEntity> entities; cacheManagerSamplerRepoLock.readLock().lock(); List<SamplerRepoEntry> disabledSamplerRepoEntries = new ArrayList<SamplerRepoEntry>(); try { if (cacheManagerNames == null) { for (Map.Entry<String, SamplerRepoEntry> entry : cacheManagerSamplerRepo.entrySet()) { enableNonStopFor(entry.getValue(), false); disabledSamplerRepoEntries.add(entry.getValue()); for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) { builder = builder == null ? CacheEntityBuilder.createWith(sampler, entry.getKey()) : builder .add(sampler, entry.getKey()); } } } else { for (String cmName : cacheManagerNames) { SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName); if (entry != null) { enableNonStopFor(entry, false); disabledSamplerRepoEntries.add(entry); for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) { builder = builder == null ? CacheEntityBuilder.createWith(sampler, cmName) : builder.add(sampler, cmName); } } } } if (builder == null) { entities = new HashSet<CacheEntity>(0); } else { entities = attributes == null ? builder.build() : builder.add(attributes).build(); } } finally { for (SamplerRepoEntry samplerRepoEntry : disabledSamplerRepoEntries) { enableNonStopFor(samplerRepoEntry, true); } cacheManagerSamplerRepoLock.readLock().unlock(); } return entities; } DfltSamplerRepositoryService(ManagementRESTServiceConfiguration configuration,
RemoteAgentEndpointImpl remoteAgentEndpoint); @Override void dispose(); @Override void register(CacheManager cacheManager); @Override void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override Collection<CacheManagerEntity> createCacheManagerEntities(Set<String> cacheManagerNames,
Set<String> attributes); @Override Collection<CacheManagerConfigEntity> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override Collection<CacheEntity> createCacheEntities(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> attributes); @Override Collection<CacheConfigEntity> createCacheConfigEntities(Set<String> cacheManagerNames,
Set<String> cacheNames); @Override Collection<CacheStatisticSampleEntity> createCacheStatisticSampleEntity(Set<String> cacheManagerNames,
Set<String> cacheNames,
Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName,
String cacheName,
CacheEntity resource); @Override void clearCache(String cacheManagerName,
String cacheName); @Override void updateCacheManager(String cacheManagerName,
CacheManagerEntity resource); @Override Collection<QueryResultsEntity> executeQuery(String cacheManagerName, String queryString); @Override Collection<AgentEntity> getAgents(Set<String> ids); @Override Collection<AgentMetadataEntity> getAgentsMetadata(Set<String> ids); static final String AGENCY; }### Answer:
@Test public void testCanAddDecoratedCache() { String cacheName = "decoratedTestCache"; Cache underlyingCache = new Cache(new CacheConfiguration(cacheName, 10)); cacheManager.addCache(new BlockingCache(underlyingCache)); assertThat(repositoryService.createCacheEntities(null, singleton(cacheName), null).isEmpty(), is(false)); }
@Test public void testCreateCacheEntitiesDisablesNonStop() throws Exception { repositoryService.createCacheEntities(Collections.singleton("testCacheManager"), Collections.singleton("testCache1"), Collections.singleton("Size")); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } |
### Question:
ManagementService implements CacheManagerEventListener { public void init() throws CacheException { CacheManager cacheManager = new CacheManager(backingCacheManager); try { registerCacheManager(cacheManager); registerPeerProviders(); List caches = cacheManager.getCaches(); for (int i = 0; i < caches.size(); i++) { Cache cache = (Cache) caches.get(i); registerCachesIfRequired(cache); registerCacheStatisticsIfRequired(cache); registerCacheConfigurationIfRequired(cache); registerCacheStoreIfRequired(cache); } } catch (Exception e) { throw new CacheException(e); } status = Status.STATUS_ALIVE; backingCacheManager.getCacheManagerEventListenerRegistry().registerListener(this); } ManagementService(net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics,
boolean registerCacheStores); ManagementService(net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics,
boolean registerCacheStores); static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer:
@Test public void testRegistrationServiceFourTrueUsing14MBeanServerWithConstructorInjection() throws Exception { mBeanServer = create14MBeanServer(); ManagementService managementService = new ManagementService(manager, mBeanServer, true, true, true, true, true); managementService.init(); assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE)); }
@Test public void testRegistrationServiceFourTrueUsing14MBeanServerWithConstructorInjection() throws Exception { mBeanServer = create14MBeanServer(); ManagementService managementService = new ManagementService(manager, mBeanServer, true, true, true, true, true); managementService.init(); assertEquals(OBJECTS_IN_TEST_EHCACHE, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size()); } |
### Question:
ElementResource { @DELETE public void deleteElement() throws WebApplicationException { LOG.debug("DELETE element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); if (element.equals("*")) { ehcache.removeAll(); } else { boolean removed = ehcache.remove(element); if (!removed) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } } ElementResource(UriInfo uriInfo, Request request,
String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer:
@Test public void testDeleteElement() throws Exception { long beforeCreated = System.currentTimeMillis(); Thread.sleep(10); String originalString = "The rain in Spain falls mainly on the plain"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(originalString.getBytes()); int status = HttpUtil.put("http: assertEquals(201, status); HttpURLConnection urlConnection = HttpUtil.get("http: assertEquals(200, urlConnection.getResponseCode()); urlConnection = HttpUtil.delete("http: assertEquals(204, urlConnection.getResponseCode()); assertEquals(404, HttpUtil.get("http: } |
### Question:
ElementResource { @GET public Response getElement() { LOG.debug("GET element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); net.sf.ehcache.Element ehcacheElement = lookupElement(ehcache); Element localElement = new Element(ehcacheElement, uriInfo.getAbsolutePath().toString()); Date lastModifiedDate = createLastModified(ehcacheElement); EntityTag entityTag = createETag(ehcacheElement); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModifiedDate, entityTag); if (responseBuilder != null) { return responseBuilder.build(); } else { return Response.ok(localElement.getValue(), localElement.getMimeType()) .lastModified(lastModifiedDate) .tag(entityTag) .header("Expires", (new Date(localElement.getExpirationDate())).toString()) .build(); } } ElementResource(UriInfo uriInfo, Request request,
String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer:
@Test public void testGetElement() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: } |
### Question:
CacheResource { @GET public Cache getCache() { LOG.debug("GET Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); if (ehcache == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } String cacheAsString = ehcache.toString(); cacheAsString = cacheAsString.substring(0, cacheAsString.length() - 1); cacheAsString = cacheAsString + "size = " + ehcache.getSize() + " ]"; return new Cache(ehcache.getName(), uriInfo.getAbsolutePath().toString(), cacheAsString, new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element") String element); }### Answer:
@Test public void testGetCache() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: } |
### Question:
CacheResource { @DELETE public Response deleteCache() { LOG.debug("DELETE Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); Response response; if (ehcache == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } else { CacheManager.getInstance().removeCache(cache); response = Response.ok().build(); } return response; } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element") String element); }### Answer:
@Test public void testDeleteCache() throws Exception { HttpURLConnection urlConnection = HttpUtil.put("http: urlConnection = HttpUtil.delete("http: assertEquals(200, urlConnection.getResponseCode()); if (urlConnection.getHeaderField("Server").matches("(.*)Glassfish(.*)")) { assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); } String responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); assertEquals("", responseBody); urlConnection = HttpUtil.delete("http: assertEquals(404, urlConnection.getResponseCode()); } |
### Question:
CachesResource { @GET public List<Cache> getCaches() { LOG.debug("GET Caches"); String[] cacheNames = MANAGER.getCacheNames(); List<Cache> cacheList = new ArrayList<Cache>(); for (String cacheName : cacheNames) { Ehcache ehcache = MANAGER.getCache(cacheName); URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize(); Cache cache = new Cache(cacheName, cacheUri.toString(), ehcache.toString(), new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); cacheList.add(cache); } return cacheList; } @Path("{cache}") CacheResource getCacheResource(@PathParam("cache") String cache); @GET List<Cache> getCaches(); }### Answer:
@Test public void testGetCaches() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(result.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); String cacheCount = xpath.evaluate("count( assertTrue(Integer.parseInt(cacheCount) >= 6); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public String ping() { return "pong"; } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testPing() { String result = cacheService.ping(); assertEquals("pong", result); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public Cache getCache(String cacheName) throws CacheException { Ehcache ehcache = manager.getCache(cacheName); if (ehcache != null) { return new Cache(ehcache); } else { return null; } } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetCache() throws CacheException_Exception, NoSuchCacheException_Exception { Cache cache = cacheService.getCache("doesnotexist"); assertNull(cache); cache = cacheService.getCache("sampleCache1"); assertEquals("sampleCache1", cache.getName()); assertEquals("rest/sampleCache1", cache.getUri()); assertTrue(cache.getDescription().indexOf("sampleCache1") != -1); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { manager.addCache(cacheName); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testAddCache() throws Exception { cacheService.addCache("newcache1"); Cache cache = cacheService.getCache("newcache1"); assertNotNull(cache); try { cacheService.addCache("newcache1"); } catch (SOAPFaultException e) { assertTrue(e.getCause().getMessage().indexOf("Cache newcache1 already exists") != -1); } } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void removeCache(String cacheName) throws IllegalStateException { manager.removeCache(cacheName); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testRemoveCache() throws Exception { cacheService.addCache("newcache2"); Cache cache = cacheService.getCache("newcache2"); assertNotNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); cacheService.removeCache("newcache2"); cache = cacheService.getCache("newcache2"); assertNull(cache); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public String[] cacheNames() throws IllegalStateException { return manager.getCacheNames(); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testCacheNames() throws IllegalStateException_Exception { List cacheNames = cacheService.cacheNames(); assertTrue(cacheNames.size() >= 6); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public Status getStatus(String cacheName) { net.sf.ehcache.Cache cache = lookupCache(cacheName); return Status.fromCode(cache.getStatus().intValue()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testCacheStatus() throws CacheException_Exception, NoSuchCacheException_Exception { Status status = cacheService.getStatus("sampleCache1"); assertTrue(status == Status.STATUS_ALIVE); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void put(String cacheName, Element element) throws NoSuchCacheException, CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.put(element.getEhcacheElement()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testCachePutNull() throws Exception, NoSuchCacheException_Exception, IllegalStateException_Exception { Element element = new Element(); element.setKey("1"); cacheService.put("sampleCache1", element); element = getElementFromCache(); boolean equals = Arrays.equals(null, element.getValue()); assertTrue(equals); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public List getKeys(String cacheName) throws IllegalStateException, CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return cache.getKeys(); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetKeys() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { for (int i = 0; i < 1000; i++) { Element element = new Element(); element.setKey(i); element.setValue(("value" + i).getBytes()); cacheService.put("sampleCache1", element); } List keys = cacheService.getKeys("sampleCache1"); assertEquals(1000, keys.size()); keys = cacheService.getKeysWithExpiryCheck("sampleCache1"); assertEquals(1000, keys.size()); keys = cacheService.getKeysNoDuplicateCheck("sampleCache1"); assertEquals(1000, keys.size()); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public boolean remove(String cacheName, String key) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return cache.remove(key); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testRemove() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { putElementIntoCache(); assertEquals(1, cacheService.getSize("sampleCache1")); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public Statistics getStatistics(String cacheName) throws IllegalStateException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return new Statistics(cache.getStatistics()); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetStatistics() throws Exception { Statistics statistics = cacheService.getStatistics("sampleCache1"); long hitBaseline = statistics.getCacheHits(); long evictionBaseline = statistics.getEvictionCount(); long memoryHitBaseline = statistics.getInMemoryHits(); long diskHitBaseline = statistics.getOnDiskHits(); putElementIntoCache(); getElementFromCache(); statistics = cacheService.getStatistics("sampleCache1"); assertEquals(hitBaseline + 1L, statistics.getCacheHits()); assertEquals(evictionBaseline + 0L, statistics.getEvictionCount()); assertEquals(memoryHitBaseline + 1L, statistics.getInMemoryHits()); assertEquals(diskHitBaseline + 0L, statistics.getOnDiskHits()); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void load(String cacheName, String key) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.load(key); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testLoad() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { cacheService.load("sampleCache1", "2"); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public void loadAll(String cacheName, Collection<String> keys) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); cache.loadAll(keys, null); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testLoadAll() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { List keys = new ArrayList(); for (int i = 0; i < 5; i++) { keys.add("" + i); } cacheService.loadAll("sampleCache1", keys); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public Element getWithLoader(String cacheName, String key) { net.sf.ehcache.Cache cache = lookupCache(cacheName); net.sf.ehcache.Element element = cache.getWithLoader(key, null, null); if (element != null) { return new Element(element); } else { return null; } } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetWithLoad() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { cacheService.getWithLoader("sampleCache1", "2"); } |
### Question:
EhcacheWebServiceEndpoint { @WebMethod public HashMap getAllWithLoader(String cacheName, Collection keys) throws CacheException { net.sf.ehcache.Cache cache = lookupCache(cacheName); return (HashMap) cache.getAllWithLoader(keys, null); } @WebMethod String ping(); @WebMethod Cache getCache(String cacheName); @WebMethod void addCache(String cacheName); @WebMethod void removeCache(String cacheName); @WebMethod String[] cacheNames(); @WebMethod Status getStatus(String cacheName); @WebMethod void put(String cacheName, Element element); @WebMethod Element get(String cacheName, String key); @WebMethod List getKeys(String cacheName); @WebMethod boolean remove(String cacheName, String key); @WebMethod List getKeysWithExpiryCheck(String cacheName); @WebMethod List getKeysNoDuplicateCheck(String cacheName); @WebMethod Element getQuiet(String cacheName, Object key); @WebMethod void putQuiet(String cacheName, Element element); @WebMethod boolean removeQuiet(String cacheName, String key); @WebMethod void removeAll(String cacheName); @WebMethod int getSize(String cacheName); @WebMethod Statistics getStatistics(String cacheName); @WebMethod void load(String cacheName, String key); @WebMethod void loadAll(String cacheName, Collection<String> keys); @WebMethod HashMap getAllWithLoader(String cacheName, Collection keys); @WebMethod Element getWithLoader(String cacheName, String key); }### Answer:
@Test public void testGetAllWithLoader() throws NoSuchCacheException_Exception, CacheException_Exception, IllegalStateException_Exception { List keys = new ArrayList(); for (int i = 0; i < 5; i++) { keys.add("" + i); } cacheService.getAllWithLoader("sampleCache1", keys); } |
### Question:
CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); Ehcache ehcache = ehcaches.get(name); return ehcache instanceof Cache ? (Cache) ehcache : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); runtimeCfg.removeCache(cache.getCacheConfiguration()); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testRemoveCache() throws CacheException { Configuration config = new Configuration().cache(new CacheConfiguration("foo", 100)); CacheManager manager = new CacheManager(config); try { assertEquals(1, manager.getConfiguration().getCacheConfigurations().size()); assertNotNull(manager.getCache("foo")); manager.removeCache("foo"); assertNull(manager.getCache("foo")); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.removeCache(null); manager.removeCache(""); assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); if (clonedDefaultCache == null) { throw new CacheException(NO_DEFAULT_CACHE_ERROR_MSG); } addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCache() throws CacheException { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxEntriesLocalHeap(0)); CacheManager manager = new CacheManager(config); try { assertEquals(0, manager.getConfiguration().getCacheConfigurations().size()); manager.addCache("test"); manager.addCache("test2"); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = manager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = manager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); manager.addCache(""); assertEquals(2, manager.getConfiguration().getCacheConfigurations().size()); } finally { manager.shutdown(); } } |
### Question:
CacheManager { public synchronized Ehcache addCacheIfAbsent(final Ehcache cache) { checkStatus(); return cache == null ? null : addCacheNoCheck(cache, false); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removeAllCaches(); @Deprecated void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer:
@Test public void testAddCacheIfAbsent() { Configuration config = new Configuration().defaultCache(new CacheConfiguration().maxEntriesLocalHeap(100)); CacheManager manager = new CacheManager(config); try { manager.addCache("present"); assertThat(manager.addCacheIfAbsent(new Cache(new CacheConfiguration("present", 1000))), sameInstance(manager.getEhcache("present"))); Ehcache theCache = new Cache(new CacheConfiguration("absent", 1000)); Ehcache cache = manager.addCacheIfAbsent(theCache); assertNotNull(cache); assertThat(cache, sameInstance(theCache)); assertThat(cache.getName(), is("absent")); Ehcache other = new Cache(new CacheConfiguration(cache.getName(), 1000)); Ehcache actual = manager.addCacheIfAbsent(other); assertThat(actual, notNullValue()); assertThat(actual, not(sameInstance(other))); assertThat(actual, sameInstance(cache)); Ehcache newCache = new Cache(new CacheConfiguration(cache.getName(), 1000)); manager.removeCache(actual.getName()); actual = manager.addCacheIfAbsent(newCache); assertThat(actual, notNullValue()); assertThat(actual, not(sameInstance(cache))); assertThat(actual, sameInstance(newCache)); assertThat(manager.addCacheIfAbsent(new Cache(new CacheConfiguration(actual.getName(), 1000))), sameInstance(actual)); assertThat(manager.addCacheIfAbsent((Ehcache) null), nullValue()); } finally { manager.shutdown(); } } |
### Question:
SizeOf { public SizeOf(SizeOfFilter fieldFilter, boolean caching) { ObjectGraphWalker.Visitor visitor; if (caching) { visitor = new CachingSizeOfVisitor(); } else { visitor = new SizeOfVisitor(); } this.walker = new ObjectGraphWalker(visitor, fieldFilter); } SizeOf(SizeOfFilter fieldFilter, boolean caching); long sizeOf(Object obj); Size deepSizeOf(int maxDepth, boolean abortWhenMaxDepthExceeded, Object... obj); }### Answer:
@Test public void testSizeOf() throws Exception { Assume.assumeThat(CURRENT_JVM_INFORMATION.getMinimumObjectSize(), is(CURRENT_JVM_INFORMATION.getObjectAlignment())); SizeOf sizeOf = new CrossCheckingSizeOf(); if (System.getProperty("java.version").startsWith("1.5")) { if (IS_64_BIT) { verify64bitSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(136L)); } else { verify32bitSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(80L)); } } else { if (IS_64_BIT) { if (IS_JROCKIT) { verify64bitJRockit4GBCompressedRefsSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(144L)); } else if (IS_IBM) { verify64bitIBMSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(224L)); } else if (COMPRESSED_OOPS) { verify64bitCompressedOopsSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(112L)); } else { verify64bitSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(176L)); } } else if (IS_IBM) { verify32bitIBMSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(112L)); } else if (IS_JROCKIT) { verify32bitJRockitSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(144L)); } else { verify32bitSizes(sizeOf); assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), is(104L)); } } List<Object> list1 = new ArrayList<Object>(); List<Object> list2 = new ArrayList<Object>(); Object someInstance = new Object(); list1.add(someInstance); list2.add(someInstance); assertThat(deepSizeOf(sizeOf, list1), equalTo(deepSizeOf(sizeOf, list2))); assertThat(deepSizeOf(sizeOf, list1, list2) < (deepSizeOf(sizeOf, list1) + deepSizeOf(sizeOf, list2)), is(true)); list2.add(new Object()); assertThat(deepSizeOf(sizeOf, list2) > deepSizeOf(sizeOf, list1), is(true)); } |
### Question:
SizeOf { public Size deepSizeOf(int maxDepth, boolean abortWhenMaxDepthExceeded, Object... obj) { try { return new Size(walker.walk(maxDepth, abortWhenMaxDepthExceeded, obj), true); } catch (MaxDepthExceededException e) { LOG.warn(e.getMessage()); return new Size(e.getMeasuredSize(), false); } } SizeOf(SizeOfFilter fieldFilter, boolean caching); long sizeOf(Object obj); Size deepSizeOf(int maxDepth, boolean abortWhenMaxDepthExceeded, Object... obj); }### Answer:
@Test public void testOnHeapConsumption() throws Exception { SizeOf sizeOf = new CrossCheckingSizeOf(); int size = 80000; for (int j = 0; j < 5; j++) { container = new Object[size]; long usedBefore = measureMemoryUse(); for (int i = 0; i < size; i++) { container[i] = new EvilPair(new Object(), new SomeClass(i % 2 == 0)); } long mem = 0; for (Object s : container) { mem += deepSizeOf(sizeOf, s); } long used = measureMemoryUse() - usedBefore; float percentage = 1 - (mem / (float) used); System.err.println("Run # " + (j + 1) + ": Deviation of " + (int)(percentage * -100) + "%\n" + used + " bytes are actually being used, while we believe " + mem + " are"); if (j > 1) { assertThat("Run # " + (j + 1) + ": Deviation of " + (int)(percentage * -100) + "% was above the +/-1.5% delta threshold \n" + used + " bytes are actually being used, while we believe " + mem + " are (" + (used - mem) / size + ")", Math.abs(percentage) < .015f, is(true)); } } } |
### Question:
ManagementService implements CacheManagerEventListener { private void registerCacheManager(CacheManager cacheManager) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { if (registerCacheManager) { mBeanServer.registerMBean(cacheManager, cacheManager.getObjectName()); } } ManagementService(net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics,
boolean registerCacheStores); ManagementService(net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics,
boolean registerCacheStores); static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer:
@Test public void testRegisterCacheManager() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testNoOverflowToDisk", 1, false, false, 500, 200); manager.addCache(ehcache); ehcache.put(new Element("key1", "value1")); ehcache.put(new Element("key2", "value1")); assertNull(ehcache.get("key1")); assertNotNull(ehcache.get("key2")); ObjectName name = new ObjectName("net.sf.ehcache:type=CacheManager,name=1"); CacheManager cacheManager = new CacheManager(manager); mBeanServer.registerMBean(cacheManager, name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=testOverflowToDisk"); mBeanServer.registerMBean(new Cache(ehcache), name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=sampleCache1"); mBeanServer.registerMBean(new Cache(manager.getCache("sampleCache1")), name); mBeanServer.unregisterMBean(name); }
@Test public void testRegisterCacheManager() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testNoOverflowToDisk", 1, false, false, 500, 200); manager.addCache(ehcache); ehcache.put(new Element("key1", "value1")); ehcache.put(new Element("key2", "value1")); assertThat(ehcache.get("key1"), nullValue()); assertThat(ehcache.get("key2"), notNullValue()); ObjectName name = new ObjectName("net.sf.ehcache:type=CacheManager,name=1"); CacheManager cacheManager = new CacheManager(manager); mBeanServer.registerMBean(cacheManager, name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=testOverflowToDisk"); mBeanServer.registerMBean(new Cache(ehcache), name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=sampleCache1"); mBeanServer.registerMBean(new Cache(manager.getCache("sampleCache1")), name); mBeanServer.unregisterMBean(name); } |
### Question:
SelfPopulatingCache extends BlockingCache { public Element get(final Object key) throws LockTimeoutException { try { Element element = super.get(key); if (element == null) { Object value = factory.createEntry(key); element = makeAndCheckElement(key, value); put(element); } return element; } catch (LockTimeoutException e) { String message = "Timeout after " + timeoutMillis + " waiting on another thread " + "to fetch object for cache entry \"" + key + "\"."; throw new LockTimeoutException(message, e); } catch (final Throwable throwable) { put(new Element(key, null)); throw new CacheException("Could not fetch object for cache entry with key \"" + key + "\".", throwable); } } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer:
@Test public void testFetch() throws Exception { LOG.error("."); final Element element = selfPopulatingCache.get("key"); assertEquals("value", element.getValue()); }
@Test public void testFetchUnknown() throws Exception { final CacheEntryFactory factory = new CountingCacheEntryFactory(null); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertNull(cache.get("key")); }
@Test public void testFetchFail() throws Exception { final Exception exception = new Exception("Failed."); final CacheEntryFactory factory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { throw exception; } }; selfPopulatingCache = new SelfPopulatingCache(cache, factory); try { selfPopulatingCache.get("key"); fail(); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } }
@Test public void testCreateOnce() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); for (int i = 0; i < 5; i++) { assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); } }
@Test public void testCacheEntryFactoryReturningElementMake() throws Exception { final long specialVersionNumber = 54321L; final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Element e = new Element(key, "V_" + key); e.setVersion(specialVersionNumber); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); Element e = null; e = selfPopulatingCache.get("key1"); assertEquals("V_key1", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); e = selfPopulatingCache.get("key2"); assertEquals("V_key2", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); assertEquals(2, selfPopulatingCache.getSize()); }
@Test public void testCacheEntryFactoryReturningElementBadKey() throws Exception { final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Object modifiedKey = key.toString() + "XX"; Element e = new Element(modifiedKey, "V_" + modifiedKey); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); try { selfPopulatingCache.get("key"); fail("Should fail because key was changed"); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } }
@Test public void testFetch() throws Exception { LOG.log(Level.SEVERE, "."); final Element element = selfPopulatingCache.get("key"); assertEquals("value", element.getValue()); } |
### Question:
SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { refresh(true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer:
@Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.