aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/main/java/org/apache/velocity/util/DuckType.java
blob: 8fbc559b64093030183261b1c90959f5786e1f38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package org.apache.velocity.util;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import static org.apache.velocity.runtime.parser.node.MathUtils.isZero;

/**
 * Support for getAs<java.lang.reflect.Type>() convention for rendering (String), evaluating (Boolean)
 * or doing math with (Number) references.
 *
 * @author Nathan Bubna
 * @since 2.0
 */
public class DuckType
{
    protected enum Types
    {
        STRING("getAsString"),
        NUMBER("getAsNumber"),
        BOOLEAN("getAsBoolean"),
        EMPTY("isEmpty"),
        LENGTH("length"),
        SIZE("size");

        final String name;
        final Map<Class,Object> cache = new HashMap();

        Types(String name)
        {
            this.name = name;
        }

        void set(Class c, Object o)
        {
            cache.put(c, o);
        }

        Object get(Class c)
        {
            return cache.get(c);
        }
    }

    protected static final Object NO_METHOD = new Object();

    /**
     * Clears the internal cache of all the underlying Types.
     */
    public static void clearCache()
    {
        for(Types type : Types.values())
        {
            type.cache.clear();
        }
    }
        
    public static String asString(Object value)
    {
        return asString(value, true);
    }

    public static String asString(Object value, boolean coerceType)
    {
        if (value == null)
        {
            return null;
        }
        if (value instanceof String)
        {
            return (String)value;
        }
        if (coerceType && value.getClass().isArray())
        {
            // nicify arrays string representation
            StringBuilder builder = new StringBuilder();
            builder.append('[');
            int len = Array.getLength(value);
            for (int i = 0; i < len; ++i)
            {
                if (i > 0) builder.append(", ");
                builder.append(asString(Array.get(value, i)));
            }
            builder.append(']');
            return builder.toString();
        }
        Object got = get(value, Types.STRING);
        if (got == NO_METHOD)
        {
            return coerceType ? value.toString() : null;
        }
        return (String)got;
    }

    public static boolean asNull(Object value)
    {
        return value == null ||
            get(value, Types.STRING) == null ||
            get(value, Types.NUMBER) == null;
    }

    public static boolean asBoolean(Object value, boolean coerceType)
    {
        if (value == null)
        {
            return false;
        }
        if (value instanceof Boolean)
        {
            return (Boolean) value;
        }
        Object got = get(value, Types.BOOLEAN);
        if (got != NO_METHOD)
        {
            return (Boolean) got;
        }
        if (coerceType)
        {
            return !asEmpty(value);
        }
        return true;
    }

    // see VELOCITY-692 for discussion about empty values
    public static boolean asEmpty(Object value)
    {
        // empty variable
        if (value == null)
        {
            return true;
        }

        // empty array
        if (value.getClass().isArray())
        {
            return Array.getLength(value) == 0;// [] is false
        }

        // isEmpty() for object / string
        Object isEmpty = get(value, Types.EMPTY);
        if (isEmpty != NO_METHOD)
        {
            return (Boolean)isEmpty;
        }

        // isEmpty() for object / other char sequences
        Object length = get(value, Types.LENGTH);
        if (length != NO_METHOD && length instanceof Number)
        {
            return isZero((Number)length);
        }

        // size() object / collection
        Object size = get(value, Types.SIZE);
        if (size != NO_METHOD && size instanceof Number)
        {
            return isZero((Number)size);
        }

        // zero numbers are false
        if (value instanceof Number)
        {
            return isZero((Number)value);
        }

        // null getAsString()
        Object asString = get(value, Types.STRING);
        if (asString == null)
        {
            return true;// duck null
        }
        // empty getAsString()
        else if (asString != NO_METHOD)
        {
            return ((String)asString).length() == 0;
        }

        // null getAsNumber()
        Object asNumber = get(value, Types.NUMBER);
        if (asNumber == null)
        {
            return true;
        }
        // zero numbers are false
        else if (asNumber != NO_METHOD && asNumber instanceof Number)
        {
            return isZero((Number)asNumber);
        }

        return false;
    }

    public static Number asNumber(Object value)
    {
        return asNumber(value, true);
    }

    public static Number asNumber(Object value, boolean coerceType)
    {
        if (value == null)
        {
            return null;
        }
        if (value instanceof Number)
        {
            return (Number)value;
        }
        Object got = get(value, Types.NUMBER);
        if (got != NO_METHOD)
        {
            return (Number)got;
        }
        if (coerceType)
        {
            String string = asString(value);// coerce to string
            if (string != null)
            {
                return new BigDecimal(string);
            }
        }
        return null;
    }

    protected static Object get(Object value, Types type)
    {
        try
        {
            // check cache
            Class c = value.getClass();
            Object cached = type.get(c);
            if (cached == NO_METHOD)
            {
                return cached;
            }
            if (cached != null)
            {
                return ((Method)cached).invoke(value);
            }
            // ok, search the class
            Method method = findMethod(c, type);
            if (method == null)
            {
                type.set(c, NO_METHOD);
                return NO_METHOD;
            }
            type.set(c, method);
            return method.invoke(value);
        }
        catch (RuntimeException re)
        {
            throw re;
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);// no checked exceptions, please
        }
    }

    protected static Method findMethod(Class c, Types type)
    {
        if (c == null || c == Object.class)
        {
            return null;
        }
        Method m = getMethod(c, type.name);
        if (m != null)
        {
            return m;
        }
        for (Class i : c.getInterfaces())
        {
            m = findMethod(i, type);
            if (m != null)
            {
                return m;
            }
        }
        m = findMethod(c.getSuperclass(), type);
        if (m != null)
        {
            return m;
        }
        return null;
    }

    private static Method getMethod(Class c, String name)
    {
        if (Modifier.isPublic(c.getModifiers()))
        {
            try
            {
                Method m = c.getDeclaredMethod(name);
                if (Modifier.isPublic(m.getModifiers()))
                {
                    return m;
                }
            }
            catch (NoSuchMethodException nsme) {}
        }
        return null;
    }

}