Debian Codegraph @

jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONPojoConvertor.java

raw
1 //
2 // ========================================================================
3 // Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.util.ajax;
20
21 import java.lang.reflect.Array;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.lang.reflect.Modifier;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.Locale;
30 import java.util.Map;
31 import java.util.Set;
32
33 import org.eclipse.jetty.util.ajax.JSON.Output;
34 import org.eclipse.jetty.util.log.Log;
35 import org.eclipse.jetty.util.log.Logger;
36
37 /**
38 * Converts POJOs to JSON and vice versa.
39 * The key difference:
40 * - returns the actual object from Convertor.fromJSON (JSONObjectConverter returns a Map)
41 * - the getters/setters are resolved at initialization (JSONObjectConverter resolves it at runtime)
42 * - correctly sets the number fields
43 */
44 public class JSONPojoConvertor implements JSON.Convertor
45 {
46 private static final Logger LOG = Log.getLogger(JSONPojoConvertor.class);
47 public static final Object[] GETTER_ARG = new Object[]{};
48 public static final Object[] NULL_ARG = new Object[]{null};
49 private static final Map<Class<?>, NumberType> __numberTypes = new HashMap<Class<?>, NumberType>();
50
51 public static NumberType getNumberType(Class<?> clazz)
52 {
53 return __numberTypes.get(clazz);
54 }
55
56 protected boolean _fromJSON;
57 protected Class<?> _pojoClass;
58 protected Map<String, Method> _getters = new HashMap<String, Method>();
59 protected Map<String, Setter> _setters = new HashMap<String, Setter>();
60 protected Set<String> _excluded;
61
62 /**
63 * @param pojoClass The class to convert
64 */
65 public JSONPojoConvertor(Class<?> pojoClass)
66 {
67 this(pojoClass, null, true);
68 }
69
70 /**
71 * @param pojoClass The class to convert
72 * @param excluded The fields to exclude
73 */
74 public JSONPojoConvertor(Class<?> pojoClass, String[] excluded)
75 {
76 this(pojoClass, new HashSet<String>(Arrays.asList(excluded)), true);
77 }
78
79 /**
80 * @param pojoClass The class to convert
81 * @param excluded The fields to exclude
82 */
83 public JSONPojoConvertor(Class<?> pojoClass, Set<String> excluded)
84 {
85 this(pojoClass, excluded, true);
86 }
87
88 /**
89 * @param pojoClass The class to convert
90 * @param excluded The fields to exclude
91 * @param fromJSON If true, add a class field to the JSON
92 */
93 public JSONPojoConvertor(Class<?> pojoClass, Set<String> excluded, boolean fromJSON)
94 {
95 _pojoClass = pojoClass;
96 _excluded = excluded;
97 _fromJSON = fromJSON;
98 init();
99 }
100
101 /**
102 * @param pojoClass The class to convert
103 * @param fromJSON If true, add a class field to the JSON
104 */
105 public JSONPojoConvertor(Class<?> pojoClass, boolean fromJSON)
106 {
107 this(pojoClass, null, fromJSON);
108 }
109
110 protected void init()
111 {
112 Method[] methods = _pojoClass.getMethods();
113 for (int i = 0; i < methods.length; i++)
114 {
115 Method m = methods[i];
116 if (!Modifier.isStatic(m.getModifiers()) && m.getDeclaringClass() != Object.class)
117 {
118 String name = m.getName();
119 switch (m.getParameterCount())
120 {
121 case 0:
122
123 if (m.getReturnType() != null)
124 {
125 if (name.startsWith("is") && name.length() > 2)
126 name = name.substring(2, 3).toLowerCase(Locale.ENGLISH) + name.substring(3);
127 else if (name.startsWith("get") && name.length() > 3)
128 name = name.substring(3, 4).toLowerCase(Locale.ENGLISH) + name.substring(4);
129 else
130 break;
131 if (includeField(name, m))
132 addGetter(name, m);
133 }
134 break;
135 case 1:
136 if (name.startsWith("set") && name.length() > 3)
137 {
138 name = name.substring(3, 4).toLowerCase(Locale.ENGLISH) + name.substring(4);
139 if (includeField(name, m))
140 addSetter(name, m);
141 }
142 break;
143 }
144 }
145 }
146 }
147
148 protected void addGetter(String name, Method method)
149 {
150 _getters.put(name, method);
151 }
152
153 protected void addSetter(String name, Method method)
154 {
155 _setters.put(name, new Setter(name, method));
156 }
157
158 protected Setter getSetter(String name)
159 {
160 return _setters.get(name);
161 }
162
163 protected boolean includeField(String name, Method m)
164 {
165 return _excluded == null || !_excluded.contains(name);
166 }
167
168 protected int getExcludedCount()
169 {
170 return _excluded == null ? 0 : _excluded.size();
171 }
172
173 @Override
174 public Object fromJSON(Map object)
175 {
176 Object obj = null;
177 try
178 {
179 obj = _pojoClass.getDeclaredConstructor().newInstance();
180 }
181 catch (Exception e)
182 {
183 // TODO return Map instead?
184 throw new RuntimeException(e);
185 }
186
187 setProps(obj, object);
188 return obj;
189 }
190
191 public int setProps(Object obj, Map<?, ?> props)
192 {
193 int count = 0;
194 for (Iterator<?> iterator = props.entrySet().iterator(); iterator.hasNext(); )
195 {
196 Map.Entry<?, ?> entry = (Map.Entry<?, ?>)iterator.next();
197 Setter setter = getSetter((String)entry.getKey());
198 if (setter != null)
199 {
200 try
201 {
202 setter.invoke(obj, entry.getValue());
203 count++;
204 }
205 catch (Exception e)
206 {
207 // TODO throw exception?
208 LOG.warn(_pojoClass.getName() + "#" + setter.getPropertyName() + " not set from " +
209 (entry.getValue().getClass().getName()) + "=" + entry.getValue().toString());
210 log(e);
211 }
212 }
213 }
214 return count;
215 }
216
217 @Override
218 public void toJSON(Object obj, Output out)
219 {
220 if (_fromJSON)
221 out.addClass(_pojoClass);
222 for (Map.Entry<String, Method> entry : _getters.entrySet())
223 {
224 try
225 {
226 out.add(entry.getKey(), entry.getValue().invoke(obj, GETTER_ARG));
227 }
228 catch (Exception e)
229 {
230 // TODO throw exception?
231 LOG.warn("{} property '{}' excluded. (errors)", _pojoClass.getName(),
232 entry.getKey());
233 log(e);
234 }
235 }
236 }
237
238 protected void log(Throwable t)
239 {
240 LOG.ignore(t);
241 }
242
243 public static class Setter
244 {
245 protected String _propertyName;
246 protected Method _setter;
247 protected NumberType _numberType;
248 protected Class<?> _type;
249 protected Class<?> _componentType;
250
251 public Setter(String propertyName, Method method)
252 {
253 _propertyName = propertyName;
254 _setter = method;
255 _type = method.getParameterTypes()[0];
256 _numberType = __numberTypes.get(_type);
257 if (_numberType == null && _type.isArray())
258 {
259 _componentType = _type.getComponentType();
260 _numberType = __numberTypes.get(_componentType);
261 }
262 }
263
264 public String getPropertyName()
265 {
266 return _propertyName;
267 }
268
269 public Method getMethod()
270 {
271 return _setter;
272 }
273
274 public NumberType getNumberType()
275 {
276 return _numberType;
277 }
278
279 public Class<?> getType()
280 {
281 return _type;
282 }
283
284 public Class<?> getComponentType()
285 {
286 return _componentType;
287 }
288
289 public boolean isPropertyNumber()
290 {
291 return _numberType != null;
292 }
293
294 public void invoke(Object obj, Object value) throws IllegalArgumentException,
295 IllegalAccessException, InvocationTargetException
296 {
297 if (value == null)
298 _setter.invoke(obj, NULL_ARG);
299 else
300 invokeObject(obj, value);
301 }
302
303 protected void invokeObject(Object obj, Object value) throws IllegalArgumentException,
304 IllegalAccessException, InvocationTargetException
305 {
306
307 if (_type.isEnum())
308 {
309 if (value instanceof Enum)
310 _setter.invoke(obj, value);
311 else
312 _setter.invoke(obj, Enum.valueOf((Class<? extends Enum>)_type, value.toString()));
313 }
314 else if (_numberType != null && value instanceof Number)
315 {
316 _setter.invoke(obj, _numberType.getActualValue((Number)value));
317 }
318 else if (Character.TYPE.equals(_type) || Character.class.equals(_type))
319 {
320 _setter.invoke(obj, String.valueOf(value).charAt(0));
321 }
322 else if (_componentType != null && value.getClass().isArray())
323 {
324 if (_numberType == null)
325 {
326 int len = Array.getLength(value);
327 Object array = Array.newInstance(_componentType, len);
328 try
329 {
330 System.arraycopy(value, 0, array, 0, len);
331 }
332 catch (Exception e)
333 {
334 // unusual array with multiple types
335 LOG.ignore(e);
336 _setter.invoke(obj, value);
337 return;
338 }
339 _setter.invoke(obj, array);
340 }
341 else
342 {
343 Object[] old = (Object[])value;
344 Object array = Array.newInstance(_componentType, old.length);
345 try
346 {
347 for (int i = 0; i < old.length; i++)
348 {
349 Array.set(array, i, _numberType.getActualValue((Number)old[i]));
350 }
351 }
352 catch (Exception e)
353 {
354 // unusual array with multiple types
355 LOG.ignore(e);
356 _setter.invoke(obj, value);
357 return;
358 }
359 _setter.invoke(obj, array);
360 }
361 }
362 else
363 _setter.invoke(obj, value);
364 }
365 }
366
367 public interface NumberType
368 {
369 Object getActualValue(Number number);
370 }
371
372 public static final NumberType SHORT = new NumberType()
373 {
374 @Override
375 public Object getActualValue(Number number)
376 {
377 return new Short(number.shortValue());
378 }
379 };
380
381 public static final NumberType INTEGER = new NumberType()
382 {
383 @Override
384 public Object getActualValue(Number number)
385 {
386 return new Integer(number.intValue());
387 }
388 };
389
390 public static final NumberType FLOAT = new NumberType()
391 {
392 @Override
393 public Object getActualValue(Number number)
394 {
395 return new Float(number.floatValue());
396 }
397 };
398
399 public static final NumberType LONG = new NumberType()
400 {
401 @Override
402 public Object getActualValue(Number number)
403 {
404 return number instanceof Long ? number : new Long(number.longValue());
405 }
406 };
407
408 public static final NumberType DOUBLE = new NumberType()
409 {
410 @Override
411 public Object getActualValue(Number number)
412 {
413 return number instanceof Double ? number : new Double(number.doubleValue());
414 }
415 };
416
417 static
418 {
419 __numberTypes.put(Short.class, SHORT);
420 __numberTypes.put(Short.TYPE, SHORT);
421 __numberTypes.put(Integer.class, INTEGER);
422 __numberTypes.put(Integer.TYPE, INTEGER);
423 __numberTypes.put(Long.class, LONG);
424 __numberTypes.put(Long.TYPE, LONG);
425 __numberTypes.put(Float.class, FLOAT);
426 __numberTypes.put(Float.TYPE, FLOAT);
427 __numberTypes.put(Double.class, DOUBLE);
428 __numberTypes.put(Double.TYPE, DOUBLE);
429 }
430 }