[jboss-cvs] JBossCache/tests/functional/org/jboss/cache/pojo/optimistic ...
Ben Wang
bwang at jboss.com
Sat Jan 13 10:55:11 EST 2007
User: bwang
Date: 07/01/13 10:55:11
Added: tests/functional/org/jboss/cache/pojo/optimistic
LocalTxTest.java AbstractOptimisticTestCase.java
CachedListTest.java
Log:
JBCACHE-922 Merged src-50 and tests-50 into src and tests, respectively.
Revision Changes Path
1.1 date: 2007/01/13 15:55:11; author: bwang; state: Exp;JBossCache/tests/functional/org/jboss/cache/pojo/optimistic/LocalTxTest.java
Index: LocalTxTest.java
===================================================================
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.cache.pojo.optimistic;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.Fqn;
import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.TestingUtil;
import org.jboss.cache.pojo.test.Address;
import org.jboss.cache.pojo.test.Person;
import org.jboss.cache.pojo.util.CacheApiUtil;
import org.jboss.cache.transaction.DummyTransactionManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.UserTransaction;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
*/
public class LocalTxTest extends AbstractOptimisticTestCase
{
Log log = LogFactory.getLog(LocalTxTest.class);
PojoCache cache;
final String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
DummyTransactionManager tx_mgr;
Throwable t1_ex, t2_ex;
long start = 0;
public LocalTxTest(String name)
{
super(name);
}
protected void setUp() throws Exception
{
super.setUp();
log.info("setUp() ....");
cache = createCache();
// cache = createPessimisticCache();
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
tx_mgr = DummyTransactionManager.getInstance();
t1_ex = t2_ex = null;
}
protected void tearDown()
{
super.tearDown();
cache.stop();
DummyTransactionManager.destroy();
}
// public void testDummy() {}
UserTransaction getTransaction() throws SystemException, NotSupportedException, NamingException
{
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.cache.transaction.DummyContextFactory");
return (UserTransaction) new InitialContext(prop).lookup("UserTransaction");
}
private Person createPerson(String id, String name, int age)
{
Person p = new Person();
p.setName(name);
p.setAge(age);
cache.attach(id, p);
return p;
}
public void testSimple() throws Exception
{
log.info("testSimple() ....");
UserTransaction tx = getTransaction();
tx.begin();
Person p = createPerson("/person/test1", "Harald Gliebe", 32);
tx.commit();
tx.begin();
p.setName("Benoit");
tx.commit();
Person p1 = (Person) cache.find("/person/test1");
assertEquals("Benoit", p.getName());
assertEquals("Benoit", p1.getName());
tx.begin();
p1.setAge(41);
tx.commit();
assertEquals(41, p.getAge());
assertEquals(41, p1.getAge());
}
public void testFailure() throws Exception
{
log.info("testFailure() ....");
UserTransaction tx = getTransaction();
tx.begin();
Person p = createPerson("/person/test1", "Harald Gliebe", 32);
tx.commit();
tx.begin();
p = createPerson("/person/test1", "Harald Gliebe", 32);
tx.commit();
}
public void testFailure1() throws Exception
{
log.info("testFailure1() ....");
UserTransaction tx = getTransaction();
org.jboss.cache.Fqn f = new org.jboss.cache.Fqn("/person/test2");
tx.begin();
cache.getCache().put(f, "test", "test");
tx.commit();
tx.begin();
cache.getCache().removeNode(f);
cache.getCache().put(f, "test", "test");
tx.commit();
}
public void testFailure2() throws Exception
{
Fqn f0 = Fqn.fromString("/person/test");
Fqn f1 = new Fqn(f0, "1");
Fqn f2 = new Fqn(f0, "2");
cache.getCache().put(f1, "test", "test");
cache.getCache().put(f2, "test", "test");
int size = CacheApiUtil.getNodeChildren((CacheSPI) cache.getCache(), f0).size();
assertEquals("Size ", 2, size);
UserTransaction tx = getTransaction();
tx.begin();
cache.getCache().removeNode(f1);
size = CacheApiUtil.getNodeChildren((CacheSPI) cache.getCache(), f0).size();
assertEquals("Size ", 1, size);
cache.getCache().put(f1, "test", "test");
size = CacheApiUtil.getNodeChildren((CacheSPI) cache.getCache(), f0).size();
assertEquals("Size ", 2, size);
tx.commit();
}
public void testModification() throws Exception
{
UserTransaction tx = getTransaction();
tx.begin();
Person p = createPerson("/person/test2", "Harald", 32);
p.setName("Harald Gliebe");
tx.commit();
Person p1 = (Person) cache.find("/person/test2");
tx.begin();
p1.setName("Benoit");
tx.commit();
assertEquals(p.getName(), "Benoit");
assertEquals(p1.getName(), "Benoit");
tx.begin();
p1.setName("Harald");
tx.rollback();
assertEquals(p.getName(), "Benoit");
assertEquals(p1.getName(), "Benoit");
}
public void testConcurrentSimplePutsI() throws Exception
{
Thread t1 = new Thread("t1")
{
Transaction tx;
public void run()
{
try
{
Person p = createPerson("/person/test6", "p6", 41);
Address addr = new Address();
addr.setCity("San Jose");
List list = new ArrayList();
list.add("English");
list.add("French");
p.setLanguages(list);
UserTransaction tx = getTransaction();
tx.begin();
p.setAddress(addr);
TestingUtil.sleepThread(17000);
tx.commit();
}
catch (RollbackException rollback)
{
;
}
catch (Exception ex)
{
t1_ex = ex;
}
}
};
Thread t2 = new Thread("t2")
{
Transaction tx;
public void run()
{
UserTransaction tx = null;
try
{
TestingUtil.sleepThread(1000); // give Thread1 time to createPerson
Person p = createPerson("/person/test7", "p7", 40);
Address addr = new Address();
addr.setCity("Santa Clara");
tx = getTransaction();
tx.begin();
p.setAddress(addr);
tx.commit();
}
catch (RollbackException rollback)
{
;
}
catch (Exception ex)
{
// t2_ex = ex;
try
{
tx.rollback();
}
catch (SystemException e)
{
e.printStackTrace();
t2_ex = e;
}
}
}
};
Person p = createPerson("/person/test5", "p5", 30);
t1.start();
t2.start();
t1.join();
t2.join();
// t2 should rollback due to timeout while t2 should succeed
if (t2_ex != null)
fail("Thread2 failed: " + t2_ex);
if (t1_ex != null)
fail("Thread1 failed: " + t1_ex);
}
public void testConcurrentSimplePutsII() throws Exception
{
Thread t1 = new Thread("t1")
{
Transaction tx;
public void run()
{
try
{
Person p = (Person) cache.find("/person/test6");
Address addr = new Address();
addr.setCity("San Jose");
UserTransaction tx = getTransaction();
tx.begin();
p.setAddress(addr);
TestingUtil.sleepThread(17000);
tx.commit();
}
catch (RollbackException rollback)
{
;
}
catch (Exception ex)
{
t1_ex = ex;
}
}
};
Thread t2 = new Thread("t2")
{
Transaction tx;
public void run()
{
UserTransaction tx = null;
try
{
TestingUtil.sleepThread(1000); // give Thread1 time to createPerson
Person p = (Person) cache.find("/person/test6");
Address addr = new Address();
addr.setCity("Santa Clara");
tx = getTransaction();
tx.begin();
p.setAddress(addr);
tx.commit();
}
catch (RollbackException rollback)
{
;
}
catch (Exception ex)
{
// t2_ex = ex;
try
{
tx.rollback();
}
catch (SystemException e)
{
e.printStackTrace();
t2_ex = e;
}
}
}
};
Person p = createPerson("/person/test6", "p6", 40);
t1.start();
t2.start();
t1.join();
t2.join();
// t2 should rollback due to timeout while t2 should succeed
if (t2_ex != null)
fail("Thread1 failed: " + t2_ex);
if (t1_ex != null)
fail("Thread2 failed: " + t1_ex);
// This would fail because we are writing to __JBossInteral__ for every attach now.
// As a result, there is version conflict for optimistic locking and cuasing
// rollback.
assertNotSame("City should be different ", "San Jose", p.getAddress().getCity());
}
public void testConcurrentPuts() throws Exception
{
Thread t1 = new Thread("t1")
{
Transaction tx;
public void run()
{
try
{
List<String> lang = ((Person) cache.find("/person/test6")).getLanguages();
UserTransaction tx = getTransaction();
tx.begin();
lang.add("German");
TestingUtil.sleepThread(17000);
tx.commit();
}
catch (RollbackException rollback)
{
;
}
catch (Exception ex)
{
t1_ex = ex;
}
}
};
Thread t2 = new Thread("t2")
{
Transaction tx;
public void run()
{
UserTransaction tx = null;
try
{
TestingUtil.sleepThread(1000); // give Thread1 time to createPerson
List<String> lang = ((Person) cache.find("/person/test6")).getLanguages();
tx = getTransaction();
tx.begin();
lang.add("English");
tx.commit();
}
catch (RollbackException rollback)
{
;
}
catch (Exception ex)
{
try
{
tx.rollback();
}
catch (SystemException e)
{
e.printStackTrace();
t2_ex = e;
}
}
}
};
Person p = createPerson("/person/test6", "p6", 50);
List<String> lang = new ArrayList<String>();
lang.add("German");
p.setLanguages(lang);
t1.start();
t2.start();
t1.join();
t2.join();
// t2 should rollback due to timeout while t2 should succeed
if (t2_ex != null)
fail("Thread1 failed: " + t2_ex);
if (t1_ex != null)
fail("Thread2 failed: " + t1_ex);
int size = ((Person) cache.find("/person/test6")).getLanguages().size();
assertEquals("number of languages ",
2, size);
}
void log(String s)
{
long now;
if (start == 0)
start = System.currentTimeMillis();
now = System.currentTimeMillis();
System.out.println("[" + Thread.currentThread().getName() + "] [" + (now - start) + "] " + s);
}
public static Test suite() throws Exception
{
return new TestSuite(LocalTxTest.class);
}
public static void main(String[] args) throws Exception
{
junit.textui.TestRunner.run(suite());
}
}
1.1 date: 2007/01/13 15:55:11; author: bwang; state: Exp;JBossCache/tests/functional/org/jboss/cache/pojo/optimistic/AbstractOptimisticTestCase.java
Index: AbstractOptimisticTestCase.java
===================================================================
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.cache.pojo.optimistic;
import junit.framework.TestCase;
import org.jboss.cache.Fqn;
import org.jboss.cache.CacheListener;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.PojoCacheFactory;
import org.jboss.cache.marshall.MethodCall;
import org.jboss.cache.marshall.MethodCallFactory;
import org.jboss.cache.marshall.MethodDeclarations;
import org.jboss.cache.interceptors.Interceptor;
import org.jboss.cache.interceptors.InvocationContextInterceptor;
import org.jboss.cache.interceptors.TxInterceptor;
import org.jboss.cache.interceptors.OptimisticReplicationInterceptor;
import org.jboss.cache.interceptors.OptimisticCreateIfNotExistsInterceptor;
import org.jboss.cache.interceptors.OptimisticNodeInterceptor;
import org.jboss.cache.transaction.DummyTransactionManager;
import org.jboss.cache.misc.TestingUtil;
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.factories.XmlConfigurationParser;
import org.jboss.cache.xml.XmlHelper;
import org.jboss.cache.optimistic.TestListener;
import org.jboss.cache.optimistic.DefaultDataVersion;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.CacheLoaderConfig;
import org.w3c.dom.Element;
import javax.transaction.TransactionManager;
import javax.transaction.SystemException;
import java.io.File;
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Base test for optimistic locking. Copied from Cache counterpart.
*/
public abstract class AbstractOptimisticTestCase extends TestCase
{
private int instanceNumber;
// some test data shared among all the test cases
protected Fqn fqn = Fqn.fromString("/blah");
protected String key = "myKey", value = "myValue";
protected String getTempDir()
{
return getTempDir("tempdir");
}
private String getTempDir(String name)
{
String tempDir = System.getProperty("java.io.tmpdir", "/tmp");
tempDir = tempDir + File.separator + name;
System.out.println("tmpdir property: " + System.getProperty("java.io.tmpdir"));
System.out.println("Attempting to create dir [" + tempDir + "]");
File tempDirFile = new File(tempDir);
if (!tempDirFile.exists())
{
tempDirFile.mkdirs();
}
return tempDir;
}
public AbstractOptimisticTestCase(String name)
{
super(name);
}
protected PojoCache createCacheUnstarted() throws Exception
{
return createCacheUnstarted(true);
}
protected PojoCache createCacheUnstarted(boolean optimistic) throws Exception
{
Configuration c = new Configuration();
if (optimistic) c.setNodeLockingScheme("OPTIMISTIC");
c.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
c.setCacheMode("LOCAL");
PojoCache cache = PojoCacheFactory.createCache(c, false);
return cache;
}
protected PojoCache createCacheWithListener() throws Exception
{
return createCacheWithListener(new TestListener());
}
protected PojoCache createCacheWithListener(CacheListener listener) throws Exception
{
PojoCache cache = createCacheUnstarted();
cache.create();
cache.start();
cache.getCache().addCacheListener(listener);
return cache;
}
/**
* Returns a tree cache with passivation disabled in the loader.
*
* @return
* @throws Exception
*/
protected PojoCache createCacheWithLoader() throws Exception
{
return createCacheWithLoader(false);
}
protected CacheLoaderConfig getCacheLoaderConfig(boolean shared, String filename, boolean passivation) throws Exception
{
String xml = " <config>\n" +
" <passivation>" + passivation + "</passivation>\n" +
" <preload></preload>\n" +
" <shared>" + shared + "</shared>\n" +
" <cacheloader>\n" +
" <class>org.jboss.cache.loader.FileCacheLoader</class>\n" +
" <properties>\n" +
" </properties>\n" +
" <async>false</async>\n" +
" <fetchPersistentState>" + (!shared) + "</fetchPersistentState>\n" +
" <ignoreModifications>false</ignoreModifications>\n" +
" </cacheloader>\n" +
" </config>";
Element element = XmlHelper.stringToElement(xml);
return XmlConfigurationParser.parseCacheLoaderConfig(element);
}
protected PojoCache createCacheWithLoader(boolean passivationEnabled) throws Exception
{
PojoCache cache = createCacheUnstarted();
Configuration c = cache.getCache().getConfiguration();
c.setCacheLoaderConfig(getCacheLoaderConfig(true, getTempDir(), passivationEnabled));
cache.create();
cache.start();
return cache;
}
protected PojoCache createCache() throws Exception
{
PojoCache cache = createCacheUnstarted();
cache.create();
cache.start();
return cache;
}
protected void destroyCache(PojoCache c)
{
c.stop();
c.destroy();
}
protected PojoCache createPessimisticCache() throws Exception
{
Configuration c = new Configuration();
c.setClusterName("name");
c.setInitialStateRetrievalTimeout(5000);
c.setClusterConfig(getDefaultProperties());
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
c.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
c.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
PojoCache cache = PojoCacheFactory.createCache(c, false);
cache.create();
cache.start();
return cache;
}
protected PojoCache createPessimisticCacheLocal() throws Exception
{
Configuration c = new Configuration();
c.setClusterName("name");
c.setInitialStateRetrievalTimeout(5000);
c.setClusterConfig(getDefaultProperties());
c.setCacheMode(Configuration.CacheMode.LOCAL);
c.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
c.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
PojoCache cache = PojoCacheFactory.createCache(c, false);
cache.create();
cache.start();
return cache;
}
protected String getDefaultProperties()
{
return "UDP(mcast_addr=228.1.2.3;mcast_port=48866;ip_ttl=32;" +
"mcast_send_buf_size=150000;mcast_recv_buf_size=80000;loopback=true;ip_mcast=true;bind_addr=127.0.0.1):" +
"PING(timeout=1000;num_initial_members=2):" +
"MERGE2(min_interval=5000;max_interval=10000):" +
"FD_SOCK:" +
"VERIFY_SUSPECT(timeout=1500):" +
"pbcast.NAKACK(gc_lag=50;max_xmit_size=8192;retransmit_timeout=600,1200,2400,4800):" +
"UNICAST(timeout=600,1200,2400,4800):" +
"pbcast.STABLE(desired_avg_gossip=20000):" +
"FRAG(frag_size=8192;down_thread=false;up_thread=false):" +
"pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
"shun=false;print_local_addr=true):" +
"pbcast.STATE_TRANSFER";
}
protected PojoCache createReplicatedCache(Configuration.CacheMode mode) throws Exception
{
return createReplicatedCache("test", mode);
}
protected PojoCache createReplicatedCache(String name, Configuration.CacheMode mode) throws Exception
{
Configuration c = new Configuration();
c.setClusterName(name);
c.setInitialStateRetrievalTimeout(5000);
c.setClusterConfig(getDefaultProperties());
c.setCacheMode(mode);
if (mode == Configuration.CacheMode.REPL_SYNC)
{
// make sure commits and rollbacks are sync as well
c.setSyncCommitPhase(true);
c.setSyncRollbackPhase(true);
}
c.setNodeLockingScheme("OPTIMISTIC");
c.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
PojoCache cache = PojoCacheFactory.createCache(c, false);
cache.create();
cache.start();
return cache;
}
protected PojoCache createReplicatedCacheWithLoader(boolean shared, Configuration.CacheMode cacheMode) throws Exception
{
return createReplicatedCacheWithLoader("temp-loader", shared, cacheMode);
}
protected PojoCache createReplicatedCacheWithLoader(boolean shared) throws Exception
{
return createReplicatedCacheWithLoader("temp-loader", shared, Configuration.CacheMode.REPL_SYNC);
}
protected PojoCache createReplicatedCacheWithLoader(String name, boolean shared) throws Exception
{
return createReplicatedCacheWithLoader(name, shared, Configuration.CacheMode.REPL_SYNC);
}
protected PojoCache createReplicatedCacheWithLoader(String name, boolean shared, Configuration.CacheMode cacheMode) throws Exception
{
Configuration c = new Configuration();
c.setClusterName(name);
c.setInitialStateRetrievalTimeout(5000);
c.setClusterConfig(getDefaultProperties());
c.setCacheMode(cacheMode);
c.setSyncCommitPhase(true);
c.setSyncRollbackPhase(true);
c.setNodeLockingScheme("OPTIMISTIC");
c.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
c.setCacheLoaderConfig(getCacheLoaderConfig(shared, shared ? getTempDir(name + "-shared") : getTempDir(name + instanceNumber++), false));
PojoCache cache = PojoCacheFactory.createCache(c, false);
cache.create();
cache.start();
return cache;
}
protected Random random;
protected void randomSleep(int min, int max)
{
if (random == null) random = new Random();
long l = -1;
while (l < min) l = random.nextInt(max);
TestingUtil.sleepThread(l);
}
protected void tearDown()
{
TransactionManager mgr = DummyTransactionManager.getInstance();
try
{
if (mgr.getTransaction() != null)
{
mgr.rollback();
}
}
catch (SystemException e)
{
// do nothing
}
}
protected Interceptor getAlteredInterceptorChain(Interceptor newLast, CacheSPI spi, boolean replicated)
{
Interceptor ici = new InvocationContextInterceptor();
ici.setCache(spi);
Interceptor txInterceptor = new TxInterceptor();
txInterceptor.setCache(spi);
Interceptor replicationInterceptor = new OptimisticReplicationInterceptor();
replicationInterceptor.setCache(spi);
Interceptor createInterceptor = new OptimisticCreateIfNotExistsInterceptor();
createInterceptor.setCache(spi);
Interceptor nodeInterceptor = new OptimisticNodeInterceptor();
nodeInterceptor.setCache(spi);
ici.setNext(txInterceptor);
if (replicated)
{
txInterceptor.setNext(replicationInterceptor);
replicationInterceptor.setNext(createInterceptor);
}
else
{
txInterceptor.setNext(createInterceptor);
}
createInterceptor.setNext(nodeInterceptor);
nodeInterceptor.setNext(newLast);
return ici;
}
public abstract class ExceptionThread extends Thread
{
protected Exception exception;
public void setException(Exception e)
{
exception = e;
}
public Exception getException()
{
return exception;
}
}
protected List injectDataVersion(List modifications)
{
List newList = new ArrayList();
Iterator mi = modifications.iterator();
while (mi.hasNext())
{
MethodCall c = (MethodCall) mi.next();
Object[] oa = c.getArgs();
Object[] na = new Object[oa.length + 1];
System.out.println("*** " + oa.length);
for (int i = 0; i < oa.length; i++) na[i] = oa[i];
na[oa.length] = new DefaultDataVersion();
newList.add(MethodCallFactory.create(MethodDeclarations.getVersionedMethod(c.getMethodId()), na));
}
return newList;
}
}
1.1 date: 2007/01/13 15:55:11; author: bwang; state: Exp;JBossCache/tests/functional/org/jboss/cache/pojo/optimistic/CachedListTest.java
Index: CachedListTest.java
===================================================================
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.cache.pojo.optimistic;
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.PojoCacheFactory;
import org.jboss.cache.pojo.test.Address;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* List interface testing.
*
* @author Ben Wang
*/
public class CachedListTest extends AbstractOptimisticTestCase
{
Log log = LogFactory.getLog(CachedListTest.class);
PojoCache cache_;
List languages;
List languages2;
public CachedListTest(String name)
{
super(name);
}
protected void setUp() throws Exception
{
super.setUp();
cache_ = createCache();
// cache_ = createPessimisticCache();
log.info("setUp() ....");
}
protected void tearDown()
{
super.tearDown();
cache_.stop();
}
public void testAddAndRemoveIndex() throws Throwable
{
stage();
languages.add(1, "Taiwanese");
assertEquals("Languages size ", 4, languages.size());
assertEquals("Language ", (Object) "Taiwanese", (Object) languages.get(1));
languages.remove(2);
assertEquals("Languages size ", 3, languages.size());
assertEquals("Language ", (Object) "English", (Object) languages.get(2));
languages.add("Mandarin");
assertEquals("Languages size ", 4, languages.size());
languages.remove("Mandarin");
assertEquals("Languages size ", 3, languages.size());
}
protected void stage() throws Throwable
{
languages = new ArrayList();
languages.add("English");
languages.add("French");
languages.add("English");
cache_.attach("/person/test6", languages);
languages = (List) cache_.find("/person/test6");
int size = languages.size();
assertEquals("Size of list ", 3, size);
languages2 = new ArrayList();
languages2.addAll(languages);
assertEquals("New ArrayList().addAll(CachedList)", languages, languages2);
}
public void testAddAllAndClear() throws Throwable
{
stage();
List list = new ArrayList();
list.add("Taiwanese");
list.add("Madarin");
assertTrue("Language is Taiwanese ", list.contains("Taiwanese"));
languages.addAll(list);
assertEquals("Languages size ", 5, languages.size());
languages.removeAll(list);
assertEquals("Languages size ", 3, languages.size());
assertEquals("Index of French ", 1, languages.indexOf("French"));
languages.clear();
assertEquals("Languages size ", 0, languages.size());
assertTrue("Languages empty ", languages.isEmpty());
}
public void testEquals() throws Throwable
{
stage();
List list = (List) cache_.find("/person/test6");
assertTrue("List should be the same ", list.equals(languages));
list = new ArrayList();
list.add("German");
list.add("test");
list.add("English");
assertFalse("List should not be the same ", languages.equals(list));
assertFalse("List should not be the same ", list.equals(languages));
}
public void testIterator() throws Throwable
{
languages = new ArrayList();
Iterator it0 = languages.iterator();
assertFalse("Iterator should be empty ", it0.hasNext());
stage();
Iterator it = languages.iterator();
Iterator it2 = languages2.iterator();
int counter = 0;
while (it.hasNext())
{
counter++;
assertEquals(it.next(), it2.next());
it.remove();
it2.remove();
}
assertEquals("Size should be ", 3, counter);
assertEquals("Skills should be empty ", 0, languages.size());
}
public void testListIterator() throws Throwable
{
languages = new ArrayList();
ListIterator it0 = languages.listIterator();
assertFalse("Iterator should be empty ", it0.hasNext());
assertFalse("Iterator should be empty ", it0.hasPrevious());
stage();
ListIterator li = languages.listIterator();
ListIterator li2 = languages2.listIterator();
assertFalse("LI has no previous element ", li.hasPrevious());
assertFalse("LI2 has no previous element ", li2.hasPrevious());
assertTrue("LI has next element ", li.hasNext());
assertTrue("LI2 has next element ", li2.hasNext());
assertEquals(li.next(), li2.next());
assertEquals("Index is ", 1, li.nextIndex());
assertEquals("Index is ", 1, li2.nextIndex());
assertEquals("Index is ", 0, li.previousIndex());
assertEquals("Index is ", 0, li2.previousIndex());
assertEquals(li.next(), li2.next());
assertEquals(li.next(), li2.next()); // the end
try
{
li.next();
fail("Should throw an exception here ");
}
catch (NoSuchElementException ex)
{
;
}
try
{
li2.next();
fail("Should throw an exception here ");
}
catch (NoSuchElementException ex)
{
;
}
assertEquals("Index is ", 3, li.nextIndex());
assertEquals("Index is ", 3, li2.nextIndex());
assertEquals("Index is ", 2, li.previousIndex());
assertEquals("Index is ", 2, li2.previousIndex());
li.previous();
li2.previous();
assertEquals("Index is ", 2, li.nextIndex());
assertEquals("Index is ", 2, li2.nextIndex());
assertEquals("Index is ", 1, li.previousIndex());
assertEquals("Index is ", 1, li2.previousIndex());
li.previous();
li2.previous();
li.previous();
li2.previous();
try
{
li.previous();
fail("Should throw an exception here ");
}
catch (NoSuchElementException ex)
{
;
}
try
{
li2.previous();
fail("Should throw an exception here ");
}
catch (NoSuchElementException ex)
{
;
}
try
{
assertEquals(li.next(), li2.next());
li.remove();
li2.remove();
}
catch (Exception e)
{
fail("ListIterator.remove failed" + e);
}
try
{
assertEquals(li.next(), li2.next());
li.remove();
li2.remove();
}
catch (Exception e)
{
fail("ListIterator.remove failed" + e);
}
try
{
assertEquals(li.next(), li2.next());
assertEquals("ListIterator.remove test problem with nextIndex, cache next index=" + li.nextIndex() +
", jdk next index=" + li2.nextIndex() + "cache list size = " + languages.size() + ", jdk list size = " + languages.size(),
li.nextIndex(), li2.nextIndex());
li2.set("German");
li.set("German");
String s1 = (String) li.previous();
String s2 = (String) li2.previous();
assertEquals(s1, s2);
assertEquals(s2, "German");
}
catch (Exception e)
{
fail("ListIterator.remove failed" + e + ", cache list size = " + languages.size() + ", jdk list size = " + languages.size());
}
try
{
assertEquals(li.next(), li2.next());
li2.add("Vulcan");
li.add("Vulcan");
String s1 = (String) li.previous();
String s2 = (String) li2.previous();
assertEquals(s1, s2);
assertEquals(s2, "Vulcan");
}
catch (Exception e)
{
fail("ListIterator.add failed" + e + ", cache list size = " + languages.size() + ", jdk list size = " + languages.size());
}
}
public void testAttachAndDetach() throws Exception
{
List list = new ArrayList();
list.add("English");
list.add("French");
list.add("Taiwanese");
cache_.attach("/test", list); // attach
list = (List) cache_.find("/test");
assertEquals("Size ", 3, list.size());
list = (List) cache_.detach("/test");
assertEquals("Size ", 3, list.size());
System.out.println("**** End of cache content **** ");
list.remove(2);
list.add("Hoklo");
assertEquals("Size ", 3, list.size());
assertEquals("Content ", "Hoklo", list.get(2));
// Try to re-attach
cache_.attach("/test", list);
list.remove(2);
assertEquals("Size ", 2, list.size());
}
public void testPojoAttachAndDetach() throws Exception
{
Address add1 = new Address();
add1.setCity("San Jose");
add1.setZip(95123);
Address add2 = new Address();
add2.setCity("Sunnyvale");
add2.setZip(94086);
Address add3 = new Address();
add3.setCity("Santa Clara");
add3.setZip(951131);
List list = new ArrayList();
list.add(add1);
list.add(add2);
list.add(add3);
cache_.attach("/test", list); // attach
list = (List) cache_.find("/test");
assertEquals("Size ", 3, list.size());
list = (List) cache_.detach("/test");
assertEquals("Size ", 3, list.size());
System.out.println("**** End of cache content **** ");
list.remove(2);
list.add(add2);
assertEquals("Size ", 3, list.size());
assertEquals("Content ", add2, list.get(2));
// Try to re-attach
cache_.attach("/test", list);
list.remove(2);
assertEquals("Size ", 2, list.size());
}
public void testEqual1() throws Exception
{
List list1 = new ArrayList();
list1.add("ID1");
list1.add("ID2");
cache_.attach("test1", list1);
list1 = (List)cache_.find("test1");
List list2 = new ArrayList();
list2.add("ID1");
list2.add("ID2");
cache_.attach("test2", list2);
list2 = (List)cache_.find("test2");
List list3 = new ArrayList();
list3.add("ID2");
list3.add("ID1");
cache_.attach("test3", list3);
list3 = (List)cache_.find("test3");
assertEquals("List should be equal: ", list1, list1);
assertTrue("List should be equal: ", list1.equals(list1));
assertTrue("List should be equal: ", list1.equals(list2));
assertFalse("List should not be equal: ", list1.equals(list3));
}
public void testEqual2() throws Exception
{
List list1 = new ArrayList();
cache_.attach("test1", list1);
list1 = (List)cache_.find("test1");
list1.add("ID1");
list1.add("ID2");
List list2 = new ArrayList();
cache_.attach("test2", list2);
list2 = (List)cache_.find("test2");
list2.add("ID1");
list2.add("ID2");
List list3 = new ArrayList();
cache_.attach("test3", list3);
list3 = (List)cache_.find("test3");
list3.add("ID2");
list3.add("ID1");
assertEquals("List should be equal: ", list1, list1);
assertTrue("List should be equal: ", list1.equals(list1));
assertTrue("List should be equal: ", list1.equals(list2));
assertFalse("List should not be equal: ", list1.equals(list3));
}
public static Test suite() throws Exception
{
return new TestSuite(CachedListTest.class);
}
public static void main(String[] args) throws Exception
{
junit.textui.TestRunner.run(suite());
}
}
More information about the jboss-cvs-commits
mailing list