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

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