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 45KB

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