You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JsonBuilderHandler.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * Copyright 2014, The gwtquery team.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.google.gwt.query.vm;
  17. import com.google.gwt.query.client.Function;
  18. import com.google.gwt.query.client.IsProperties;
  19. import com.google.gwt.query.client.Properties;
  20. import com.google.gwt.query.client.builders.JsonBuilder;
  21. import com.google.gwt.query.client.builders.Name;
  22. import com.google.gwt.query.rebind.JsonBuilderGenerator;
  23. import com.google.gwt.query.vm.JsonFactoryJre.JreJsonFunction;
  24. import java.lang.reflect.Array;
  25. import java.lang.reflect.InvocationHandler;
  26. import java.lang.reflect.Method;
  27. import java.lang.reflect.ParameterizedType;
  28. import java.lang.reflect.Type;
  29. import java.util.ArrayList;
  30. import java.util.Collections;
  31. import java.util.Date;
  32. import java.util.HashSet;
  33. import java.util.Hashtable;
  34. import java.util.List;
  35. import elemental.json.Json;
  36. import elemental.json.JsonArray;
  37. import elemental.json.JsonBoolean;
  38. import elemental.json.JsonNull;
  39. import elemental.json.JsonNumber;
  40. import elemental.json.JsonObject;
  41. import elemental.json.JsonString;
  42. import elemental.json.JsonValue;
  43. /**
  44. * Reflection handler for JsonBuilder implementation in JVM.
  45. */
  46. public class JsonBuilderHandler implements InvocationHandler {
  47. static JsonFactoryJre jsonFactory = new JsonFactoryJre();
  48. private JsonObject jsonObject;
  49. public JsonBuilderHandler() {
  50. jsonObject = Json.createObject();
  51. }
  52. public JsonBuilderHandler(JsonObject j) {
  53. jsonObject = j;
  54. }
  55. public JsonBuilderHandler(String payload) throws Throwable {
  56. jsonObject = Json.parse(payload);
  57. }
  58. @SuppressWarnings("unchecked")
  59. private <T> Object jsonArrayToList(JsonArray j, Class<T> ctype, boolean isArray) {
  60. if (j == null) {
  61. return null;
  62. }
  63. List<T> l = new ArrayList<T>();
  64. for (int i = 0; j != null && i < j.length(); i++) {
  65. l.add((T) getValue(j, i, null, null, ctype, null));
  66. }
  67. return l.isEmpty() ? Collections.emptyList() : isArray ? l.toArray((T[]) Array.newInstance(ctype, l.size())) : l;
  68. }
  69. private Double toDouble(String attr, JsonArray arr, int idx, JsonObject obj) {
  70. try {
  71. return obj != null ? obj.getNumber(attr) : arr.getNumber(idx);
  72. } catch (Exception e) {
  73. return Double.valueOf(0d);
  74. }
  75. }
  76. private Object getValue(JsonArray arr, int idx, JsonObject obj, String attr, Class<?> clz,
  77. Method method) {
  78. if (clz.equals(Boolean.class) || clz == Boolean.TYPE) {
  79. try {
  80. return obj != null ? obj.getBoolean(attr) : arr.getBoolean(idx);
  81. } catch (Exception e) {
  82. return Boolean.FALSE;
  83. }
  84. } else if (clz.equals(Date.class)) {
  85. return new Date((long) (obj != null ? obj.getNumber(attr) : arr.getNumber(idx)));
  86. } else if (clz.equals(Byte.class) || clz == Byte.TYPE) {
  87. return toDouble(attr, arr, idx, obj).byteValue();
  88. } else if (clz.equals(Short.class) || clz == Short.TYPE) {
  89. return toDouble(attr, arr, idx, obj).shortValue();
  90. } else if (clz.equals(Integer.class) || clz == Integer.TYPE) {
  91. return toDouble(attr, arr, idx, obj).intValue();
  92. } else if (clz.equals(Double.class) || clz == Double.TYPE) {
  93. return toDouble(attr, arr, idx, obj);
  94. } else if (clz.equals(Float.class) || clz == Float.TYPE) {
  95. return toDouble(attr, arr, idx, obj).floatValue();
  96. } else if (clz.equals(Long.class) || clz == Long.TYPE) {
  97. return toDouble(attr, arr, idx, obj).longValue();
  98. }
  99. Object ret = obj != null ? obj.get(attr) : arr.get(idx);
  100. if (ret instanceof JreJsonFunction || clz.equals(Function.class)) {
  101. return ret != null && ret instanceof JreJsonFunction ? ((JreJsonFunction) ret).getFunction()
  102. : null;
  103. } else if (ret instanceof JsonNull) {
  104. return null;
  105. } else if (ret instanceof JsonString) {
  106. return ((JsonString) ret).asString();
  107. } else if (ret instanceof JsonBoolean) {
  108. return ((JsonBoolean) ret).asBoolean();
  109. } else if (ret instanceof JsonNumber) {
  110. return toDouble(attr, arr, idx, obj);
  111. } else if (ret instanceof JsonArray || clz.isArray() || clz.equals(List.class)) {
  112. Class<?> ctype = Object.class;
  113. if (clz.isArray()) {
  114. ctype = clz.getComponentType();
  115. } else {
  116. Type returnType = method.getGenericReturnType();
  117. if (returnType instanceof ParameterizedType) {
  118. ctype = (Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[0];
  119. }
  120. }
  121. return jsonArrayToList(obj.getArray(attr), ctype, clz.isArray());
  122. } else if (ret instanceof JsonObject) {
  123. if (clz == Object.class) {
  124. return jsonFactory.createBinder((JsonObject) ret);
  125. } else if (IsProperties.class.isAssignableFrom(clz) && !clz.isAssignableFrom(ret.getClass())) {
  126. return jsonFactory.create(clz, (JsonObject) ret);
  127. }
  128. }
  129. return ret;
  130. }
  131. private <T> JsonArray listToJsonArray(Object... l) throws Throwable {
  132. JsonArray ret = Json.createArray();
  133. for (Object o : l) {
  134. setValue(ret, null, null, o);
  135. }
  136. return ret;
  137. }
  138. private Object setValue(JsonArray jsArr, JsonObject jsObj, String attr, Object val) {
  139. if (val == null) {
  140. return Json.createNull();
  141. }
  142. try {
  143. Class<?> valClaz = JsonValue.class;
  144. if (val instanceof Number) {
  145. val = ((Number) val).doubleValue();
  146. valClaz = Double.TYPE;
  147. } else if (val instanceof Boolean) {
  148. valClaz = Boolean.TYPE;
  149. } else if (val instanceof Date) {
  150. val = ((Date) val).getTime();
  151. valClaz = Double.TYPE;
  152. } else if (val instanceof String) {
  153. valClaz = String.class;
  154. } else if (val instanceof IsProperties) {
  155. val = ((IsProperties) val).getDataImpl();
  156. } else if (val.getClass().isArray() || val instanceof List) {
  157. val =
  158. listToJsonArray(val.getClass().isArray() ? (Object[]) val : ((List<?>) val).toArray());
  159. } else if (val instanceof Function) {
  160. val = new JreJsonFunction((Function) val);
  161. }
  162. if (jsObj != null) {
  163. Method mth = jsObj.getClass().getMethod("put", String.class, valClaz);
  164. mth.invoke(jsObj, new Object[] {attr, val});
  165. return jsObj;
  166. } else {
  167. Method mth = jsArr.getClass().getMethod("set", Integer.TYPE, valClaz);
  168. mth.invoke(jsArr, new Object[] {new Integer(jsArr.length()), val});
  169. return jsArr;
  170. }
  171. } catch (Throwable e) {
  172. e.printStackTrace();
  173. }
  174. return null;
  175. }
  176. @Override
  177. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  178. String mname = method.getName();
  179. Class<?>[] classes = method.getParameterTypes();
  180. int largs = classes.length;
  181. Name name = method.getAnnotation(Name.class);
  182. String attr = name != null ? name.value() : methodName2AttrName(mname);
  183. if ("getFieldNames".equals(mname)) {
  184. return jsonObject.keys();
  185. } else if ("as".equals(mname)) {
  186. @SuppressWarnings("unchecked")
  187. Class<? extends JsonBuilder> clz = (Class<? extends JsonBuilder>) args[0];
  188. return jsonFactory.create(clz, jsonObject);
  189. } else if ("getJsonName".equals(mname)) {
  190. return JsonBuilderGenerator.classNameToJsonName(getDataBindingClassName(proxy.getClass()));
  191. } else if (mname.matches("getProperties|getDataImpl")) {
  192. return jsonObject;
  193. } else if (largs > 0 && ("parse".equals(mname) || "load".equals(mname))) {
  194. String json = String.valueOf(args[0]);
  195. if (largs > 1 && Boolean.TRUE.equals(args[1])) {
  196. json = Properties.wrapPropertiesString(json);
  197. }
  198. jsonObject = Json.parse(json);
  199. } else if ("strip".equals(mname)) {
  200. stripProxy((JsonBuilder) proxy);
  201. } else if (mname.matches("toString")) {
  202. return jsonObject.toString();
  203. } else if (mname.matches("toJsonWithName")) {
  204. String jsonName =
  205. JsonBuilderGenerator.classNameToJsonName(getDataBindingClassName(proxy.getClass()));
  206. return "{\"" + jsonName + "\":" + jsonObject.toString() + "}";
  207. } else if (mname.matches("toJson")) {
  208. return jsonObject.toString();
  209. } else if ("toQueryString".equals(mname)) {
  210. return param(jsonObject);
  211. } else if (largs == 1 && mname.equals("get")) {
  212. Class<?> ret = method.getReturnType();
  213. attr = String.valueOf(args[0]);
  214. return getValue(null, 0, jsonObject, attr, ret, method);
  215. } else if (largs == 0 || mname.startsWith("get")) {
  216. Class<?> ret = method.getReturnType();
  217. return getValue(null, 0, jsonObject, attr, ret, method);
  218. } else if (largs == 2 && mname.equals("set")) {
  219. setValue(null, jsonObject, String.valueOf(args[0]), args[1]);
  220. return proxy;
  221. } else if (largs == 1 || mname.startsWith("set")) {
  222. setValue(null, jsonObject, attr, args[0]);
  223. return proxy;
  224. }
  225. return null;
  226. }
  227. public String methodName2AttrName(String s) {
  228. return deCapitalize(s.replaceFirst("^[gs]et", ""));
  229. }
  230. private String deCapitalize(String s) {
  231. return s != null && s.length() > 0 ? s.substring(0, 1).toLowerCase() + s.substring(1) : s;
  232. }
  233. /*
  234. * This method removes all the json which is not mapped into a
  235. * method inside the JsonBuilder Object.
  236. * Also if the proxy contains another JsonBuilder in their methods
  237. * the method strip() is called.
  238. */
  239. private void stripProxy(JsonBuilder proxy) throws Throwable {
  240. Class<?> type = proxy.getClass().getInterfaces()[0];
  241. HashSet<String> validAttrs = getAttributeNames(type.getMethods());
  242. Hashtable<String, Method> ispropertyGetters = getJsonBuilders(type.getMethods());
  243. for (String key : jsonObject.keys()) {
  244. String name = methodName2AttrName(key);
  245. if (!validAttrs.contains(name)) {
  246. jsonObject.remove(key);
  247. continue;
  248. }
  249. Method ispropertyGetter = ispropertyGetters.get(name);
  250. if (ispropertyGetter != null) {
  251. ((IsProperties) invoke(proxy, ispropertyGetter, new Object[] {})).strip();
  252. }
  253. }
  254. }
  255. private String getDataBindingClassName(Class<?> type) {
  256. for (Class<?> c : type.getInterfaces()) {
  257. if (c.equals(JsonBuilder.class)) {
  258. return type.getName();
  259. } else {
  260. return getDataBindingClassName(c);
  261. }
  262. }
  263. return null;
  264. }
  265. private String param(JsonObject o) {
  266. String ret = "";
  267. for (String k : o.keys()) {
  268. ret += ret.isEmpty() ? "" : "&";
  269. JsonValue v = o.get(k);
  270. if (v instanceof JsonArray) {
  271. for (int i = 0, l = ((JsonArray) v).length(); i < l; i++) {
  272. ret += i > 0 ? "&" : "";
  273. JsonValue e = ((JsonArray) v).get(i);
  274. ret += k + "[]=" + e.toJson();
  275. }
  276. } else {
  277. if (v != null && !(v instanceof JsonNull)) {
  278. ret += k + "=" + v.toJson();
  279. }
  280. }
  281. }
  282. return ret;
  283. }
  284. private HashSet<String> getAttributeNames(Method[] methods) {
  285. HashSet<String> valid = new HashSet<String>();
  286. if (methods == null || methods.length == 0) {
  287. return valid;
  288. }
  289. for (Method m : methods) {
  290. String attr = methodName2AttrName(m.getName());
  291. Name annotation = m.getAnnotation(Name.class);
  292. if (annotation != null) {
  293. attr = annotation.value();
  294. }
  295. valid.add(attr);
  296. }
  297. return valid;
  298. }
  299. private Hashtable<String, Method> getJsonBuilders(Method[] methods) {
  300. Hashtable<String, Method> ispropertyGetters = new Hashtable<String, Method>();
  301. if (methods == null || methods.length == 0) {
  302. return ispropertyGetters;
  303. }
  304. for (Method m : methods) {
  305. Class<?>[] classes = m.getParameterTypes();
  306. boolean isJsonBuilder =
  307. classes.length == 0 && IsProperties.class.isAssignableFrom(m.getReturnType());
  308. if (isJsonBuilder) {
  309. String attr = methodName2AttrName(m.getName());
  310. ispropertyGetters.put(attr, m);
  311. }
  312. }
  313. return ispropertyGetters;
  314. }
  315. }