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

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