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.

ConnectorBundleLoaderFactory.java 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  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.vaadin.server.widgetsetutils;
  17. import java.io.PrintWriter;
  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.Comparator;
  23. import java.util.HashMap;
  24. import java.util.HashSet;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Map.Entry;
  28. import java.util.Set;
  29. import java.util.TreeMap;
  30. import com.google.gwt.core.client.GWT;
  31. import com.google.gwt.core.client.RunAsyncCallback;
  32. import com.google.gwt.core.ext.Generator;
  33. import com.google.gwt.core.ext.GeneratorContext;
  34. import com.google.gwt.core.ext.TreeLogger;
  35. import com.google.gwt.core.ext.TreeLogger.Type;
  36. import com.google.gwt.core.ext.UnableToCompleteException;
  37. import com.google.gwt.core.ext.typeinfo.JClassType;
  38. import com.google.gwt.core.ext.typeinfo.JMethod;
  39. import com.google.gwt.core.ext.typeinfo.JParameterizedType;
  40. import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
  41. import com.google.gwt.core.ext.typeinfo.JType;
  42. import com.google.gwt.core.ext.typeinfo.NotFoundException;
  43. import com.google.gwt.core.ext.typeinfo.TypeOracle;
  44. import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
  45. import com.google.gwt.user.rebind.SourceWriter;
  46. import com.vaadin.client.JsArrayObject;
  47. import com.vaadin.client.ServerConnector;
  48. import com.vaadin.client.annotations.OnStateChange;
  49. import com.vaadin.client.communication.JsonDecoder;
  50. import com.vaadin.client.metadata.ConnectorBundleLoader;
  51. import com.vaadin.client.metadata.ConnectorBundleLoader.CValUiInfo;
  52. import com.vaadin.client.metadata.InvokationHandler;
  53. import com.vaadin.client.metadata.OnStateChangeMethod;
  54. import com.vaadin.client.metadata.ProxyHandler;
  55. import com.vaadin.client.metadata.TypeData;
  56. import com.vaadin.client.metadata.TypeDataStore;
  57. import com.vaadin.client.metadata.TypeDataStore.MethodAttribute;
  58. import com.vaadin.client.ui.UnknownComponentConnector;
  59. import com.vaadin.server.widgetsetutils.metadata.ClientRpcVisitor;
  60. import com.vaadin.server.widgetsetutils.metadata.ConnectorBundle;
  61. import com.vaadin.server.widgetsetutils.metadata.ConnectorInitVisitor;
  62. import com.vaadin.server.widgetsetutils.metadata.GeneratedSerializer;
  63. import com.vaadin.server.widgetsetutils.metadata.OnStateChangeVisitor;
  64. import com.vaadin.server.widgetsetutils.metadata.Property;
  65. import com.vaadin.server.widgetsetutils.metadata.RendererVisitor;
  66. import com.vaadin.server.widgetsetutils.metadata.ServerRpcVisitor;
  67. import com.vaadin.server.widgetsetutils.metadata.StateInitVisitor;
  68. import com.vaadin.server.widgetsetutils.metadata.TypeVisitor;
  69. import com.vaadin.server.widgetsetutils.metadata.WidgetInitVisitor;
  70. import com.vaadin.shared.annotations.DelegateToWidget;
  71. import com.vaadin.shared.annotations.NoLayout;
  72. import com.vaadin.shared.communication.ClientRpc;
  73. import com.vaadin.shared.communication.ServerRpc;
  74. import com.vaadin.shared.ui.Connect;
  75. import com.vaadin.shared.ui.Connect.LoadStyle;
  76. import com.vaadin.tools.CvalAddonsChecker;
  77. import com.vaadin.tools.CvalChecker;
  78. import com.vaadin.tools.CvalChecker.InvalidCvalException;
  79. public class ConnectorBundleLoaderFactory extends Generator {
  80. /**
  81. * Special SourceWriter that approximates the number of written bytes to
  82. * support splitting long methods into shorter chunks to avoid hitting the
  83. * 65535 byte limit.
  84. */
  85. private class SplittingSourceWriter implements SourceWriter {
  86. private final SourceWriter target;
  87. private final String baseName;
  88. private final int splitSize;
  89. private final List<String> methodNames;
  90. // Seems to be undercounted by about 15%
  91. private int approximateChars = 0;
  92. private int wrapCount = 0;
  93. public SplittingSourceWriter(SourceWriter target, String baseName,
  94. int splitSize) {
  95. this.target = target;
  96. this.baseName = baseName;
  97. this.splitSize = splitSize;
  98. methodNames = new ArrayList<String>();
  99. methodNames.add(baseName);
  100. }
  101. @Override
  102. public void beginJavaDocComment() {
  103. target.beginJavaDocComment();
  104. addChars(10);
  105. }
  106. private void addChars(int i) {
  107. approximateChars += i;
  108. }
  109. private void addChars(String s) {
  110. addChars(s.length());
  111. }
  112. private void addChars(String s, Object[] args) {
  113. addChars(String.format(s, args));
  114. }
  115. @Override
  116. public void commit(TreeLogger logger) {
  117. target.commit(logger);
  118. }
  119. @Override
  120. public void endJavaDocComment() {
  121. target.endJavaDocComment();
  122. addChars(10);
  123. }
  124. @Override
  125. public void indent() {
  126. target.indent();
  127. addChars(10);
  128. }
  129. @Override
  130. public void indentln(String s) {
  131. target.indentln(s);
  132. addChars(s);
  133. }
  134. @Override
  135. public void indentln(String s, Object... args) {
  136. target.indentln(s, args);
  137. addChars(s, args);
  138. }
  139. @Override
  140. public void outdent() {
  141. target.outdent();
  142. }
  143. @Override
  144. public void print(String s) {
  145. target.print(s);
  146. addChars(s);
  147. }
  148. @Override
  149. public void print(String s, Object... args) {
  150. target.print(s, args);
  151. addChars(s, args);
  152. }
  153. @Override
  154. public void println() {
  155. target.println();
  156. addChars(5);
  157. }
  158. @Override
  159. public void println(String s) {
  160. target.println(s);
  161. addChars(s);
  162. }
  163. @Override
  164. public void println(String s, Object... args) {
  165. target.println(s, args);
  166. addChars(s, args);
  167. }
  168. public void splitIfNeeded() {
  169. splitIfNeeded(false, null);
  170. }
  171. public void splitIfNeeded(boolean isNative, String params) {
  172. if (approximateChars > splitSize) {
  173. String newMethod = baseName + wrapCount++;
  174. String args = params == null ? "" : params;
  175. if (isNative) {
  176. outdent();
  177. println("}-*/;");
  178. // To support fields of type long (#13692)
  179. println("@com.google.gwt.core.client.UnsafeNativeLong");
  180. println("private native void %s(%s) /*-{", newMethod, args);
  181. } else {
  182. println("%s();", newMethod);
  183. outdent();
  184. println("}");
  185. println("private void %s(%s) {", newMethod, args);
  186. }
  187. methodNames.add(newMethod);
  188. indent();
  189. approximateChars = 0;
  190. }
  191. }
  192. public List<String> getMethodNames() {
  193. return Collections.unmodifiableList(methodNames);
  194. }
  195. }
  196. private CvalAddonsChecker cvalChecker = new CvalAddonsChecker();
  197. @Override
  198. public String generate(TreeLogger logger, GeneratorContext context,
  199. String typeName) throws UnableToCompleteException {
  200. TypeOracle typeOracle = context.getTypeOracle();
  201. try {
  202. JClassType classType = typeOracle.getType(typeName);
  203. String packageName = classType.getPackage().getName();
  204. String className = classType.getSimpleSourceName() + "Impl";
  205. generateClass(logger, context, packageName, className, typeName);
  206. return packageName + "." + className;
  207. } catch (UnableToCompleteException e) {
  208. // Just rethrow
  209. throw e;
  210. } catch (Exception e) {
  211. logger.log(Type.ERROR, getClass() + " failed", e);
  212. throw new UnableToCompleteException();
  213. }
  214. }
  215. private void generateClass(TreeLogger logger, GeneratorContext context,
  216. String packageName, String className, String requestedType)
  217. throws Exception {
  218. PrintWriter printWriter = context.tryCreate(logger, packageName,
  219. className);
  220. if (printWriter == null) {
  221. return;
  222. }
  223. List<CValUiInfo> cvalInfos = null;
  224. try {
  225. if (cvalChecker != null) {
  226. cvalInfos = cvalChecker.run();
  227. // Don't run twice
  228. cvalChecker = null;
  229. }
  230. } catch (InvalidCvalException e) {
  231. System.err.println("\n\n\n\n" + CvalChecker.LINE);
  232. for (String line : e.getMessage().split("\n")) {
  233. System.err.println(line);
  234. }
  235. System.err.println(CvalChecker.LINE + "\n\n\n\n");
  236. System.exit(1);
  237. throw new UnableToCompleteException();
  238. }
  239. List<ConnectorBundle> bundles = buildBundles(logger,
  240. context.getTypeOracle());
  241. ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(
  242. packageName, className);
  243. composer.setSuperclass(requestedType);
  244. SourceWriter w = composer.createSourceWriter(context, printWriter);
  245. w.println("public void init() {");
  246. w.indent();
  247. for (ConnectorBundle bundle : bundles) {
  248. detectBadProperties(bundle, logger);
  249. String name = bundle.getName();
  250. boolean isEager = name
  251. .equals(ConnectorBundleLoader.EAGER_BUNDLE_NAME);
  252. w.print("addAsyncBlockLoader(new AsyncBundleLoader(\"");
  253. w.print(escape(name));
  254. w.print("\", ");
  255. w.print("new String[] {");
  256. for (Entry<JClassType, Set<String>> entry : bundle.getIdentifiers()
  257. .entrySet()) {
  258. Set<String> identifiers = entry.getValue();
  259. for (String id : identifiers) {
  260. w.print("\"");
  261. w.print(escape(id));
  262. w.print("\",");
  263. }
  264. }
  265. w.println("}) {");
  266. w.indent();
  267. w.print("protected void load(final ");
  268. w.print(TypeDataStore.class.getName());
  269. w.println(" store) {");
  270. w.indent();
  271. if (!isEager) {
  272. w.print(GWT.class.getName());
  273. w.print(".runAsync(");
  274. }
  275. w.println("new %s() {", RunAsyncCallback.class.getName());
  276. w.indent();
  277. w.println("public void onSuccess() {");
  278. w.indent();
  279. w.println("load();");
  280. w.println("%s.get().setLoaded(getName());",
  281. ConnectorBundleLoader.class.getName());
  282. // Close onSuccess method
  283. w.outdent();
  284. w.println("}");
  285. w.println("private void load() {");
  286. w.indent();
  287. String loadNativeJsBundle = "loadJsBundle";
  288. printBundleData(logger, w, bundle, loadNativeJsBundle);
  289. // Close load method
  290. w.outdent();
  291. w.println("}");
  292. // Separate method for loading native JS stuff (e.g. callbacks)
  293. String loadNativeJsMethodName = "loadNativeJs";
  294. // To support fields of type long (#13692)
  295. w.println("@com.google.gwt.core.client.UnsafeNativeLong");
  296. w.println("private native void %s(%s store) /*-{",
  297. loadNativeJsMethodName, TypeDataStore.class.getName());
  298. w.indent();
  299. List<String> jsMethodNames = printJsBundleData(logger, w, bundle,
  300. loadNativeJsMethodName);
  301. w.outdent();
  302. w.println("}-*/;");
  303. // Call all generated native method inside one Java method to avoid
  304. // refercences inside native methods to each other
  305. w.println("private void %s(%s store) {", loadNativeJsBundle,
  306. TypeDataStore.class.getName());
  307. w.indent();
  308. printLoadJsBundleData(w, loadNativeJsBundle, jsMethodNames);
  309. w.outdent();
  310. w.println("}");
  311. // onFailure method declaration starts
  312. w.println("public void onFailure(Throwable reason) {");
  313. w.indent();
  314. w.println("%s.get().setLoadFailure(getName(), reason);",
  315. ConnectorBundleLoader.class.getName());
  316. w.outdent();
  317. w.println("}");
  318. // Close new RunAsyncCallback() {}
  319. w.outdent();
  320. w.print("}");
  321. if (isEager) {
  322. w.println(".onSuccess();");
  323. } else {
  324. w.println(");");
  325. }
  326. // Close load method
  327. w.outdent();
  328. w.println("}");
  329. // Close add(new ...
  330. w.outdent();
  331. w.println("});");
  332. }
  333. if (cvalInfos != null && !cvalInfos.isEmpty()) {
  334. w.println("{");
  335. for (CValUiInfo c : cvalInfos) {
  336. if ("evaluation".equals(c.type)) {
  337. w.println("cvals.add(new CValUiInfo(\"" + c.product
  338. + "\", \"" + c.version + "\", \"" + c.widgetset
  339. + "\", null));");
  340. }
  341. }
  342. w.println("}");
  343. }
  344. w.outdent();
  345. w.println("}");
  346. w.commit(logger);
  347. }
  348. private void printLoadJsBundleData(SourceWriter w, String methodName,
  349. List<String> methods) {
  350. SplittingSourceWriter writer = new SplittingSourceWriter(w, methodName,
  351. 30000);
  352. for (String method : methods) {
  353. writer.println("%s(store);", method);
  354. writer.splitIfNeeded();
  355. }
  356. }
  357. private void detectBadProperties(ConnectorBundle bundle, TreeLogger logger)
  358. throws UnableToCompleteException {
  359. Map<JClassType, Set<String>> definedProperties = new HashMap<JClassType, Set<String>>();
  360. for (Property property : bundle.getNeedsProperty()) {
  361. JClassType beanType = property.getBeanType();
  362. Set<String> usedPropertyNames = definedProperties.get(beanType);
  363. if (usedPropertyNames == null) {
  364. usedPropertyNames = new HashSet<String>();
  365. definedProperties.put(beanType, usedPropertyNames);
  366. }
  367. String name = property.getName();
  368. if (!usedPropertyNames.add(name)) {
  369. logger.log(Type.ERROR, beanType.getQualifiedSourceName()
  370. + " has multiple properties with the name " + name
  371. + ". This can happen if there are multiple "
  372. + "setters with identical names ignoring case.");
  373. throw new UnableToCompleteException();
  374. }
  375. if (!property.hasAccessorMethods()) {
  376. logger.log(Type.ERROR, beanType.getQualifiedSourceName()
  377. + " has the property '" + name
  378. + "' without getter defined.");
  379. throw new UnableToCompleteException();
  380. }
  381. }
  382. }
  383. private List<String> printJsBundleData(TreeLogger logger, SourceWriter w,
  384. ConnectorBundle bundle, String methodName) {
  385. SplittingSourceWriter writer = new SplittingSourceWriter(w, methodName,
  386. 30000);
  387. Set<Property> needsProperty = bundle.getNeedsProperty();
  388. for (Property property : needsProperty) {
  389. writer.println("var data = {");
  390. writer.indent();
  391. if (property.getAnnotation(NoLayout.class) != null) {
  392. writer.println("noLayout: 1, ");
  393. }
  394. writer.println("setter: function(bean, value) {");
  395. writer.indent();
  396. property.writeSetterBody(logger, writer, "bean", "value");
  397. writer.outdent();
  398. writer.println("},");
  399. writer.println("getter: function(bean) {");
  400. writer.indent();
  401. property.writeGetterBody(logger, writer, "bean");
  402. writer.outdent();
  403. writer.println("}");
  404. writer.outdent();
  405. writer.println("};");
  406. // Method declaration
  407. writer.print(
  408. "store.@%s::setPropertyData(Ljava/lang/Class;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)",
  409. TypeDataStore.class.getName());
  410. writer.println("(@%s::class, '%s', data);", property.getBeanType()
  411. .getQualifiedSourceName(), property.getName());
  412. writer.println();
  413. writer.splitIfNeeded(true,
  414. String.format("%s store", TypeDataStore.class.getName()));
  415. }
  416. return writer.getMethodNames();
  417. }
  418. private void printBundleData(TreeLogger logger, SourceWriter sourceWriter,
  419. ConnectorBundle bundle, String loadNativeJsMethodName)
  420. throws UnableToCompleteException {
  421. // Split into new load method when reaching approximately 30000 bytes
  422. SplittingSourceWriter w = new SplittingSourceWriter(sourceWriter,
  423. "load", 30000);
  424. writeSuperClasses(w, bundle);
  425. writeIdentifiers(w, bundle);
  426. writeGwtConstructors(w, bundle);
  427. writeReturnTypes(w, bundle);
  428. writeInvokers(logger, w, bundle);
  429. writeParamTypes(w, bundle);
  430. writeProxys(w, bundle);
  431. writeMethodAttributes(logger, w, bundle);
  432. w.println("%s(store);", loadNativeJsMethodName);
  433. // Must use Java code to generate Type data (because of Type[]), doing
  434. // this after the JS property data has been initialized
  435. writePropertyTypes(logger, w, bundle);
  436. writeSerializers(logger, w, bundle);
  437. writePresentationTypes(w, bundle);
  438. writeDelegateToWidget(logger, w, bundle);
  439. writeOnStateChangeHandlers(logger, w, bundle);
  440. }
  441. private void writeOnStateChangeHandlers(TreeLogger logger,
  442. SplittingSourceWriter w, ConnectorBundle bundle)
  443. throws UnableToCompleteException {
  444. Map<JClassType, Set<JMethod>> needsOnStateChangeHandler = bundle
  445. .getNeedsOnStateChangeHandler();
  446. for (Entry<JClassType, Set<JMethod>> entry : needsOnStateChangeHandler
  447. .entrySet()) {
  448. JClassType connector = entry.getKey();
  449. TreeLogger typeLogger = logger.branch(
  450. Type.DEBUG,
  451. "Generating @OnStateChange support for "
  452. + connector.getName());
  453. // Build map to speed up error checking
  454. HashMap<String, Property> stateProperties = new HashMap<String, Property>();
  455. JClassType stateType = ConnectorBundle
  456. .findInheritedMethod(connector, "getState").getReturnType()
  457. .isClassOrInterface();
  458. for (Property property : bundle.getProperties(stateType)) {
  459. stateProperties.put(property.getName(), property);
  460. }
  461. for (JMethod method : entry.getValue()) {
  462. TreeLogger methodLogger = typeLogger.branch(Type.DEBUG,
  463. "Processing method " + method.getName());
  464. if (method.isPublic() || method.isProtected()) {
  465. methodLogger
  466. .log(Type.ERROR,
  467. "@OnStateChange is only supported for methods with private or default visibility.");
  468. throw new UnableToCompleteException();
  469. }
  470. OnStateChange onStateChange = method
  471. .getAnnotation(OnStateChange.class);
  472. String[] properties = onStateChange.value();
  473. if (properties.length == 0) {
  474. methodLogger.log(Type.ERROR,
  475. "There are no properties to listen to");
  476. throw new UnableToCompleteException();
  477. }
  478. // Verify that all properties do exist
  479. for (String propertyName : properties) {
  480. if (!stateProperties.containsKey(propertyName)) {
  481. methodLogger.log(Type.ERROR,
  482. "State class has no property named "
  483. + propertyName);
  484. throw new UnableToCompleteException();
  485. }
  486. }
  487. if (method.getParameters().length != 0) {
  488. methodLogger.log(Type.ERROR,
  489. "Method should accept zero parameters");
  490. throw new UnableToCompleteException();
  491. }
  492. // new OnStateChangeMethod(Class declaringClass, String
  493. // methodName, String[], properties)
  494. w.print("store.addOnStateChangeMethod(%s, new %s(",
  495. getClassLiteralString(connector),
  496. OnStateChangeMethod.class.getName());
  497. if (!connector.equals(method.getEnclosingType())) {
  498. w.print("%s, ",
  499. getClassLiteralString(method.getEnclosingType()));
  500. }
  501. w.print("\"%s\", ", method.getName());
  502. w.print("new String[] {");
  503. for (String propertyName : properties) {
  504. w.print("\"%s\", ", propertyName);
  505. }
  506. w.print("}");
  507. w.println("));");
  508. w.splitIfNeeded();
  509. }
  510. }
  511. }
  512. private void writeSuperClasses(SplittingSourceWriter w,
  513. ConnectorBundle bundle) {
  514. List<JClassType> needsSuperclass = new ArrayList<JClassType>(
  515. bundle.getNeedsSuperclass());
  516. // Emit in hierarchy order to ensure superclass is defined when
  517. // referenced
  518. Collections.sort(needsSuperclass, new Comparator<JClassType>() {
  519. @Override
  520. public int compare(JClassType type1, JClassType type2) {
  521. int depthDiff = getDepth(type1) - getDepth(type2);
  522. if (depthDiff != 0) {
  523. return depthDiff;
  524. } else {
  525. // Just something to get a stable compare
  526. return type1.getName().compareTo(type2.getName());
  527. }
  528. }
  529. private int getDepth(JClassType type) {
  530. int depth = 0;
  531. while (type != null) {
  532. depth++;
  533. type = type.getSuperclass();
  534. }
  535. return depth;
  536. }
  537. });
  538. for (JClassType jClassType : needsSuperclass) {
  539. JClassType superclass = jClassType.getSuperclass();
  540. while (superclass != null && !superclass.isPublic()) {
  541. superclass = superclass.getSuperclass();
  542. }
  543. String classLiteralString;
  544. if (superclass == null) {
  545. classLiteralString = "null";
  546. } else {
  547. classLiteralString = getClassLiteralString(superclass);
  548. }
  549. w.println("store.setSuperClass(%s, %s);",
  550. getClassLiteralString(jClassType), classLiteralString);
  551. }
  552. }
  553. private void writeDelegateToWidget(TreeLogger logger,
  554. SplittingSourceWriter w, ConnectorBundle bundle) {
  555. Map<JClassType, Set<Property>> needsDelegateToWidget = bundle
  556. .getNeedsDelegateToWidget();
  557. for (Entry<JClassType, Set<Property>> entry : needsDelegateToWidget
  558. .entrySet()) {
  559. JClassType beanType = entry.getKey();
  560. for (Property property : entry.getValue()) {
  561. w.println(
  562. "store.setDelegateToWidget(%s, \"%s\", \"%s\");",
  563. getClassLiteralString(beanType),// property.getBeanType()),
  564. property.getName(),
  565. property.getAnnotation(DelegateToWidget.class).value());
  566. }
  567. w.splitIfNeeded();
  568. }
  569. }
  570. private void writeSerializers(TreeLogger logger, SplittingSourceWriter w,
  571. ConnectorBundle bundle) throws UnableToCompleteException {
  572. Map<JType, GeneratedSerializer> serializers = bundle.getSerializers();
  573. for (Entry<JType, GeneratedSerializer> entry : serializers.entrySet()) {
  574. JType type = entry.getKey();
  575. GeneratedSerializer serializer = entry.getValue();
  576. w.print("store.setSerializerFactory(");
  577. writeClassLiteral(w, type);
  578. w.print(", ");
  579. w.println("new Invoker() {");
  580. w.indent();
  581. w.println("public Object invoke(Object target, Object[] params) {");
  582. w.indent();
  583. serializer.writeSerializerInstantiator(logger, w);
  584. w.outdent();
  585. w.println("}");
  586. w.outdent();
  587. w.print("}");
  588. w.println(");");
  589. w.splitIfNeeded();
  590. }
  591. }
  592. private void writePresentationTypes(SplittingSourceWriter w,
  593. ConnectorBundle bundle) {
  594. Map<JClassType, JType> presentationTypes = bundle
  595. .getPresentationTypes();
  596. for (Entry<JClassType, JType> entry : presentationTypes.entrySet()) {
  597. w.print("store.setPresentationType(");
  598. writeClassLiteral(w, entry.getKey());
  599. w.print(", ");
  600. writeClassLiteral(w, entry.getValue());
  601. w.println(");");
  602. w.splitIfNeeded();
  603. }
  604. }
  605. private void writePropertyTypes(TreeLogger logger, SplittingSourceWriter w,
  606. ConnectorBundle bundle) {
  607. Set<Property> properties = bundle.getNeedsProperty();
  608. for (Property property : properties) {
  609. w.print("store.setPropertyType(");
  610. writeClassLiteral(w, property.getBeanType());
  611. w.print(", \"");
  612. w.print(escape(property.getName()));
  613. w.print("\", ");
  614. writeTypeCreator(w, property.getPropertyType());
  615. w.println(");");
  616. w.splitIfNeeded();
  617. }
  618. }
  619. private void writeMethodAttributes(TreeLogger logger,
  620. SplittingSourceWriter w, ConnectorBundle bundle) {
  621. for (Entry<JClassType, Map<JMethod, Set<MethodAttribute>>> typeEntry : bundle
  622. .getMethodAttributes().entrySet()) {
  623. JClassType type = typeEntry.getKey();
  624. for (Entry<JMethod, Set<MethodAttribute>> methodEntry : typeEntry
  625. .getValue().entrySet()) {
  626. JMethod method = methodEntry.getKey();
  627. Set<MethodAttribute> attributes = methodEntry.getValue();
  628. for (MethodAttribute attribute : attributes) {
  629. w.println("store.setMethodAttribute(%s, \"%s\", %s.%s);",
  630. getClassLiteralString(type), method.getName(),
  631. MethodAttribute.class.getCanonicalName(),
  632. attribute.name());
  633. w.splitIfNeeded();
  634. }
  635. }
  636. }
  637. }
  638. private void writeProxys(SplittingSourceWriter w, ConnectorBundle bundle) {
  639. Set<JClassType> needsProxySupport = bundle.getNeedsProxySupport();
  640. for (JClassType type : needsProxySupport) {
  641. w.print("store.setProxyHandler(");
  642. writeClassLiteral(w, type);
  643. w.print(", new ");
  644. w.print(ProxyHandler.class.getCanonicalName());
  645. w.println("() {");
  646. w.indent();
  647. w.println("public Object createProxy(final "
  648. + InvokationHandler.class.getName() + " handler) {");
  649. w.indent();
  650. w.print("return new ");
  651. w.print(type.getQualifiedSourceName());
  652. w.println("() {");
  653. w.indent();
  654. JMethod[] methods = type.getOverridableMethods();
  655. for (JMethod method : methods) {
  656. if (method.isAbstract()) {
  657. w.print("public ");
  658. w.print(method.getReturnType().getQualifiedSourceName());
  659. w.print(" ");
  660. w.print(method.getName());
  661. w.print("(");
  662. JType[] types = method.getParameterTypes();
  663. for (int i = 0; i < types.length; i++) {
  664. if (i != 0) {
  665. w.print(", ");
  666. }
  667. w.print(types[i].getQualifiedSourceName());
  668. w.print(" p");
  669. w.print(Integer.toString(i));
  670. }
  671. w.println(") {");
  672. w.indent();
  673. if (!method.getReturnType().getQualifiedSourceName()
  674. .equals("void")) {
  675. w.print("return ");
  676. }
  677. w.print("handler.invoke(this, ");
  678. w.print(TypeData.class.getCanonicalName());
  679. w.print(".getType(");
  680. writeClassLiteral(w, type);
  681. w.print(").getMethod(\"");
  682. w.print(escape(method.getName()));
  683. w.print("\"), new Object [] {");
  684. for (int i = 0; i < types.length; i++) {
  685. w.print("p" + i + ", ");
  686. }
  687. w.println("});");
  688. w.outdent();
  689. w.println("}");
  690. }
  691. }
  692. w.outdent();
  693. w.println("};");
  694. w.outdent();
  695. w.println("}");
  696. w.outdent();
  697. w.println("});");
  698. w.splitIfNeeded();
  699. }
  700. }
  701. private void writeParamTypes(SplittingSourceWriter w, ConnectorBundle bundle) {
  702. Map<JClassType, Set<JMethod>> needsParamTypes = bundle
  703. .getNeedsParamTypes();
  704. for (Entry<JClassType, Set<JMethod>> entry : needsParamTypes.entrySet()) {
  705. JClassType type = entry.getKey();
  706. Set<JMethod> methods = entry.getValue();
  707. for (JMethod method : methods) {
  708. w.print("store.setParamTypes(");
  709. writeClassLiteral(w, type);
  710. w.print(", \"");
  711. w.print(escape(method.getName()));
  712. w.print("\", new Type[] {");
  713. for (JType parameter : method.getParameterTypes()) {
  714. ConnectorBundleLoaderFactory.writeTypeCreator(w, parameter);
  715. w.print(", ");
  716. }
  717. w.println("});");
  718. w.splitIfNeeded();
  719. }
  720. }
  721. }
  722. private void writeInvokers(TreeLogger logger, SplittingSourceWriter w,
  723. ConnectorBundle bundle) throws UnableToCompleteException {
  724. Map<JClassType, Set<JMethod>> needsInvoker = bundle.getNeedsInvoker();
  725. for (Entry<JClassType, Set<JMethod>> entry : needsInvoker.entrySet()) {
  726. JClassType type = entry.getKey();
  727. TreeLogger typeLogger = logger.branch(Type.DEBUG,
  728. "Creating invokers for " + type);
  729. Set<JMethod> methods = entry.getValue();
  730. for (JMethod method : methods) {
  731. w.print("store.setInvoker(");
  732. writeClassLiteral(w, type);
  733. w.print(", \"");
  734. w.print(escape(method.getName()));
  735. w.print("\",");
  736. if (method.isPublic()) {
  737. typeLogger.log(Type.DEBUG, "Invoking " + method.getName()
  738. + " using java");
  739. writeJavaInvoker(w, type, method);
  740. } else {
  741. TreeLogger methodLogger = typeLogger.branch(Type.DEBUG,
  742. "Invoking " + method.getName() + " using jsni");
  743. // Must use JSNI to access non-public methods
  744. writeJsniInvoker(methodLogger, w, type, method);
  745. }
  746. w.println(");");
  747. w.splitIfNeeded();
  748. }
  749. }
  750. }
  751. private void writeJsniInvoker(TreeLogger logger, SplittingSourceWriter w,
  752. JClassType type, JMethod method) throws UnableToCompleteException {
  753. w.println("new JsniInvoker() {");
  754. w.indent();
  755. w.println(
  756. "protected native Object jsniInvoke(Object target, %s<Object> params) /*-{ ",
  757. JsArrayObject.class.getName());
  758. w.indent();
  759. JType returnType = method.getReturnType();
  760. boolean hasReturnType = !"void".equals(returnType
  761. .getQualifiedSourceName());
  762. // Note that void is also a primitive type
  763. boolean hasPrimitiveReturnType = hasReturnType
  764. && returnType.isPrimitive() != null;
  765. if (hasReturnType) {
  766. w.print("return ");
  767. if (hasPrimitiveReturnType) {
  768. // Integer.valueOf(expression);
  769. w.print("@%s::valueOf(%s)(", returnType.isPrimitive()
  770. .getQualifiedBoxedSourceName(), returnType
  771. .getJNISignature());
  772. // Implementation tested briefly, but I don't dare leave it
  773. // enabled since we are not using it in the framework and we
  774. // have not tests for it.
  775. logger.log(Type.ERROR,
  776. "JSNI invocation is not yet supported for methods with "
  777. + "primitive return types. Change your method "
  778. + "to public to be able to use conventional"
  779. + " Java invoking instead.");
  780. throw new UnableToCompleteException();
  781. }
  782. }
  783. JType[] parameterTypes = method.getParameterTypes();
  784. w.print("target.@%s::" + method.getName() + "(*)(", method
  785. .getEnclosingType().getQualifiedSourceName());
  786. for (int i = 0; i < parameterTypes.length; i++) {
  787. if (i != 0) {
  788. w.print(", ");
  789. }
  790. w.print("params[" + i + "]");
  791. JPrimitiveType primitive = parameterTypes[i].isPrimitive();
  792. if (primitive != null) {
  793. // param.intValue();
  794. w.print(".@%s::%sValue()()",
  795. primitive.getQualifiedBoxedSourceName(),
  796. primitive.getQualifiedSourceName());
  797. }
  798. }
  799. if (hasPrimitiveReturnType) {
  800. assert hasReturnType;
  801. w.print(")");
  802. }
  803. w.println(");");
  804. if (!hasReturnType) {
  805. w.println("return null;");
  806. }
  807. w.outdent();
  808. w.println("}-*/;");
  809. w.outdent();
  810. w.print("}");
  811. }
  812. private void writeJavaInvoker(SplittingSourceWriter w, JClassType type,
  813. JMethod method) {
  814. w.println("new Invoker() {");
  815. w.indent();
  816. w.println("public Object invoke(Object target, Object[] params) {");
  817. w.indent();
  818. JType returnType = method.getReturnType();
  819. boolean hasReturnType = !"void".equals(returnType
  820. .getQualifiedSourceName());
  821. if (hasReturnType) {
  822. w.print("return ");
  823. }
  824. JType[] parameterTypes = method.getParameterTypes();
  825. w.print("((" + type.getQualifiedSourceName() + ") target)."
  826. + method.getName() + "(");
  827. for (int i = 0; i < parameterTypes.length; i++) {
  828. JType parameterType = parameterTypes[i];
  829. if (i != 0) {
  830. w.print(", ");
  831. }
  832. String parameterTypeName = getBoxedTypeName(parameterType);
  833. if (parameterTypeName.startsWith("elemental.json.Json")) {
  834. // Need to pass through native method to allow casting Object to
  835. // JSO if the value is a string
  836. w.print("%s.<%s>obj2jso(params[%d])",
  837. JsonDecoder.class.getCanonicalName(),
  838. parameterTypeName, i);
  839. } else {
  840. w.print("(" + parameterTypeName + ") params[" + i + "]");
  841. }
  842. }
  843. w.println(");");
  844. if (!hasReturnType) {
  845. w.println("return null;");
  846. }
  847. w.outdent();
  848. w.println("}");
  849. w.outdent();
  850. w.print("}");
  851. }
  852. private void writeReturnTypes(SplittingSourceWriter w,
  853. ConnectorBundle bundle) {
  854. Map<JClassType, Set<JMethod>> methodReturnTypes = bundle
  855. .getMethodReturnTypes();
  856. for (Entry<JClassType, Set<JMethod>> entry : methodReturnTypes
  857. .entrySet()) {
  858. JClassType type = entry.getKey();
  859. Set<JMethod> methods = entry.getValue();
  860. for (JMethod method : methods) {
  861. // setReturnType(Class<?> type, String methodName, Type
  862. // returnType)
  863. w.print("store.setReturnType(");
  864. writeClassLiteral(w, type);
  865. w.print(", \"");
  866. w.print(escape(method.getName()));
  867. w.print("\", ");
  868. writeTypeCreator(w, method.getReturnType());
  869. w.println(");");
  870. w.splitIfNeeded();
  871. }
  872. }
  873. }
  874. private void writeGwtConstructors(SplittingSourceWriter w,
  875. ConnectorBundle bundle) {
  876. Set<JClassType> constructors = bundle.getGwtConstructors();
  877. for (JClassType type : constructors) {
  878. w.print("store.setConstructor(");
  879. writeClassLiteral(w, type);
  880. w.println(", new Invoker() {");
  881. w.indent();
  882. w.println("public Object invoke(Object target, Object[] params) {");
  883. w.indent();
  884. w.print("return ");
  885. w.print(GWT.class.getName());
  886. w.print(".create(");
  887. writeClassLiteral(w, type);
  888. w.println(");");
  889. w.outdent();
  890. w.println("}");
  891. w.outdent();
  892. w.println("});");
  893. w.splitIfNeeded();
  894. }
  895. }
  896. public static void writeClassLiteral(SourceWriter w, JType type) {
  897. w.print(getClassLiteralString(type));
  898. }
  899. public static String getClassLiteralString(JType type) {
  900. return type.getQualifiedSourceName() + ".class";
  901. }
  902. private void writeIdentifiers(SplittingSourceWriter w,
  903. ConnectorBundle bundle) {
  904. Map<JClassType, Set<String>> identifiers = bundle.getIdentifiers();
  905. for (Entry<JClassType, Set<String>> entry : identifiers.entrySet()) {
  906. Set<String> ids = entry.getValue();
  907. JClassType type = entry.getKey();
  908. for (String id : ids) {
  909. w.print("store.setClass(\"");
  910. w.print(escape(id));
  911. w.print("\", ");
  912. writeClassLiteral(w, type);
  913. w.println(");");
  914. w.splitIfNeeded();
  915. }
  916. }
  917. }
  918. private List<ConnectorBundle> buildBundles(TreeLogger logger,
  919. TypeOracle typeOracle) throws NotFoundException,
  920. UnableToCompleteException {
  921. Map<LoadStyle, Collection<JClassType>> connectorsByLoadStyle = new HashMap<LoadStyle, Collection<JClassType>>();
  922. for (LoadStyle loadStyle : LoadStyle.values()) {
  923. connectorsByLoadStyle.put(loadStyle, new ArrayList<JClassType>());
  924. }
  925. // Find all types with a valid mapping
  926. Collection<JClassType> selectedTypes = getConnectorsForWidgetset(
  927. logger, typeOracle);
  928. // Group by load style
  929. for (JClassType connectorSubtype : selectedTypes) {
  930. LoadStyle loadStyle = getLoadStyle(connectorSubtype);
  931. if (loadStyle != null) {
  932. connectorsByLoadStyle.get(loadStyle).add(connectorSubtype);
  933. }
  934. }
  935. List<ConnectorBundle> bundles = new ArrayList<ConnectorBundle>();
  936. Collection<TypeVisitor> visitors = getVisitors(typeOracle);
  937. ConnectorBundle eagerBundle = new ConnectorBundle(
  938. ConnectorBundleLoader.EAGER_BUNDLE_NAME, visitors, typeOracle);
  939. TreeLogger eagerLogger = logger.branch(Type.TRACE,
  940. "Populating eager bundle");
  941. // Eager connectors and all RPC interfaces are loaded by default
  942. eagerBundle.processTypes(eagerLogger,
  943. connectorsByLoadStyle.get(LoadStyle.EAGER));
  944. eagerBundle.processType(eagerLogger, typeOracle
  945. .findType(UnknownComponentConnector.class.getCanonicalName()));
  946. eagerBundle.processSubTypes(eagerLogger,
  947. typeOracle.getType(ClientRpc.class.getName()));
  948. eagerBundle.processSubTypes(eagerLogger,
  949. typeOracle.getType(ServerRpc.class.getName()));
  950. bundles.add(eagerBundle);
  951. ConnectorBundle deferredBundle = new ConnectorBundle(
  952. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME, eagerBundle);
  953. TreeLogger deferredLogger = logger.branch(Type.TRACE,
  954. "Populating deferred bundle");
  955. deferredBundle.processTypes(deferredLogger,
  956. connectorsByLoadStyle.get(LoadStyle.DEFERRED));
  957. bundles.add(deferredBundle);
  958. Collection<JClassType> lazy = connectorsByLoadStyle.get(LoadStyle.LAZY);
  959. for (JClassType type : lazy) {
  960. ConnectorBundle bundle = new ConnectorBundle(type.getName(),
  961. eagerBundle);
  962. TreeLogger subLogger = logger.branch(Type.TRACE, "Populating "
  963. + type.getName() + " bundle");
  964. bundle.processType(subLogger, type);
  965. bundles.add(bundle);
  966. }
  967. return bundles;
  968. }
  969. /**
  970. * Returns the connector types that should be included in the widgetset.
  971. * This method can be overridden to create a widgetset only containing
  972. * selected connectors.
  973. * <p>
  974. * The default implementation finds all type implementing
  975. * {@link ServerConnector} that have a @{@link Connect} annotation. It also
  976. * checks that multiple connectors aren't connected to the same server-side
  977. * class.
  978. *
  979. * @param logger
  980. * the logger to which information can be logged
  981. * @param typeOracle
  982. * the type oracle that can be used for finding types
  983. * @return a collection of all the connector types that should be included
  984. * in the widgetset
  985. * @throws UnableToCompleteException
  986. * if the operation fails
  987. */
  988. protected Collection<JClassType> getConnectorsForWidgetset(
  989. TreeLogger logger, TypeOracle typeOracle)
  990. throws UnableToCompleteException {
  991. JClassType serverConnectorType;
  992. try {
  993. serverConnectorType = typeOracle.getType(ServerConnector.class
  994. .getName());
  995. } catch (NotFoundException e) {
  996. logger.log(Type.ERROR,
  997. "Can't find " + ServerConnector.class.getName());
  998. throw new UnableToCompleteException();
  999. }
  1000. JClassType[] types = serverConnectorType.getSubtypes();
  1001. Map<String, JClassType> mappings = new TreeMap<String, JClassType>();
  1002. // Keep track of what has happened to avoid logging intermediate state
  1003. Map<JClassType, List<JClassType>> replaced = new TreeMap<JClassType, List<JClassType>>(
  1004. ConnectorBundle.jClassComparator);
  1005. for (JClassType type : types) {
  1006. Connect connectAnnotation = type.getAnnotation(Connect.class);
  1007. if (connectAnnotation == null) {
  1008. continue;
  1009. }
  1010. String identifier = connectAnnotation.value().getCanonicalName();
  1011. JClassType previousMapping = mappings.put(identifier, type);
  1012. if (previousMapping != null) {
  1013. // There are multiple mappings, pick the subclass
  1014. JClassType subclass;
  1015. JClassType superclass;
  1016. if (previousMapping.isAssignableFrom(type)) {
  1017. subclass = type;
  1018. superclass = previousMapping;
  1019. } else if (type.isAssignableFrom(previousMapping)) {
  1020. subclass = previousMapping;
  1021. superclass = type;
  1022. } else {
  1023. // Neither inherits from the other - this is a conflict
  1024. logger.log(
  1025. Type.ERROR,
  1026. "Conflicting @Connect mappings detected for "
  1027. + identifier
  1028. + ": "
  1029. + type.getQualifiedSourceName()
  1030. + " and "
  1031. + previousMapping.getQualifiedSourceName()
  1032. + ". There can only be multiple @Connect mappings for the same server-side type if one is the subclass of the other.");
  1033. throw new UnableToCompleteException();
  1034. }
  1035. mappings.put(identifier, subclass);
  1036. // Inherit any previous replacements
  1037. List<JClassType> previousReplacements = replaced
  1038. .remove(superclass);
  1039. if (previousReplacements == null) {
  1040. previousReplacements = new ArrayList<JClassType>();
  1041. }
  1042. previousReplacements.add(superclass);
  1043. replaced.put(subclass, previousReplacements);
  1044. }
  1045. }
  1046. // Log the final set of replacements
  1047. for (Entry<JClassType, List<JClassType>> entry : replaced.entrySet()) {
  1048. String msg = entry.getKey().getQualifiedSourceName() + " replaces ";
  1049. List<JClassType> list = entry.getValue();
  1050. for (int i = 0; i < list.size(); i++) {
  1051. if (i != 0) {
  1052. msg += ", ";
  1053. }
  1054. msg += list.get(i).getQualifiedSourceName();
  1055. }
  1056. logger.log(Type.INFO, msg);
  1057. }
  1058. // Return the types of the final mapping
  1059. return mappings.values();
  1060. }
  1061. private Collection<TypeVisitor> getVisitors(TypeOracle oracle)
  1062. throws NotFoundException {
  1063. List<TypeVisitor> visitors = Arrays.<TypeVisitor> asList(
  1064. new ConnectorInitVisitor(), new StateInitVisitor(),
  1065. new WidgetInitVisitor(), new RendererVisitor(),
  1066. new ClientRpcVisitor(), new ServerRpcVisitor(),
  1067. new OnStateChangeVisitor());
  1068. for (TypeVisitor typeVisitor : visitors) {
  1069. typeVisitor.init(oracle);
  1070. }
  1071. return visitors;
  1072. }
  1073. protected LoadStyle getLoadStyle(JClassType connectorType) {
  1074. Connect annotation = connectorType.getAnnotation(Connect.class);
  1075. return annotation.loadStyle();
  1076. }
  1077. public static String getBoxedTypeName(JType type) {
  1078. if (type.isPrimitive() != null) {
  1079. // Used boxed types for primitives
  1080. return type.isPrimitive().getQualifiedBoxedSourceName();
  1081. } else {
  1082. return type.getErasedType().getQualifiedSourceName();
  1083. }
  1084. }
  1085. public static void writeTypeCreator(SourceWriter sourceWriter, JType type) {
  1086. String typeName = ConnectorBundleLoaderFactory.getBoxedTypeName(type);
  1087. JParameterizedType parameterized = type.isParameterized();
  1088. if (parameterized != null) {
  1089. sourceWriter.print("new Type(\"" + typeName + "\", ");
  1090. sourceWriter.print("new Type[] {");
  1091. JClassType[] typeArgs = parameterized.getTypeArgs();
  1092. for (JClassType jClassType : typeArgs) {
  1093. writeTypeCreator(sourceWriter, jClassType);
  1094. sourceWriter.print(", ");
  1095. }
  1096. sourceWriter.print("}");
  1097. } else {
  1098. sourceWriter.print("new Type(" + typeName + ".class");
  1099. }
  1100. sourceWriter.print(")");
  1101. }
  1102. }