1 52 53 package freemarker.core; 54 55 import freemarker.template.Template; 56 57 64 public class CustomAttribute 65 { 66 70 public static final int SCOPE_ENVIRONMENT = 0; 71 72 76 public static final int SCOPE_TEMPLATE = 1; 77 78 82 public static final int SCOPE_CONFIGURATION = 2; 83 84 private final Object key = new Object (); 88 private final int scope; 89 90 94 public CustomAttribute(int scope) { 95 if(scope != SCOPE_ENVIRONMENT && 96 scope != SCOPE_TEMPLATE && 97 scope != SCOPE_CONFIGURATION) { 98 throw new IllegalArgumentException (); 99 } 100 this.scope = scope; 101 } 102 103 109 protected Object create() { 110 return null; 111 } 112 113 119 public final Object get() { 120 return getScopeConfigurable().getCustomAttribute(key, this); 121 } 122 123 130 public final Object get(Template t) { 131 if(scope != SCOPE_TEMPLATE) { 132 throw new UnsupportedOperationException ("This is not a template-scope attribute"); 133 } 134 return ((Configurable)t).getCustomAttribute(key, this); 135 } 136 137 144 public final void set(Object value) { 145 getScopeConfigurable().setCustomAttribute(key, value); 146 } 147 148 157 public final void set(Object value, Template t) { 158 if(scope != SCOPE_TEMPLATE) { 159 throw new UnsupportedOperationException ("This is not a template-scope attribute"); 160 } 161 ((Configurable)t).setCustomAttribute(key, value); 162 } 163 164 private Configurable getScopeConfigurable() { 165 Configurable c = Environment.getCurrentEnvironment(); 166 if(c == null) { 167 throw new IllegalStateException ("No current environment"); 168 } 169 switch(scope) { 170 case SCOPE_ENVIRONMENT: { 171 return c; 172 } 173 case SCOPE_TEMPLATE: { 174 return c.getParent(); 175 } 176 case SCOPE_CONFIGURATION: { 177 return c.getParent().getParent(); 178 } 179 default: { 180 throw new Error (); 181 } 182 } 183 } 184 } 185 | Popular Tags |