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.

SerializerGenerator.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.JEnumConstant;
  17. import com.google.gwt.core.ext.typeinfo.JEnumType;
  18. import com.google.gwt.core.ext.typeinfo.JMethod;
  19. import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
  20. import com.google.gwt.core.ext.typeinfo.JType;
  21. import com.google.gwt.core.ext.typeinfo.TypeOracle;
  22. import com.google.gwt.json.client.JSONObject;
  23. import com.google.gwt.json.client.JSONString;
  24. import com.google.gwt.json.client.JSONValue;
  25. import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
  26. import com.google.gwt.user.rebind.SourceWriter;
  27. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  28. import com.vaadin.terminal.gwt.client.ConnectorMap;
  29. import com.vaadin.terminal.gwt.client.communication.DiffJSONSerializer;
  30. import com.vaadin.terminal.gwt.client.communication.JSONSerializer;
  31. import com.vaadin.terminal.gwt.client.communication.JsonDecoder;
  32. import com.vaadin.terminal.gwt.client.communication.JsonEncoder;
  33. import com.vaadin.terminal.gwt.client.communication.SerializerMap;
  34. /**
  35. * GWT generator for creating serializer classes for custom classes sent from
  36. * server to client.
  37. *
  38. * Only fields with a correspondingly named setter are deserialized.
  39. *
  40. * @since 7.0
  41. */
  42. public class SerializerGenerator extends Generator {
  43. private static final String SUBTYPE_SEPARATOR = "___";
  44. private static String beanSerializerPackageName = SerializerMap.class
  45. .getPackage().getName();
  46. @Override
  47. public String generate(TreeLogger logger, GeneratorContext context,
  48. String beanTypeName) throws UnableToCompleteException {
  49. JClassType beanType = context.getTypeOracle().findType(beanTypeName);
  50. String beanSerializerClassName = getSerializerSimpleClassName(beanType);
  51. try {
  52. // Generate class source code
  53. generateClass(logger, context, beanType, beanSerializerPackageName,
  54. beanSerializerClassName);
  55. } catch (Exception e) {
  56. logger.log(TreeLogger.ERROR, "SerializerGenerator failed for "
  57. + beanType.getQualifiedSourceName(), e);
  58. throw new UnableToCompleteException();
  59. }
  60. // return the fully qualifed name of the class generated
  61. return getFullyQualifiedSerializerClassName(beanType);
  62. }
  63. /**
  64. * Generate source code for a VaadinSerializer implementation.
  65. *
  66. * @param logger
  67. * Logger object
  68. * @param context
  69. * Generator context
  70. * @param beanType
  71. * @param beanTypeName
  72. * bean type for which the serializer is to be generated
  73. * @param beanSerializerTypeName
  74. * name of the serializer class to generate
  75. */
  76. private void generateClass(TreeLogger logger, GeneratorContext context,
  77. JClassType beanType, String serializerPackageName,
  78. String serializerClassName) {
  79. // get print writer that receives the source code
  80. PrintWriter printWriter = null;
  81. printWriter = context.tryCreate(logger, serializerPackageName,
  82. serializerClassName);
  83. // print writer if null, source code has ALREADY been generated
  84. if (printWriter == null) {
  85. return;
  86. }
  87. boolean isEnum = (beanType.isEnum() != null);
  88. Date date = new Date();
  89. TypeOracle typeOracle = context.getTypeOracle();
  90. String beanQualifiedSourceName = beanType.getQualifiedSourceName();
  91. logger.log(Type.DEBUG, "Processing serializable type "
  92. + beanQualifiedSourceName + "...");
  93. // init composer, set class properties, create source writer
  94. ClassSourceFileComposerFactory composer = null;
  95. composer = new ClassSourceFileComposerFactory(serializerPackageName,
  96. serializerClassName);
  97. composer.addImport(GWT.class.getName());
  98. composer.addImport(JSONValue.class.getName());
  99. composer.addImport(com.vaadin.terminal.gwt.client.communication.Type.class
  100. .getName());
  101. // composer.addImport(JSONObject.class.getName());
  102. // composer.addImport(VPaintableMap.class.getName());
  103. composer.addImport(JsonDecoder.class.getName());
  104. // composer.addImport(VaadinSerializer.class.getName());
  105. if (isEnum) {
  106. composer.addImplementedInterface(JSONSerializer.class.getName()
  107. + "<" + beanQualifiedSourceName + ">");
  108. } else {
  109. composer.addImplementedInterface(DiffJSONSerializer.class.getName()
  110. + "<" + beanQualifiedSourceName + ">");
  111. }
  112. SourceWriter sourceWriter = composer.createSourceWriter(context,
  113. printWriter);
  114. sourceWriter.indent();
  115. // Serializer
  116. // public JSONValue serialize(Object value, ConnectorMap idMapper,
  117. // ApplicationConnection connection) {
  118. sourceWriter.println("public " + JSONValue.class.getName()
  119. + " serialize(" + beanQualifiedSourceName + " value, "
  120. + ConnectorMap.class.getName() + " idMapper, "
  121. + ApplicationConnection.class.getName() + " connection) {");
  122. sourceWriter.indent();
  123. // MouseEventDetails castedValue = (MouseEventDetails) value;
  124. sourceWriter.println(beanQualifiedSourceName + " castedValue = ("
  125. + beanQualifiedSourceName + ") value;");
  126. if (isEnum) {
  127. writeEnumSerializer(logger, sourceWriter, beanType);
  128. } else {
  129. writeBeanSerializer(logger, sourceWriter, beanType);
  130. }
  131. // }
  132. sourceWriter.outdent();
  133. sourceWriter.println("}");
  134. sourceWriter.println();
  135. // Updater
  136. // public void update(T target, Type type, JSONValue jsonValue,
  137. // ApplicationConnection connection);
  138. if (!isEnum) {
  139. sourceWriter.println("public void update("
  140. + beanQualifiedSourceName + " target, Type type, "
  141. + JSONValue.class.getName() + " jsonValue, "
  142. + ApplicationConnection.class.getName() + " connection) {");
  143. sourceWriter.indent();
  144. writeBeanDeserializer(logger, sourceWriter, beanType, true);
  145. sourceWriter.outdent();
  146. sourceWriter.println("}");
  147. }
  148. // Deserializer
  149. // T deserialize(Type type, JSONValue jsonValue, ApplicationConnection
  150. // connection);
  151. sourceWriter.println("public " + beanQualifiedSourceName
  152. + " deserialize(Type type, " + JSONValue.class.getName()
  153. + " jsonValue, " + ApplicationConnection.class.getName()
  154. + " connection) {");
  155. sourceWriter.indent();
  156. if (isEnum) {
  157. writeEnumDeserializer(logger, sourceWriter, beanType.isEnum());
  158. } else {
  159. writeBeanDeserializer(logger, sourceWriter, beanType, false);
  160. }
  161. sourceWriter.println("}");
  162. sourceWriter.outdent();
  163. // End of class
  164. sourceWriter.println("}");
  165. sourceWriter.outdent();
  166. // commit generated class
  167. context.commit(logger, printWriter);
  168. logger.log(TreeLogger.INFO, "Generated Serializer class "
  169. + getFullyQualifiedSerializerClassName(beanType));
  170. }
  171. private void writeEnumDeserializer(TreeLogger logger,
  172. SourceWriter sourceWriter, JEnumType enumType) {
  173. sourceWriter.println("String enumIdentifier = (("
  174. + JSONString.class.getName() + ")jsonValue).stringValue();");
  175. for (JEnumConstant e : enumType.getEnumConstants()) {
  176. sourceWriter.println("if (\"" + e.getName()
  177. + "\".equals(enumIdentifier)) {");
  178. sourceWriter.indent();
  179. sourceWriter.println("return " + enumType.getQualifiedSourceName()
  180. + "." + e.getName() + ";");
  181. sourceWriter.outdent();
  182. sourceWriter.println("}");
  183. }
  184. sourceWriter.println("return null;");
  185. }
  186. private void writeBeanDeserializer(TreeLogger logger,
  187. SourceWriter sourceWriter, JClassType beanType, boolean update) {
  188. String beanQualifiedSourceName = beanType.getQualifiedSourceName();
  189. if (!update) {
  190. sourceWriter.println(beanQualifiedSourceName
  191. + " target = GWT.create(" + beanQualifiedSourceName
  192. + ".class);");
  193. }
  194. // JSONOBject json = (JSONObject)jsonValue;
  195. sourceWriter.println(JSONObject.class.getName() + " json = ("
  196. + JSONObject.class.getName() + ")jsonValue;");
  197. for (JMethod method : getSetters(beanType)) {
  198. String setterName = method.getName();
  199. String fieldName = setterName.substring(3); // setZIndex() -> ZIndex
  200. JType setterParameterType = method.getParameterTypes()[0];
  201. logger.log(Type.DEBUG, "* Processing field " + fieldName + " in "
  202. + beanQualifiedSourceName + " (" + beanType.getName() + ")");
  203. // if (json.containsKey("height")) {
  204. sourceWriter.println("if (json.containsKey(\"" + fieldName
  205. + "\")) {");
  206. sourceWriter.indent();
  207. String jsonFieldName = "json_" + fieldName;
  208. // JSONValue json_Height = json.get("height");
  209. sourceWriter.println("JSONValue " + jsonFieldName
  210. + " = json.get(\"" + fieldName + "\");");
  211. String fieldType;
  212. String getterName = "get" + fieldName;
  213. JPrimitiveType primitiveType = setterParameterType.isPrimitive();
  214. if (primitiveType != null) {
  215. // This is a primitive type -> must used the boxed type
  216. fieldType = primitiveType.getQualifiedBoxedSourceName();
  217. if (primitiveType == JPrimitiveType.BOOLEAN) {
  218. getterName = "is" + fieldName;
  219. }
  220. } else {
  221. fieldType = setterParameterType.getQualifiedSourceName();
  222. }
  223. // String referenceValue = target.getHeight();
  224. sourceWriter.println(fieldType + " referenceValue = target."
  225. + getterName + "();");
  226. // target.setHeight((String)
  227. // JsonDecoder.decodeValue(jsonFieldValue,referenceValue, idMapper,
  228. // connection));
  229. sourceWriter.print("target." + setterName + "((" + fieldType + ") "
  230. + JsonDecoder.class.getName() + ".decodeValue(");
  231. GeneratedRpcMethodProviderGenerator.writeTypeCreator(sourceWriter,
  232. setterParameterType);
  233. sourceWriter.println(", " + jsonFieldName
  234. + ", referenceValue, connection));");
  235. // } ... end of if contains
  236. sourceWriter.outdent();
  237. sourceWriter.println("}");
  238. }
  239. if (!update) {
  240. // return target;
  241. sourceWriter.println("return target;");
  242. }
  243. }
  244. private void writeEnumSerializer(TreeLogger logger,
  245. SourceWriter sourceWriter, JClassType beanType) {
  246. // return new JSONString(castedValue.name());
  247. sourceWriter.println("return new " + JSONString.class.getName()
  248. + "(castedValue.name());");
  249. }
  250. private void writeBeanSerializer(TreeLogger logger,
  251. SourceWriter sourceWriter, JClassType beanType) {
  252. // JSONObject json = new JSONObject();
  253. sourceWriter.println(JSONObject.class.getName() + " json = new "
  254. + JSONObject.class.getName() + "();");
  255. for (JMethod setterMethod : getSetters(beanType)) {
  256. String setterName = setterMethod.getName();
  257. String fieldName = setterName.substring(3); // setZIndex() -> ZIndex
  258. String getterName = findGetter(beanType, setterMethod);
  259. if (getterName == null) {
  260. logger.log(TreeLogger.ERROR, "No getter found for " + fieldName
  261. + ". Serialization will likely fail");
  262. }
  263. // json.put("button",
  264. // JsonEncoder.encode(castedValue.getButton(), false, idMapper,
  265. // connection));
  266. sourceWriter.println("json.put(\"" + fieldName + "\", "
  267. + JsonEncoder.class.getName() + ".encode(castedValue."
  268. + getterName + "(), false, idMapper, connection));");
  269. }
  270. // return json;
  271. sourceWriter.println("return json;");
  272. }
  273. private String findGetter(JClassType beanType, JMethod setterMethod) {
  274. JType setterParameterType = setterMethod.getParameterTypes()[0];
  275. String fieldName = setterMethod.getName().substring(3);
  276. if (setterParameterType.getQualifiedSourceName().equals(
  277. boolean.class.getName())) {
  278. return "is" + fieldName;
  279. } else {
  280. return "get" + fieldName;
  281. }
  282. }
  283. /**
  284. * Returns a list of all setters found in the beanType or its parent class
  285. *
  286. * @param beanType
  287. * The type to check
  288. * @return A list of setter methods from the class and its parents
  289. */
  290. protected static List<JMethod> getSetters(JClassType beanType) {
  291. List<JMethod> setterMethods = new ArrayList<JMethod>();
  292. while (beanType != null
  293. && !beanType.getQualifiedSourceName().equals(
  294. Object.class.getName())) {
  295. for (JMethod method : beanType.getMethods()) {
  296. // Process all setters that have corresponding fields
  297. if (!method.isPublic() || method.isStatic()
  298. || !method.getName().startsWith("set")
  299. || method.getParameterTypes().length != 1) {
  300. // Not setter, skip to next method
  301. continue;
  302. }
  303. setterMethods.add(method);
  304. }
  305. beanType = beanType.getSuperclass();
  306. }
  307. return setterMethods;
  308. }
  309. private static String getSerializerSimpleClassName(JClassType beanType) {
  310. return getSimpleClassName(beanType) + "_Serializer";
  311. }
  312. private static String getSimpleClassName(JClassType type) {
  313. if (type.isMemberType()) {
  314. // Assumed to be static sub class
  315. String baseName = getSimpleClassName(type.getEnclosingType());
  316. String name = baseName + SUBTYPE_SEPARATOR
  317. + type.getSimpleSourceName();
  318. return name;
  319. }
  320. return type.getSimpleSourceName();
  321. }
  322. public static String getFullyQualifiedSerializerClassName(JClassType type) {
  323. return beanSerializerPackageName + "."
  324. + getSerializerSimpleClassName(type);
  325. }
  326. }