001 package org.crsh.util;
002
003 import javax.servlet.ServletContext;
004 import java.util.AbstractMap;
005 import java.util.AbstractSet;
006 import java.util.Enumeration;
007 import java.util.Iterator;
008 import java.util.Set;
009
010 /** @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a> */
011 public class ServletContextMap extends AbstractMap<String, Object> {
012
013 /** . */
014 private final ServletContext context;
015
016 public ServletContextMap(ServletContext context) {
017 this.context = context;
018 }
019
020 @Override
021 public boolean containsKey(Object key) {
022 return key instanceof String && context.getAttribute((String)key) != null;
023 }
024
025 @Override
026 public Object get(Object key) {
027 if (key instanceof String) {
028 return context.getAttribute((String)key);
029 } else {
030 return null;
031 }
032 }
033
034 private AbstractSet<Entry<String, Object>> entries = new AbstractSet<Entry<String, Object>>() {
035
036 @Override
037 public Iterator<Entry<String, Object>> iterator() {
038 final Enumeration<String> names = context.getAttributeNames();
039 return new Iterator<Entry<String, Object>>() {
040 public boolean hasNext() {
041 return names.hasMoreElements();
042 }
043
044 public Entry<String, Object> next() {
045 final String name = names.nextElement();
046 return new Entry<String, Object>() {
047 public String getKey() {
048 return name;
049 }
050
051 public Object getValue() {
052 return context.getAttribute(name);
053 }
054
055 public Object setValue(Object value) {
056 throw new UnsupportedOperationException();
057 }
058 };
059 }
060
061 public void remove() {
062 throw new UnsupportedOperationException();
063 }
064 };
065 }
066
067 @Override
068 public int size() {
069 int size = 0;
070 for (Enumeration<String> names = context.getAttributeNames();names.hasMoreElements();) {
071 size++;
072 }
073 return size;
074 }
075 };
076
077
078 @Override
079 public Set<Entry<String, Object>> entrySet() {
080 return entries;
081 }
082 }