Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SerializerGenerator.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.widgetsetutils;
  5. import java.io.PrintWriter;
  6. import java.util.ArrayList;
  7. import java.util.Date;
  8. import java.util.List;
  9. import com.google.gwt.core.client.GWT;
  10. import com.google.gwt.core.ext.Generator;
  11. import com.google.gwt.core.ext.GeneratorContext;
  12. import com.google.gwt.core.ext.TreeLogger;
  13. import com.google.gwt.core.ext.TreeLogger.Type;
  14. import com.google.gwt.core.ext.UnableToCompleteException;
  15. import com.google.gwt.core.ext.typeinfo.JClassType;
  16. import com.google.gwt.core.ext.typeinfo.JMethod;
  17. import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
  18. import com.google.gwt.core.ext.typeinfo.JType;
  19. import com.google.gwt.core.ext.typeinfo.TypeOracle;
  20. import com.google.gwt.json.client.JSONArray;
  21. import com.google.gwt.json.client.JSONObject;
  22. import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
  23. import com.google.gwt.user.rebind.SourceWriter;
  24. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  25. import com.vaadin.terminal.gwt.client.ConnectorMap;
  26. import com.vaadin.terminal.gwt.client.communication.JSONSerializer;
  27. import com.vaadin.terminal.gwt.client.communication.JsonDecoder;
  28. import com.vaadin.terminal.gwt.client.communication.JsonEncoder;
  29. import com.vaadin.terminal.gwt.client.communication.SerializerMap;
  30. /**
  31. * GWT generator for creating serializer classes for custom classes sent from
  32. * server to client.
  33. *
  34. * Only fields with a correspondingly named setter are deserialized.
  35. *
  36. * @since 7.0
  37. */
  38. public class SerializerGenerator extends Generator {
  39. private static final String SUBTYPE_SEPARATOR = "___";
  40. private static String beanSerializerPackageName = SerializerMap.class
  41. .getPackage().getName();
  42. @Override
  43. public String generate(TreeLogger logger, GeneratorContext context,
  44. String beanTypeName) throws UnableToCompleteException {
  45. JClassType beanType = context.getTypeOracle().findType(beanTypeName);
  46. String beanSerializerClassName = getSerializerSimpleClassName(beanType);
  47. try {
  48. // Generate class source code
  49. generateClass(logger, context, beanType, beanSerializerPackageName,
  50. beanSerializerClassName);
  51. } catch (Exception e) {
  52. logger.log(TreeLogger.ERROR, "SerializerGenerator failed for "
  53. + beanType.getQualifiedSourceName(), e);
  54. }
  55. // return the fully qualifed name of the class generated
  56. logger.log(TreeLogger.INFO, "Generated Serializer class "
  57. + getFullyQualifiedSerializerClassName(beanType));
  58. return getFullyQualifiedSerializerClassName(beanType);
  59. }
  60. /**
  61. * Generate source code for a VaadinSerializer implementation.
  62. *
  63. * @param logger
  64. * Logger object
  65. * @param context
  66. * Generator context
  67. * @param beanType
  68. * @param beanTypeName
  69. * bean type for which the serializer is to be generated
  70. * @param beanSerializerTypeName
  71. * name of the serializer class to generate
  72. */
  73. private void generateClass(TreeLogger logger, GeneratorContext context,
  74. JClassType beanType, String serializerPackageName,
  75. String serializerClassName) {
  76. // get print writer that receives the source code
  77. PrintWriter printWriter = null;
  78. printWriter = context.tryCreate(logger, serializerPackageName,
  79. serializerClassName);
  80. // print writer if null, source code has ALREADY been generated
  81. if (printWriter == null) {
  82. return;
  83. }
  84. Date date = new Date();
  85. TypeOracle typeOracle = context.getTypeOracle();
  86. String beanQualifiedSourceName = beanType.getQualifiedSourceName();
  87. logger.log(Type.DEBUG, "Processing serializable type "
  88. + beanQualifiedSourceName + "...");
  89. // init composer, set class properties, create source writer
  90. ClassSourceFileComposerFactory composer = null;
  91. composer = new ClassSourceFileComposerFactory(serializerPackageName,
  92. serializerClassName);
  93. composer.addImport(GWT.class.getName());
  94. composer.addImport(JSONArray.class.getName());
  95. // composer.addImport(JSONObject.class.getName());
  96. // composer.addImport(VPaintableMap.class.getName());
  97. composer.addImport(JsonDecoder.class.getName());
  98. // composer.addImport(VaadinSerializer.class.getName());
  99. composer.addImplementedInterface(JSONSerializer.class.getName());
  100. SourceWriter sourceWriter = composer.createSourceWriter(context,
  101. printWriter);
  102. sourceWriter.indent();
  103. // Serializer
  104. // public JSONValue serialize(Object value, ConnectorMap idMapper,
  105. // ApplicationConnection connection) {
  106. sourceWriter.println("public " + JSONObject.class.getName()
  107. + " serialize(" + Object.class.getName() + " value, "
  108. + ConnectorMap.class.getName() + " idMapper, "
  109. + ApplicationConnection.class.getName() + " connection) {");
  110. sourceWriter.indent();
  111. // MouseEventDetails castedValue = (MouseEventDetails) value;
  112. sourceWriter.println(beanQualifiedSourceName + " castedValue = ("
  113. + beanQualifiedSourceName + ") value;");
  114. // JSONObject json = new JSONObject();
  115. sourceWriter.println(JSONObject.class.getName() + " json = new "
  116. + JSONObject.class.getName() + "();");
  117. for (JMethod setterMethod : getSetters(beanType)) {
  118. String setterName = setterMethod.getName();
  119. String capitalizedFieldName = setterName.substring(3);
  120. String fieldName = decapitalize(capitalizedFieldName);
  121. String getterName = findGetter(beanType, setterMethod);
  122. if (getterName == null) {
  123. logger.log(TreeLogger.WARN, "No getter found for " + fieldName
  124. + ". Serialization will likely fail");
  125. }
  126. // json.put("button",
  127. // JsonEncoder.encode(castedValue.getButton(), idMapper,
  128. // connection));
  129. sourceWriter.println("json.put(\"" + fieldName + "\", "
  130. + JsonEncoder.class.getName() + ".encode(castedValue."
  131. + getterName + "(), idMapper, connection));");
  132. }
  133. // return json;
  134. sourceWriter.println("return json;");
  135. // }
  136. sourceWriter.println("}");
  137. // Deserializer
  138. sourceWriter.println("public " + beanQualifiedSourceName
  139. + " deserialize(" + JSONObject.class.getName() + " jsonValue, "
  140. + ConnectorMap.class.getName() + " idMapper, "
  141. + ApplicationConnection.class.getName() + " connection) {");
  142. sourceWriter.indent();
  143. // VButtonState state = GWT.create(VButtonState.class);
  144. sourceWriter.println(beanQualifiedSourceName + " state = GWT.create("
  145. + beanQualifiedSourceName + ".class);");
  146. for (JMethod method : getSetters(beanType)) {
  147. String setterName = method.getName();
  148. String capitalizedFieldName = setterName.substring(3);
  149. String fieldName = decapitalize(capitalizedFieldName);
  150. JType setterParameterType = method.getParameterTypes()[0];
  151. logger.log(Type.INFO, "* Processing field " + fieldName + " in "
  152. + beanQualifiedSourceName + " (" + beanType.getName() + ")");
  153. String jsonFieldName = "json" + capitalizedFieldName;
  154. // JSONArray jsonHeight = (JSONArray) jsonValue.get("height");
  155. sourceWriter.println("JSONArray " + jsonFieldName
  156. + " = (JSONArray) jsonValue.get(\"" + fieldName + "\");");
  157. // state.setHeight((String)
  158. // JsonDecoder.convertValue(jsonFieldValue,idMapper, connection));
  159. String fieldType;
  160. JPrimitiveType primitiveType = setterParameterType.isPrimitive();
  161. if (primitiveType != null) {
  162. // This is a primitive type -> must used the boxed type
  163. fieldType = primitiveType.getQualifiedBoxedSourceName();
  164. } else {
  165. fieldType = setterParameterType.getQualifiedSourceName();
  166. }
  167. sourceWriter.println("state." + setterName + "((" + fieldType
  168. + ") JsonDecoder.convertValue(" + jsonFieldName
  169. + ", idMapper, connection));");
  170. }
  171. // return state;
  172. sourceWriter.println("return state;");
  173. sourceWriter.println("}");
  174. sourceWriter.outdent();
  175. // End of class
  176. sourceWriter.println("}");
  177. sourceWriter.outdent();
  178. // commit generated class
  179. context.commit(logger, printWriter);
  180. logger.log(Type.INFO,
  181. "Done. (" + (new Date().getTime() - date.getTime()) / 1000
  182. + "seconds)");
  183. }
  184. private String findGetter(JClassType beanType, JMethod setterMethod) {
  185. JType setterParameterType = setterMethod.getParameterTypes()[0];
  186. String capitalizedFieldName = setterMethod.getName().substring(3);
  187. if (setterParameterType.getQualifiedSourceName().equals(
  188. boolean.class.getName())) {
  189. return "is" + capitalizedFieldName;
  190. } else {
  191. return "get" + capitalizedFieldName;
  192. }
  193. }
  194. /**
  195. * Returns a list of all setters found in the beanType or its parent class
  196. *
  197. * @param beanType
  198. * The type to check
  199. * @return A list of setter methods from the class and its parents
  200. */
  201. protected static List<JMethod> getSetters(JClassType beanType) {
  202. List<JMethod> setterMethods = new ArrayList<JMethod>();
  203. while (!beanType.getQualifiedSourceName()
  204. .equals(Object.class.getName())) {
  205. for (JMethod method : beanType.getMethods()) {
  206. // Process all setters that have corresponding fields
  207. if (!method.isPublic() || method.isStatic()
  208. || !method.getName().startsWith("set")
  209. || method.getParameterTypes().length != 1) {
  210. // Not setter, skip to next method
  211. continue;
  212. }
  213. setterMethods.add(method);
  214. }
  215. beanType = beanType.getSuperclass();
  216. }
  217. return setterMethods;
  218. }
  219. private String decapitalize(String name) {
  220. return name.substring(0, 1).toLowerCase() + name.substring(1);
  221. }
  222. private static String getSerializerSimpleClassName(JClassType beanType) {
  223. return getSimpleClassName(beanType) + "_Serializer";
  224. }
  225. private static String getSimpleClassName(JClassType type) {
  226. if (type.isMemberType()) {
  227. // Assumed to be static sub class
  228. String baseName = getSimpleClassName(type.getEnclosingType());
  229. String name = baseName + SUBTYPE_SEPARATOR
  230. + type.getSimpleSourceName();
  231. return name;
  232. }
  233. return type.getSimpleSourceName();
  234. }
  235. public static String getFullyQualifiedSerializerClassName(JClassType type) {
  236. return beanSerializerPackageName + "."
  237. + getSerializerSimpleClassName(type);
  238. }
  239. }