package org.jboss.cache.aop;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.util.NestedRuntimeException;
import java.util.AbstractList;
import java.util.Map;
public class CachedList extends AbstractList
{
protected TreeCacheAop cache;
protected Fqn fqn;
CachedList(TreeCacheAop cache, Fqn fqn)
{
this.cache = cache;
this.fqn = fqn;
}
protected Node getNode()
{
try {
return cache.get(fqn);
} catch (Exception e) {
throw new NestedRuntimeException(e);
}
}
public Object get(int index)
{
try {
return cache.getObject(new Fqn(fqn, new Integer(index)));
} catch (Exception e) {
throw new NestedRuntimeException(e);
}
}
public int size()
{
Map children = getNode().getChildren();
return children == null ? 0 : children.size();
}
public Object set(int index, Object element)
{
try {
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException();
Object oldValue = get(index);
return cache.putObject(new Fqn(fqn, new Integer(index)), element);
} catch (Exception e) {
throw new NestedRuntimeException(e);
}
}
public void add(int index, Object element)
{
try {
if (index < 0 || index > size())
throw new IndexOutOfBoundsException();
for (int i = size(); i > index; i--) {
Object obj = cache.removeObject(new Fqn(fqn, new Integer(i - 1)));
cache.putObject(new Fqn(fqn, new Integer(i)), obj);
}
cache.putObject(new Fqn(fqn, new Integer(index)), element);
} catch (Exception e) {
throw new NestedRuntimeException(e);
}
}
public boolean remove(Object o)
{
return super.remove(o);
}
public Object remove(int index)
{
try {
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException();
Object result = cache.removeObject(new Fqn(fqn, new Integer(index)));
int size = size() - 1;
for (int i = index; i < size; i++) {
Object obj = cache.removeObject(new Fqn(fqn, new Integer(i + 1)));
cache.putObject(new Fqn(fqn, new Integer(i)), obj);
}
return result;
} catch (Exception e) {
throw new NestedRuntimeException(e);
}
}
}