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

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