1 52 53 package freemarker.template.utility; 54 55 import java.util.ArrayList ; 56 import java.util.HashMap ; 57 58 import freemarker.ext.util.WrapperTemplateModel; 59 import freemarker.template.AdapterTemplateModel; 60 import freemarker.template.TemplateBooleanModel; 61 import freemarker.template.TemplateCollectionModel; 62 import freemarker.template.TemplateDateModel; 63 import freemarker.template.TemplateHashModelEx; 64 import freemarker.template.TemplateModel; 65 import freemarker.template.TemplateModelException; 66 import freemarker.template.TemplateModelIterator; 67 import freemarker.template.TemplateNumberModel; 68 import freemarker.template.TemplateScalarModel; 69 import freemarker.template.TemplateSequenceModel; 70 71 76 public class DeepUnwrap 77 { 78 private static final Class OBJECT_CLASS = Object .class; 79 106 public static Object unwrap(TemplateModel model) throws TemplateModelException { 107 return unwrap(model, false); 108 } 109 110 115 public static Object premissiveUnwrap(TemplateModel model) throws TemplateModelException { 116 return unwrap(model, true); 117 } 118 119 private static Object unwrap(TemplateModel model, boolean permissive) throws TemplateModelException { 120 if(model instanceof AdapterTemplateModel) { 121 return ((AdapterTemplateModel)model).getAdaptedObject(OBJECT_CLASS); 122 } 123 if (model instanceof WrapperTemplateModel) { 124 return ((WrapperTemplateModel)model).getWrappedObject(); 125 } 126 if(model instanceof TemplateScalarModel) { 127 return ((TemplateScalarModel)model).getAsString(); 128 } 129 if(model instanceof TemplateNumberModel) { 130 return ((TemplateNumberModel)model).getAsNumber(); 131 } 132 if(model instanceof TemplateDateModel) { 133 return ((TemplateDateModel)model).getAsDate(); 134 } 135 if(model instanceof TemplateBooleanModel) { 136 return ((TemplateBooleanModel)model).getAsBoolean() ? Boolean.TRUE : Boolean.FALSE; 137 } 138 if(model instanceof TemplateSequenceModel) { 139 TemplateSequenceModel seq = (TemplateSequenceModel)model; 140 ArrayList list = new ArrayList (seq.size()); 141 for(int i = 0; i < seq.size(); ++i) { 142 list.add(unwrap(seq.get(i))); 143 } 144 return list; 145 } 146 if(model instanceof TemplateCollectionModel) { 147 TemplateCollectionModel coll = (TemplateCollectionModel)model; 148 ArrayList list = new ArrayList (); 149 TemplateModelIterator it = coll.iterator(); 150 while(it.hasNext()) { 151 list.add(unwrap(it.next())); 152 } 153 return list; 154 } 155 if(model instanceof TemplateHashModelEx) { 156 TemplateHashModelEx hash = (TemplateHashModelEx)model; 157 HashMap map = new HashMap (); 158 TemplateModelIterator keys = hash.keys().iterator(); 159 while(keys.hasNext()) { 160 String key = (String )unwrap(keys.next()); 161 map.put(key, unwrap(hash.get(key))); 162 } 163 return map; 164 } 165 if (permissive) { 166 return model; 167 } 168 throw new TemplateModelException("Cannot deep-unwrap model of type " + model.getClass().getName()); 169 } 170 } | Popular Tags |