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.

JsonPaintTarget.java 33KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.server;
  5. import java.io.BufferedReader;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.io.PrintWriter;
  11. import java.io.Serializable;
  12. import java.util.Collection;
  13. import java.util.HashMap;
  14. import java.util.HashSet;
  15. import java.util.Iterator;
  16. import java.util.LinkedList;
  17. import java.util.Map;
  18. import java.util.Set;
  19. import java.util.Stack;
  20. import java.util.Vector;
  21. import com.vaadin.Application;
  22. import com.vaadin.terminal.ApplicationResource;
  23. import com.vaadin.terminal.ExternalResource;
  24. import com.vaadin.terminal.PaintException;
  25. import com.vaadin.terminal.PaintTarget;
  26. import com.vaadin.terminal.Paintable;
  27. import com.vaadin.terminal.Resource;
  28. import com.vaadin.terminal.ThemeResource;
  29. import com.vaadin.terminal.VariableOwner;
  30. import com.vaadin.ui.Alignment;
  31. import com.vaadin.ui.ClientWidget;
  32. import com.vaadin.ui.Component;
  33. import com.vaadin.ui.CustomLayout;
  34. /**
  35. * User Interface Description Language Target.
  36. *
  37. * TODO document better: role of this class, UIDL format, attributes, variables,
  38. * etc.
  39. *
  40. * @author IT Mill Ltd.
  41. * @version
  42. * @VERSION@
  43. * @since 5.0
  44. */
  45. @SuppressWarnings("serial")
  46. public class JsonPaintTarget implements PaintTarget {
  47. /* Document type declarations */
  48. private final static String UIDL_ARG_NAME = "name";
  49. private final Stack<String> mOpenTags;
  50. private final Stack<JsonTag> openJsonTags;
  51. private final PrintWriter uidlBuffer;
  52. private boolean closed = false;
  53. private final AbstractCommunicationManager manager;
  54. private int changes = 0;
  55. private Set<Object> usedResources = new HashSet<Object>();
  56. private boolean customLayoutArgumentsOpen = false;
  57. private JsonTag tag;
  58. private int errorsOpen;
  59. private boolean cacheEnabled = false;
  60. private Collection<Paintable> paintedComponents = new HashSet<Paintable>();
  61. private Collection<Paintable> identifiersCreatedDueRefPaint;
  62. private Collection<Class<? extends Paintable>> usedPaintableTypes = new LinkedList<Class<? extends Paintable>>();
  63. /**
  64. * Creates a new XMLPrintWriter, without automatic line flushing.
  65. *
  66. * @param variableMap
  67. * @param manager
  68. * @param outWriter
  69. * A character-output stream.
  70. * @throws PaintException
  71. * if the paint operation failed.
  72. */
  73. public JsonPaintTarget(AbstractCommunicationManager manager,
  74. PrintWriter outWriter, boolean cachingRequired)
  75. throws PaintException {
  76. this.manager = manager;
  77. // Sets the target for UIDL writing
  78. uidlBuffer = outWriter;
  79. // Initialize tag-writing
  80. mOpenTags = new Stack<String>();
  81. openJsonTags = new Stack<JsonTag>();
  82. cacheEnabled = cachingRequired;
  83. }
  84. public void startTag(String tagName) throws PaintException {
  85. startTag(tagName, false);
  86. }
  87. /**
  88. * Prints the element start tag.
  89. *
  90. * <pre>
  91. * Todo:
  92. * Checking of input values
  93. *
  94. * </pre>
  95. *
  96. * @param tagName
  97. * the name of the start tag.
  98. * @throws PaintException
  99. * if the paint operation failed.
  100. *
  101. */
  102. public void startTag(String tagName, boolean isChildNode)
  103. throws PaintException {
  104. // In case of null data output nothing:
  105. if (tagName == null) {
  106. throw new NullPointerException();
  107. }
  108. // Ensures that the target is open
  109. if (closed) {
  110. throw new PaintException(
  111. "Attempted to write to a closed PaintTarget.");
  112. }
  113. if (tag != null) {
  114. openJsonTags.push(tag);
  115. }
  116. // Checks tagName and attributes here
  117. mOpenTags.push(tagName);
  118. tag = new JsonTag(tagName);
  119. if ("error".equals(tagName)) {
  120. errorsOpen++;
  121. }
  122. customLayoutArgumentsOpen = false;
  123. }
  124. /**
  125. * Prints the element end tag.
  126. *
  127. * If the parent tag is closed before every child tag is closed an
  128. * PaintException is raised.
  129. *
  130. * @param tag
  131. * the name of the end tag.
  132. * @throws Paintexception
  133. * if the paint operation failed.
  134. */
  135. public void endTag(String tagName) throws PaintException {
  136. // In case of null data output nothing:
  137. if (tagName == null) {
  138. throw new NullPointerException();
  139. }
  140. // Ensure that the target is open
  141. if (closed) {
  142. throw new PaintException(
  143. "Attempted to write to a closed PaintTarget.");
  144. }
  145. if (openJsonTags.size() > 0) {
  146. final JsonTag parent = openJsonTags.pop();
  147. String lastTag = "";
  148. lastTag = mOpenTags.pop();
  149. if (!tagName.equalsIgnoreCase(lastTag)) {
  150. throw new PaintException("Invalid UIDL: wrong ending tag: '"
  151. + tagName + "' expected: '" + lastTag + "'.");
  152. }
  153. // simple hack which writes error uidl structure into attribute
  154. if ("error".equals(lastTag)) {
  155. if (errorsOpen == 1) {
  156. parent.addAttribute("\"error\":[\"error\",{}"
  157. + tag.getData() + "]");
  158. } else {
  159. // sub error
  160. parent.addData(tag.getJSON());
  161. }
  162. errorsOpen--;
  163. } else {
  164. parent.addData(tag.getJSON());
  165. }
  166. tag = parent;
  167. } else {
  168. changes++;
  169. uidlBuffer.print(((changes > 1) ? "," : "") + tag.getJSON());
  170. tag = null;
  171. }
  172. }
  173. /**
  174. * Substitutes the XML sensitive characters with predefined XML entities.
  175. *
  176. * @param xml
  177. * the String to be substituted.
  178. * @return A new string instance where all occurrences of XML sensitive
  179. * characters are substituted with entities.
  180. */
  181. static public String escapeXML(String xml) {
  182. if (xml == null || xml.length() <= 0) {
  183. return "";
  184. }
  185. return escapeXML(new StringBuilder(xml)).toString();
  186. }
  187. /**
  188. * Substitutes the XML sensitive characters with predefined XML entities.
  189. *
  190. * @param xml
  191. * the String to be substituted.
  192. * @return A new StringBuilder instance where all occurrences of XML
  193. * sensitive characters are substituted with entities.
  194. *
  195. */
  196. static StringBuilder escapeXML(StringBuilder xml) {
  197. if (xml == null || xml.length() <= 0) {
  198. return new StringBuilder("");
  199. }
  200. final StringBuilder result = new StringBuilder(xml.length() * 2);
  201. for (int i = 0; i < xml.length(); i++) {
  202. final char c = xml.charAt(i);
  203. final String s = toXmlChar(c);
  204. if (s != null) {
  205. result.append(s);
  206. } else {
  207. result.append(c);
  208. }
  209. }
  210. return result;
  211. }
  212. static public String escapeJSON(String s) {
  213. if (s == null) {
  214. return "";
  215. }
  216. final StringBuilder sb = new StringBuilder();
  217. for (int i = 0; i < s.length(); i++) {
  218. final char ch = s.charAt(i);
  219. switch (ch) {
  220. case '"':
  221. sb.append("\\\"");
  222. break;
  223. case '\\':
  224. sb.append("\\\\");
  225. break;
  226. case '\b':
  227. sb.append("\\b");
  228. break;
  229. case '\f':
  230. sb.append("\\f");
  231. break;
  232. case '\n':
  233. sb.append("\\n");
  234. break;
  235. case '\r':
  236. sb.append("\\r");
  237. break;
  238. case '\t':
  239. sb.append("\\t");
  240. break;
  241. case '/':
  242. sb.append("\\/");
  243. break;
  244. default:
  245. if (ch >= '\u0000' && ch <= '\u001F') {
  246. final String ss = Integer.toHexString(ch);
  247. sb.append("\\u");
  248. for (int k = 0; k < 4 - ss.length(); k++) {
  249. sb.append('0');
  250. }
  251. sb.append(ss.toUpperCase());
  252. } else {
  253. sb.append(ch);
  254. }
  255. }
  256. }
  257. return sb.toString();
  258. }
  259. /**
  260. * Substitutes a XML sensitive character with predefined XML entity.
  261. *
  262. * @param c
  263. * the Character to be replaced with an entity.
  264. * @return String of the entity or null if character is not to be replaced
  265. * with an entity.
  266. */
  267. private static String toXmlChar(char c) {
  268. switch (c) {
  269. case '&':
  270. return "&amp;"; // & => &amp;
  271. case '>':
  272. return "&gt;"; // > => &gt;
  273. case '<':
  274. return "&lt;"; // < => &lt;
  275. case '"':
  276. return "&quot;"; // " => &quot;
  277. case '\'':
  278. return "&apos;"; // ' => &apos;
  279. default:
  280. return null;
  281. }
  282. }
  283. /**
  284. * Prints XML-escaped text.
  285. *
  286. * @param str
  287. * @throws PaintException
  288. * if the paint operation failed.
  289. *
  290. */
  291. public void addText(String str) throws PaintException {
  292. tag.addData("\"" + escapeJSON(str) + "\"");
  293. }
  294. public void addAttribute(String name, boolean value) throws PaintException {
  295. tag.addAttribute("\"" + name + "\":" + (value ? "true" : "false"));
  296. }
  297. public void addAttribute(String name, Resource value) throws PaintException {
  298. if (value instanceof ExternalResource) {
  299. addAttribute(name, ((ExternalResource) value).getURL());
  300. } else if (value instanceof ApplicationResource) {
  301. final ApplicationResource r = (ApplicationResource) value;
  302. final Application a = r.getApplication();
  303. if (a == null) {
  304. throw new PaintException(
  305. "Application not specified for resorce "
  306. + value.getClass().getName());
  307. }
  308. String uri;
  309. if (a.getURL() != null) {
  310. uri = a.getURL().getPath();
  311. } else {
  312. uri = "";
  313. }
  314. if (uri.length() > 0 && uri.charAt(uri.length() - 1) != '/') {
  315. uri += "/";
  316. }
  317. uri += a.getRelativeLocation(r);
  318. addAttribute(name, uri);
  319. } else if (value instanceof ThemeResource) {
  320. final String uri = "theme://"
  321. + ((ThemeResource) value).getResourceId();
  322. addAttribute(name, uri);
  323. } else {
  324. throw new PaintException("Ajax adapter does not "
  325. + "support resources of type: "
  326. + value.getClass().getName());
  327. }
  328. }
  329. public void addAttribute(String name, int value) throws PaintException {
  330. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  331. }
  332. public void addAttribute(String name, long value) throws PaintException {
  333. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  334. }
  335. public void addAttribute(String name, float value) throws PaintException {
  336. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  337. }
  338. public void addAttribute(String name, double value) throws PaintException {
  339. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  340. }
  341. public void addAttribute(String name, String value) throws PaintException {
  342. // In case of null data output nothing:
  343. if ((value == null) || (name == null)) {
  344. throw new NullPointerException(
  345. "Parameters must be non-null strings");
  346. }
  347. tag.addAttribute("\"" + name + "\": \"" + escapeJSON(value) + "\"");
  348. if (customLayoutArgumentsOpen && "template".equals(name)) {
  349. getUsedResources().add("layouts/" + value + ".html");
  350. }
  351. if (name.equals("locale")) {
  352. manager.requireLocale(value);
  353. }
  354. }
  355. public void addAttribute(String name, Paintable value)
  356. throws PaintException {
  357. final String id = getPaintIdentifier(value);
  358. addAttribute(name, id);
  359. }
  360. public void addAttribute(String name, Map<?, ?> value)
  361. throws PaintException {
  362. StringBuilder sb = new StringBuilder();
  363. sb.append("\"");
  364. sb.append(name);
  365. sb.append("\": ");
  366. sb.append("{");
  367. for (Iterator<?> it = value.keySet().iterator(); it.hasNext();) {
  368. Object key = it.next();
  369. Object mapValue = value.get(key);
  370. sb.append("\"");
  371. if (key instanceof Paintable) {
  372. Paintable paintable = (Paintable) key;
  373. sb.append(getPaintIdentifier(paintable));
  374. } else {
  375. sb.append(escapeJSON(key.toString()));
  376. }
  377. sb.append("\":");
  378. if (mapValue instanceof Float || mapValue instanceof Integer
  379. || mapValue instanceof Double
  380. || mapValue instanceof Boolean
  381. || mapValue instanceof Alignment) {
  382. sb.append(mapValue);
  383. } else {
  384. sb.append("\"");
  385. sb.append(escapeJSON(mapValue.toString()));
  386. sb.append("\"");
  387. }
  388. if (it.hasNext()) {
  389. sb.append(",");
  390. }
  391. }
  392. sb.append("}");
  393. tag.addAttribute(sb.toString());
  394. }
  395. public void addAttribute(String name, Object[] values) {
  396. // In case of null data output nothing:
  397. if ((values == null) || (name == null)) {
  398. throw new NullPointerException(
  399. "Parameters must be non-null strings");
  400. }
  401. final StringBuilder buf = new StringBuilder();
  402. buf.append("\"" + name + "\":[");
  403. for (int i = 0; i < values.length; i++) {
  404. if (i > 0) {
  405. buf.append(",");
  406. }
  407. buf.append("\"");
  408. buf.append(escapeJSON(values[i].toString()));
  409. buf.append("\"");
  410. }
  411. buf.append("]");
  412. tag.addAttribute(buf.toString());
  413. }
  414. public void addVariable(VariableOwner owner, String name, String value)
  415. throws PaintException {
  416. tag.addVariable(new StringVariable(owner, name, escapeJSON(value)));
  417. }
  418. public void addVariable(VariableOwner owner, String name, Paintable value)
  419. throws PaintException {
  420. tag.addVariable(new StringVariable(owner, name,
  421. getPaintIdentifier(value)));
  422. }
  423. public void addVariable(VariableOwner owner, String name, int value)
  424. throws PaintException {
  425. tag.addVariable(new IntVariable(owner, name, value));
  426. }
  427. public void addVariable(VariableOwner owner, String name, long value)
  428. throws PaintException {
  429. tag.addVariable(new LongVariable(owner, name, value));
  430. }
  431. public void addVariable(VariableOwner owner, String name, float value)
  432. throws PaintException {
  433. tag.addVariable(new FloatVariable(owner, name, value));
  434. }
  435. public void addVariable(VariableOwner owner, String name, double value)
  436. throws PaintException {
  437. tag.addVariable(new DoubleVariable(owner, name, value));
  438. }
  439. public void addVariable(VariableOwner owner, String name, boolean value)
  440. throws PaintException {
  441. tag.addVariable(new BooleanVariable(owner, name, value));
  442. }
  443. public void addVariable(VariableOwner owner, String name, String[] value)
  444. throws PaintException {
  445. tag.addVariable(new ArrayVariable(owner, name, value));
  446. }
  447. /**
  448. * Adds a upload stream type variable.
  449. *
  450. * TODO not converted for JSON
  451. *
  452. * @param owner
  453. * the Listener for variable changes.
  454. * @param name
  455. * the Variable name.
  456. *
  457. * @throws PaintException
  458. * if the paint operation failed.
  459. */
  460. public void addUploadStreamVariable(VariableOwner owner, String name)
  461. throws PaintException {
  462. startTag("uploadstream");
  463. addAttribute(UIDL_ARG_NAME, name);
  464. endTag("uploadstream");
  465. }
  466. /**
  467. * Prints the single text section.
  468. *
  469. * Prints full text section. The section data is escaped
  470. *
  471. * @param sectionTagName
  472. * the name of the tag.
  473. * @param sectionData
  474. * the section data to be printed.
  475. * @throws PaintException
  476. * if the paint operation failed.
  477. */
  478. public void addSection(String sectionTagName, String sectionData)
  479. throws PaintException {
  480. tag.addData("{\"" + sectionTagName + "\":\"" + escapeJSON(sectionData)
  481. + "\"}");
  482. }
  483. /**
  484. * Adds XML directly to UIDL.
  485. *
  486. * @param xml
  487. * the Xml to be added.
  488. * @throws PaintException
  489. * if the paint operation failed.
  490. */
  491. public void addUIDL(String xml) throws PaintException {
  492. // Ensure that the target is open
  493. if (closed) {
  494. throw new PaintException(
  495. "Attempted to write to a closed PaintTarget.");
  496. }
  497. // Make sure that the open start tag is closed before
  498. // anything is written.
  499. // Escape and write what was given
  500. if (xml != null) {
  501. tag.addData("\"" + escapeJSON(xml) + "\"");
  502. }
  503. }
  504. /**
  505. * Adds XML section with namespace.
  506. *
  507. * @param sectionTagName
  508. * the name of the tag.
  509. * @param sectionData
  510. * the section data.
  511. * @param namespace
  512. * the namespace to be added.
  513. * @throws PaintException
  514. * if the paint operation failed.
  515. *
  516. * @see com.vaadin.terminal.PaintTarget#addXMLSection(String, String,
  517. * String)
  518. */
  519. public void addXMLSection(String sectionTagName, String sectionData,
  520. String namespace) throws PaintException {
  521. // Ensure that the target is open
  522. if (closed) {
  523. throw new PaintException(
  524. "Attempted to write to a closed PaintTarget.");
  525. }
  526. startTag(sectionTagName);
  527. if (namespace != null) {
  528. addAttribute("xmlns", namespace);
  529. }
  530. if (sectionData != null) {
  531. tag.addData("\"" + escapeJSON(sectionData) + "\"");
  532. }
  533. endTag(sectionTagName);
  534. }
  535. /**
  536. * Gets the UIDL already printed to stream. Paint target must be closed
  537. * before the <code>getUIDL</code> can be called.
  538. *
  539. * @return the UIDL.
  540. */
  541. public String getUIDL() {
  542. if (closed) {
  543. return uidlBuffer.toString();
  544. }
  545. throw new IllegalStateException(
  546. "Tried to read UIDL from open PaintTarget");
  547. }
  548. /**
  549. * Closes the paint target. Paint target must be closed before the
  550. * <code>getUIDL</code> can be called. Subsequent attempts to write to paint
  551. * target. If the target was already closed, call to this function is
  552. * ignored. will generate an exception.
  553. *
  554. * @throws PaintException
  555. * if the paint operation failed.
  556. */
  557. public void close() throws PaintException {
  558. if (tag != null) {
  559. uidlBuffer.write(tag.getJSON());
  560. }
  561. flush();
  562. closed = true;
  563. }
  564. /**
  565. * Method flush.
  566. */
  567. private void flush() {
  568. uidlBuffer.flush();
  569. }
  570. /*
  571. * (non-Javadoc)
  572. *
  573. * @see com.vaadin.terminal.PaintTarget#startTag(com.vaadin.terminal
  574. * .Paintable, java.lang.String)
  575. */
  576. public boolean startTag(Paintable paintable, String tagName)
  577. throws PaintException {
  578. startTag(tagName, true);
  579. final boolean isPreviouslyPainted = manager.hasPaintableId(paintable)
  580. && (identifiersCreatedDueRefPaint == null || !identifiersCreatedDueRefPaint
  581. .contains(paintable));
  582. final String id = manager.getPaintableId(paintable);
  583. paintable.addListener(manager);
  584. addAttribute("id", id);
  585. paintedComponents.add(paintable);
  586. if (paintable instanceof CustomLayout) {
  587. customLayoutArgumentsOpen = true;
  588. }
  589. return cacheEnabled && isPreviouslyPainted;
  590. }
  591. @Deprecated
  592. public void paintReference(Paintable paintable, String referenceName)
  593. throws PaintException {
  594. addAttribute(referenceName, paintable);
  595. }
  596. public String getPaintIdentifier(Paintable paintable) throws PaintException {
  597. if (!manager.hasPaintableId(paintable)) {
  598. if (identifiersCreatedDueRefPaint == null) {
  599. identifiersCreatedDueRefPaint = new HashSet<Paintable>();
  600. }
  601. identifiersCreatedDueRefPaint.add(paintable);
  602. }
  603. return manager.getPaintableId(paintable);
  604. }
  605. /*
  606. * (non-Javadoc)
  607. *
  608. * @see com.vaadin.terminal.PaintTarget#addCharacterData(java.lang.String )
  609. */
  610. public void addCharacterData(String text) throws PaintException {
  611. if (text != null) {
  612. tag.addData(text);
  613. }
  614. }
  615. /**
  616. * This is basically a container for UI components variables, that will be
  617. * added at the end of JSON object.
  618. *
  619. * @author mattitahvonen
  620. *
  621. */
  622. class JsonTag implements Serializable {
  623. boolean firstField = false;
  624. Vector<Object> variables = new Vector<Object>();
  625. Vector<Object> children = new Vector<Object>();
  626. Vector<Object> attr = new Vector<Object>();
  627. StringBuilder data = new StringBuilder();
  628. public boolean childrenArrayOpen = false;
  629. private boolean childNode = false;
  630. private boolean tagClosed = false;
  631. public JsonTag(String tagName) {
  632. data.append("[\"" + tagName + "\"");
  633. }
  634. private void closeTag() {
  635. if (!tagClosed) {
  636. data.append(attributesAsJsonObject());
  637. data.append(getData());
  638. // Writes the end (closing) tag
  639. data.append("]");
  640. tagClosed = true;
  641. }
  642. }
  643. public String getJSON() {
  644. if (!tagClosed) {
  645. closeTag();
  646. }
  647. return data.toString();
  648. }
  649. public void openChildrenArray() {
  650. if (!childrenArrayOpen) {
  651. // append("c : [");
  652. childrenArrayOpen = true;
  653. // firstField = true;
  654. }
  655. }
  656. public void closeChildrenArray() {
  657. // append("]");
  658. // firstField = false;
  659. }
  660. public void setChildNode(boolean b) {
  661. childNode = b;
  662. }
  663. public boolean isChildNode() {
  664. return childNode;
  665. }
  666. public String startField() {
  667. if (firstField) {
  668. firstField = false;
  669. return "";
  670. } else {
  671. return ",";
  672. }
  673. }
  674. /**
  675. *
  676. * @param s
  677. * json string, object or array
  678. */
  679. public void addData(String s) {
  680. children.add(s);
  681. }
  682. public String getData() {
  683. final StringBuilder buf = new StringBuilder();
  684. final Iterator<Object> it = children.iterator();
  685. while (it.hasNext()) {
  686. buf.append(startField());
  687. buf.append(it.next());
  688. }
  689. return buf.toString();
  690. }
  691. public void addAttribute(String jsonNode) {
  692. attr.add(jsonNode);
  693. }
  694. private String attributesAsJsonObject() {
  695. final StringBuilder buf = new StringBuilder();
  696. buf.append(startField());
  697. buf.append("{");
  698. for (final Iterator<Object> iter = attr.iterator(); iter.hasNext();) {
  699. final String element = (String) iter.next();
  700. buf.append(element);
  701. if (iter.hasNext()) {
  702. buf.append(",");
  703. }
  704. }
  705. buf.append(tag.variablesAsJsonObject());
  706. buf.append("}");
  707. return buf.toString();
  708. }
  709. public void addVariable(Variable v) {
  710. variables.add(v);
  711. }
  712. private String variablesAsJsonObject() {
  713. if (variables.size() == 0) {
  714. return "";
  715. }
  716. final StringBuilder buf = new StringBuilder();
  717. buf.append(startField());
  718. buf.append("\"v\":{");
  719. final Iterator<Object> iter = variables.iterator();
  720. while (iter.hasNext()) {
  721. final Variable element = (Variable) iter.next();
  722. buf.append(element.getJsonPresentation());
  723. if (iter.hasNext()) {
  724. buf.append(",");
  725. }
  726. }
  727. buf.append("}");
  728. return buf.toString();
  729. }
  730. class TagCounter {
  731. int count;
  732. public TagCounter() {
  733. count = 0;
  734. }
  735. public void increment() {
  736. count++;
  737. }
  738. public String postfix(String s) {
  739. if (count > 0) {
  740. return s + count;
  741. }
  742. return s;
  743. }
  744. }
  745. }
  746. abstract class Variable implements Serializable {
  747. String name;
  748. public abstract String getJsonPresentation();
  749. }
  750. class BooleanVariable extends Variable implements Serializable {
  751. boolean value;
  752. public BooleanVariable(VariableOwner owner, String name, boolean v) {
  753. value = v;
  754. this.name = name;
  755. }
  756. @Override
  757. public String getJsonPresentation() {
  758. return "\"" + name + "\":" + (value == true ? "true" : "false");
  759. }
  760. }
  761. class StringVariable extends Variable implements Serializable {
  762. String value;
  763. public StringVariable(VariableOwner owner, String name, String v) {
  764. value = v;
  765. this.name = name;
  766. }
  767. @Override
  768. public String getJsonPresentation() {
  769. return "\"" + name + "\":\"" + value + "\"";
  770. }
  771. }
  772. class IntVariable extends Variable implements Serializable {
  773. int value;
  774. public IntVariable(VariableOwner owner, String name, int v) {
  775. value = v;
  776. this.name = name;
  777. }
  778. @Override
  779. public String getJsonPresentation() {
  780. return "\"" + name + "\":" + value;
  781. }
  782. }
  783. class LongVariable extends Variable implements Serializable {
  784. long value;
  785. public LongVariable(VariableOwner owner, String name, long v) {
  786. value = v;
  787. this.name = name;
  788. }
  789. @Override
  790. public String getJsonPresentation() {
  791. return "\"" + name + "\":" + value;
  792. }
  793. }
  794. class FloatVariable extends Variable implements Serializable {
  795. float value;
  796. public FloatVariable(VariableOwner owner, String name, float v) {
  797. value = v;
  798. this.name = name;
  799. }
  800. @Override
  801. public String getJsonPresentation() {
  802. return "\"" + name + "\":" + value;
  803. }
  804. }
  805. class DoubleVariable extends Variable implements Serializable {
  806. double value;
  807. public DoubleVariable(VariableOwner owner, String name, double v) {
  808. value = v;
  809. this.name = name;
  810. }
  811. @Override
  812. public String getJsonPresentation() {
  813. return "\"" + name + "\":" + value;
  814. }
  815. }
  816. class ArrayVariable extends Variable implements Serializable {
  817. String[] value;
  818. public ArrayVariable(VariableOwner owner, String name, String[] v) {
  819. value = v;
  820. this.name = name;
  821. }
  822. @Override
  823. public String getJsonPresentation() {
  824. StringBuilder sb = new StringBuilder();
  825. sb.append("\"");
  826. sb.append(name);
  827. sb.append("\":[");
  828. for (int i = 0; i < value.length;) {
  829. sb.append("\"");
  830. sb.append(escapeJSON(value[i]));
  831. sb.append("\"");
  832. i++;
  833. if (i < value.length) {
  834. sb.append(",");
  835. }
  836. }
  837. sb.append("]");
  838. return sb.toString();
  839. }
  840. }
  841. public Set<Object> getUsedResources() {
  842. return usedResources;
  843. }
  844. /**
  845. * Method to check if paintable is already painted into this target.
  846. *
  847. * @param p
  848. * @return true if is not yet painted into this target and is connected to
  849. * app
  850. */
  851. public boolean needsToBePainted(Paintable p) {
  852. if (paintedComponents.contains(p)) {
  853. return false;
  854. } else if (((Component) p).getApplication() == null) {
  855. return false;
  856. } else {
  857. return true;
  858. }
  859. }
  860. private static final Map<Class<? extends Paintable>, Class<? extends Paintable>> widgetMappingCache = new HashMap<Class<? extends Paintable>, Class<? extends Paintable>>();
  861. @SuppressWarnings("unchecked")
  862. public String getTag(Paintable paintable) {
  863. Class<? extends Paintable> class1;
  864. synchronized (widgetMappingCache) {
  865. class1 = widgetMappingCache.get(paintable.getClass());
  866. }
  867. if (class1 == null) {
  868. /*
  869. * Client widget annotation is searched from component hierarchy to
  870. * detect the component that presumably has client side
  871. * implementation. The server side name is used in the
  872. * transportation, but encoded into integer strings to optimized
  873. * transferred data.
  874. */
  875. class1 = paintable.getClass();
  876. while (!hasClientWidgetMapping(class1)) {
  877. Class<?> superclass = class1.getSuperclass();
  878. if (superclass != null
  879. && Paintable.class.isAssignableFrom(superclass)) {
  880. class1 = (Class<? extends Paintable>) superclass;
  881. } else {
  882. System.out
  883. .append("Warning: no superclass of givent has ClientWidget"
  884. + " annotation. Component will not be mapped correctly on client side.");
  885. break;
  886. }
  887. }
  888. synchronized (widgetMappingCache) {
  889. widgetMappingCache.put(paintable.getClass(), class1);
  890. }
  891. }
  892. usedPaintableTypes.add(class1);
  893. return manager.getTagForType(class1);
  894. }
  895. private boolean hasClientWidgetMapping(Class<? extends Paintable> class1) {
  896. try {
  897. return class1.isAnnotationPresent(ClientWidget.class);
  898. } catch (RuntimeException e) {
  899. if (e.getStackTrace()[0].getClassName().equals(
  900. "org.glassfish.web.loader.WebappClassLoader")) {
  901. // Glassfish 3 is darn eager to load the value class, even
  902. // though we just want to check if the annotation exists.
  903. // See #3920, remove this hack when fixed in glassfish
  904. // In some situations (depending on class loading order) it
  905. // would be enough to return true here, but it is safer to check
  906. // the annotation from bytecode
  907. String name = class1.getName().replace('.', File.separatorChar)
  908. + ".class";
  909. try {
  910. InputStream stream = class1.getClassLoader()
  911. .getResourceAsStream(name);
  912. BufferedReader bufferedReader = new BufferedReader(
  913. new InputStreamReader(stream));
  914. try {
  915. String line;
  916. boolean atSourcefile = false;
  917. while ((line = bufferedReader.readLine()) != null) {
  918. if (line.startsWith("SourceFile")) {
  919. atSourcefile = true;
  920. }
  921. if (atSourcefile) {
  922. if (line.contains("ClientWidget")) {
  923. return true;
  924. }
  925. }
  926. // TODO could optize to quit at the end attribute
  927. }
  928. } catch (IOException e1) {
  929. // TODO Auto-generated catch block
  930. e1.printStackTrace();
  931. } finally {
  932. try {
  933. bufferedReader.close();
  934. } catch (IOException e1) {
  935. // TODO Auto-generated catch block
  936. e1.printStackTrace();
  937. }
  938. }
  939. } catch (Throwable e2) {
  940. // TODO Auto-generated catch block
  941. e2.printStackTrace();
  942. }
  943. return false;
  944. } else {
  945. // throw exception forward
  946. throw e;
  947. }
  948. }
  949. }
  950. Collection<Class<? extends Paintable>> getUsedPaintableTypes() {
  951. return usedPaintableTypes;
  952. }
  953. }