1 52 53 package freemarker.ext.jython; 54 55 import org.python.core.PyException; 56 import org.python.core.PyObject; 57 58 import freemarker.ext.util.ModelFactory; 59 import freemarker.template.ObjectWrapper; 60 import freemarker.template.TemplateCollectionModel; 61 import freemarker.template.TemplateHashModelEx; 62 import freemarker.template.TemplateModel; 63 import freemarker.template.TemplateModelException; 64 65 79 public class JythonHashModel 80 extends 81 JythonModel 82 implements 83 TemplateHashModelEx 84 { 85 private static final String KEYS = "keys"; 86 private static final String KEYSET = "keySet"; 87 private static final String VALUES = "values"; 88 89 static final ModelFactory FACTORY = 90 new ModelFactory() 91 { 92 public TemplateModel create(Object object, ObjectWrapper wrapper) 93 { 94 return new JythonHashModel((PyObject)object, (JythonWrapper)wrapper); 95 } 96 }; 97 98 public JythonHashModel(PyObject object, JythonWrapper wrapper) 99 { 100 super(object, wrapper); 101 } 102 103 106 public int size() throws TemplateModelException 107 { 108 try 109 { 110 return object.__len__(); 111 } 112 catch(PyException e) 113 { 114 throw new TemplateModelException(e); 115 } 116 } 117 118 122 public TemplateCollectionModel keys() throws TemplateModelException 123 { 124 try 125 { 126 PyObject method = object.__findattr__(KEYS); 127 if(method == null) 128 { 129 method = object.__findattr__(KEYSET); 130 } 131 if(method != null) 132 { 133 return (TemplateCollectionModel)wrapper.wrap(method.__call__()); 134 } 135 } 136 catch(PyException e) 137 { 138 throw new TemplateModelException(e); 139 } 140 throw new TemplateModelException("'?keys' is not supported as there is no 'keys' nor 'keySet' attribute on an instance of " + object.__class__.__name__); 141 } 142 143 146 public TemplateCollectionModel values() throws TemplateModelException 147 { 148 try 149 { 150 PyObject method = object.__findattr__(VALUES); 151 if(method != null) 152 { 153 return (TemplateCollectionModel)wrapper.wrap(method.__call__()); 154 } 155 } 156 catch(PyException e) 157 { 158 throw new TemplateModelException(e); 159 } 160 throw new TemplateModelException("'?values' is not supported as there is no 'values' attribute on an instance of " + object.__class__.__name__); 161 } 162 } 163 | Popular Tags |