package org.jboss.cache.eviction;
import org.jboss.cache.TreeCache;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.Map;
public class RegionManager
{
private Logger log_ = Logger.getLogger(RegionManager.class);
public final static int CAPACITY = 200000;
private Map regionMap_ = new HashMap();
private Region[] regions_;
private EvictionPolicy policy_;
final static String DEFAULT_REGION = "/_default_/";
public RegionManager(EvictionPolicy policy)
{
policy_ = policy;
regions_ = null;
}
public Region createRegion(String fqn, EvictionAlgorithm algorithm)
throws RegionNameConflictException
{
if (log_.isDebugEnabled())
{
log_.debug("createRegion(): creating region for fqn- " + fqn);
}
String newFqn = appendFqn(fqn);
checkConflict(newFqn);
Region region = new Region(newFqn, policy_, algorithm);
regionMap_.put(newFqn, region);
return region;
}
public void removeRegion(String fqn)
{
regionMap_.remove(fqn);
}
private String appendFqn(String fqn)
{
if (!fqn.endsWith(TreeCache.SEPARATOR))
return fqn + TreeCache.SEPARATOR;
else
return fqn;
}
public boolean hasRegion(String myFqn)
{
String newFqn = appendFqn(myFqn);
return regionMap_.containsKey(newFqn);
}
public Region getRegion(String myFqn)
{
Region[] regions = getRegions();
String myRFqn = appendFqn(myFqn);
for (int i = (regions.length - 1); i >= 0; i--)
{
String fqn = regions[i].getFqn();
if (myRFqn.startsWith(fqn)) return regions[i];
}
if (log_.isTraceEnabled())
{
log_.trace("getRegion(): not user-specified region found for this fqn- " + myFqn
+ " will use the global default region");
}
return (Region) regionMap_.get(DEFAULT_REGION);
}
public Region[] getRegions()
{
if (regions_ != null && regions_.length == regionMap_.size())
return regions_;
Object[] objs = regionMap_.values().toArray();
Region[] regions = new Region[objs.length];
for (int i = 0; i < objs.length; i++)
{
regions[i] = (Region) objs[i];
}
if (log_.isDebugEnabled())
{
log_.debug("getRegions(): size of region " + regions.length);
}
regions_ = regions;
return regions;
}
public void checkConflict(String myFqn) throws RegionNameConflictException
{
Region[] regions = getRegions();
for (int i = 0; i < regions.length; i++)
{
String fqn = regions[i].getFqn();
if (myFqn.equals(fqn) || myFqn.startsWith(fqn))
{ throw new RegionNameConflictException("RegionManager.checkConflict(): new region fqn "
+ myFqn + " is in conflict with current region fqn- " + fqn);
}
}
}
}