1 52 53 package freemarker.template; 54 55 import java.lang.reflect.Array ; 56 import java.util.ArrayList ; 57 import java.util.Collection ; 58 import java.util.Iterator ; 59 import java.util.Map ; 60 import freemarker.ext.dom.NodeModel; 61 62 68 public class DefaultObjectWrapper extends freemarker.ext.beans.BeansWrapper { 69 70 static final DefaultObjectWrapper instance = new DefaultObjectWrapper(); 71 72 static private Class W3C_DOM_NODE_CLASS, 73 JYTHON_OBJ_CLASS; 74 75 static private ObjectWrapper JYTHON_WRAPPER; 76 77 static { 78 try { 79 W3C_DOM_NODE_CLASS = Class.forName("org.w3c.dom.Node"); 80 } catch (Exception e) {} 81 try { 82 JYTHON_OBJ_CLASS = Class.forName("org.python.core.PyObject"); 83 JYTHON_WRAPPER = freemarker.ext.jython.JythonWrapper.INSTANCE; 84 } catch (Exception e) {} 85 } 86 87 88 public TemplateModel wrap(Object obj) throws TemplateModelException { 89 if (obj == null) { 90 return super.wrap(null); 91 } 92 if (obj instanceof TemplateModel) { 93 return (TemplateModel) obj; 94 } 95 if (obj instanceof String ) { 96 return new SimpleScalar((String ) obj); 97 } 98 if (obj instanceof Number ) { 99 return new SimpleNumber((Number ) obj); 100 } 101 if (obj instanceof java.util.Date ) { 102 if(obj instanceof java.sql.Date ) { 103 return new SimpleDate((java.sql.Date ) obj); 104 } 105 if(obj instanceof java.sql.Time ) { 106 return new SimpleDate((java.sql.Time ) obj); 107 } 108 if(obj instanceof java.sql.Timestamp ) { 109 return new SimpleDate((java.sql.Timestamp ) obj); 110 } 111 return new SimpleDate((java.util.Date ) obj, getDefaultDateType()); 112 } 113 if (obj.getClass().isArray()) { 114 obj = convertArray(obj); 115 } 116 if (obj instanceof Collection ) { 117 return new SimpleSequence((Collection ) obj, this); 118 } 119 if (obj instanceof Map ) { 120 return new SimpleHash((Map ) obj, this); 121 } 122 if (obj instanceof Boolean ) { 123 return obj.equals(Boolean.TRUE) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE; 124 } 125 if (obj instanceof Iterator ) { 126 return new SimpleCollection((Iterator ) obj, this); 127 } 128 return handleUnknownType(obj); 129 } 130 131 132 136 protected TemplateModel handleUnknownType(Object obj) throws TemplateModelException { 137 if ((W3C_DOM_NODE_CLASS != null && W3C_DOM_NODE_CLASS.isInstance(obj))) 138 { 139 return wrapDomNode(obj); 140 } 141 if (JYTHON_WRAPPER != null && JYTHON_OBJ_CLASS.isInstance(obj)) { 142 return JYTHON_WRAPPER.wrap(obj); 143 } 144 return super.wrap(obj); 145 } 146 147 148 public TemplateModel wrapDomNode(Object obj) { 149 return NodeModel.wrap((org.w3c.dom.Node ) obj); 150 } 151 152 155 protected Object convertArray(Object arr) { 156 final int size = Array.getLength(arr); 157 ArrayList list = new ArrayList (size); 158 for (int i=0;i<size; i++) { 159 list.add(Array.get(arr, i)); 160 } 161 return list; 162 } 163 } 164 | Popular Tags |