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

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