/*
* Copyright 2004, 2005, 2006 Odysseus Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.odysseus.calyxo.base.access;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import de.odysseus.calyxo.base.util.MapFacade;
/**
* An accessor map is a container for other accessors. It produces a map
* which uses its contained accessors to produce objects. The
* object produced by a contained accessor is cached if that accessor
* states that it is cachable. Otherwise, a new object is served
* by the accessor each time the accessor's key is requested.
*
* @author Christoph Beck
*/
public class AccessorMap implements Accessor {
private Map map = new HashMap();
/**
* This method produces a map. This map implements the
* <code>get(Object)</code> method as follows:
* It gets the accessor stored in the outer class under the specified
* key and uses that accessor to produce the result object.
* For subsequent request of the same key, the object is cached
* if the accessor states that it is cachable.
*
* @see Accessor#isCacheable()
*/
public Object get(final HttpServletRequest request) {
return new MapFacade() {
private Map cache;
public Object get(Object key) {
Accessor accessor = AccessorMap.this.get(key);
if (accessor == null) {
throw new AccessException("No such accessor: " + key);
}
if (accessor.isCacheable()) {
if (cache == null) {
cache = new HashMap();
} else if (cache.containsKey(key)) {
return cache.get(key);
}
Object value = accessor.get(request);
cache.put(key, value);
return value;
} else {
return accessor.get(request);
}
}
};
}
/**
* The produced lookup map may be cached in a containing accessor map.
*/
public boolean isCacheable() {
return true;
}
/**
* Save accessor under specified key
*/
public void put(Object key, Accessor value) {
map.put(key, value);
}
/**
* Get accessor for specified key
*/
public Accessor get(Object key) {
return (Accessor)map.get(key);
}
/**
* Remove accessor
*/
public void remove(Object key) {
map.remove(key);
}
}