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