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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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;
  17. import java.io.PrintWriter;
  18. import java.io.Serializable;
  19. import java.io.Writer;
  20. import java.util.Collection;
  21. import java.util.HashSet;
  22. import java.util.Iterator;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import java.util.Stack;
  26. import java.util.Vector;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;
  29. import com.vaadin.ui.Alignment;
  30. import com.vaadin.ui.Component;
  31. import com.vaadin.ui.CustomLayout;
  32. /**
  33. * User Interface Description Language Target.
  34. *
  35. * TODO document better: role of this class, UIDL format, attributes, variables,
  36. * etc.
  37. *
  38. * @author Vaadin Ltd.
  39. * @since 5.0
  40. */
  41. @SuppressWarnings("serial")
  42. public class JsonPaintTarget implements PaintTarget {
  43. /* Document type declarations */
  44. private final static String UIDL_ARG_NAME = "name";
  45. private final Stack<String> mOpenTags;
  46. private final Stack<JsonTag> openJsonTags;
  47. // these match each other element-wise
  48. private final Stack<ClientConnector> openPaintables;
  49. private final Stack<String> openPaintableTags;
  50. private final PrintWriter uidlBuffer;
  51. private boolean closed = false;
  52. private final LegacyCommunicationManager manager;
  53. private int changes = 0;
  54. private final Set<Object> usedResources = new HashSet<Object>();
  55. private boolean customLayoutArgumentsOpen = false;
  56. private JsonTag tag;
  57. private boolean cacheEnabled = false;
  58. private final Set<Class<? extends ClientConnector>> usedClientConnectors = new HashSet<Class<? extends ClientConnector>>();
  59. /**
  60. * Creates a new JsonPaintTarget.
  61. *
  62. * @param manager
  63. * @param outWriter
  64. * A character-output stream.
  65. * @param cachingRequired
  66. * true if this is not a full repaint, i.e. caches are to be
  67. * used.
  68. * @throws PaintException
  69. * if the paint operation failed.
  70. */
  71. public JsonPaintTarget(LegacyCommunicationManager manager,
  72. Writer outWriter, boolean cachingRequired) throws PaintException {
  73. this.manager = manager;
  74. // Sets the target for UIDL writing
  75. uidlBuffer = new PrintWriter(outWriter);
  76. // Initialize tag-writing
  77. mOpenTags = new Stack<String>();
  78. openJsonTags = new Stack<JsonTag>();
  79. openPaintables = new Stack<ClientConnector>();
  80. openPaintableTags = new Stack<String>();
  81. cacheEnabled = cachingRequired;
  82. }
  83. @Override
  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. customLayoutArgumentsOpen = false;
  120. }
  121. /**
  122. * Prints the element end tag.
  123. *
  124. * If the parent tag is closed before every child tag is closed an
  125. * PaintException is raised.
  126. *
  127. * @param tag
  128. * the name of the end tag.
  129. * @throws PaintException
  130. * if the paint operation failed.
  131. */
  132. @Override
  133. public void endTag(String tagName) throws PaintException {
  134. // In case of null data output nothing:
  135. if (tagName == null) {
  136. throw new NullPointerException();
  137. }
  138. // Ensure that the target is open
  139. if (closed) {
  140. throw new PaintException(
  141. "Attempted to write to a closed PaintTarget.");
  142. }
  143. if (openJsonTags.size() > 0) {
  144. final JsonTag parent = openJsonTags.pop();
  145. String lastTag = "";
  146. lastTag = mOpenTags.pop();
  147. if (!tagName.equalsIgnoreCase(lastTag)) {
  148. throw new PaintException("Invalid UIDL: wrong ending tag: '"
  149. + tagName + "' expected: '" + lastTag + "'.");
  150. }
  151. parent.addData(tag.getJSON());
  152. tag = parent;
  153. } else {
  154. changes++;
  155. uidlBuffer.print(((changes > 1) ? "," : "") + tag.getJSON());
  156. tag = null;
  157. }
  158. }
  159. /**
  160. * Substitutes the XML sensitive characters with predefined XML entities.
  161. *
  162. * @param xml
  163. * the String to be substituted.
  164. * @return A new string instance where all occurrences of XML sensitive
  165. * characters are substituted with entities.
  166. */
  167. static public String escapeXML(String xml) {
  168. if (xml == null || xml.length() <= 0) {
  169. return "";
  170. }
  171. return escapeXML(new StringBuilder(xml)).toString();
  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 StringBuilder instance where all occurrences of XML
  179. * sensitive characters are substituted with entities.
  180. *
  181. */
  182. static StringBuilder escapeXML(StringBuilder xml) {
  183. if (xml == null || xml.length() <= 0) {
  184. return new StringBuilder("");
  185. }
  186. final StringBuilder result = new StringBuilder(xml.length() * 2);
  187. for (int i = 0; i < xml.length(); i++) {
  188. final char c = xml.charAt(i);
  189. final String s = toXmlChar(c);
  190. if (s != null) {
  191. result.append(s);
  192. } else {
  193. result.append(c);
  194. }
  195. }
  196. return result;
  197. }
  198. /**
  199. * Escapes the given string so it can safely be used as a JSON string.
  200. *
  201. * @param s
  202. * The string to escape
  203. * @return Escaped version of the string
  204. */
  205. static public String escapeJSON(String s) {
  206. // FIXME: Move this method to another class as other classes use it
  207. // also.
  208. if (s == null) {
  209. return "";
  210. }
  211. final StringBuilder sb = new StringBuilder();
  212. for (int i = 0; i < s.length(); i++) {
  213. final char ch = s.charAt(i);
  214. switch (ch) {
  215. case '"':
  216. sb.append("\\\"");
  217. break;
  218. case '\\':
  219. sb.append("\\\\");
  220. break;
  221. case '\b':
  222. sb.append("\\b");
  223. break;
  224. case '\f':
  225. sb.append("\\f");
  226. break;
  227. case '\n':
  228. sb.append("\\n");
  229. break;
  230. case '\r':
  231. sb.append("\\r");
  232. break;
  233. case '\t':
  234. sb.append("\\t");
  235. break;
  236. case '/':
  237. sb.append("\\/");
  238. break;
  239. default:
  240. if (ch >= '\u0000' && ch <= '\u001F') {
  241. final String ss = Integer.toHexString(ch);
  242. sb.append("\\u");
  243. for (int k = 0; k < 4 - ss.length(); k++) {
  244. sb.append('0');
  245. }
  246. sb.append(ss.toUpperCase());
  247. } else {
  248. sb.append(ch);
  249. }
  250. }
  251. }
  252. return sb.toString();
  253. }
  254. /**
  255. * Substitutes a XML sensitive character with predefined XML entity.
  256. *
  257. * @param c
  258. * the Character to be replaced with an entity.
  259. * @return String of the entity or null if character is not to be replaced
  260. * with an entity.
  261. */
  262. private static String toXmlChar(char c) {
  263. switch (c) {
  264. case '&':
  265. return "&amp;"; // & => &amp;
  266. case '>':
  267. return "&gt;"; // > => &gt;
  268. case '<':
  269. return "&lt;"; // < => &lt;
  270. case '"':
  271. return "&quot;"; // " => &quot;
  272. case '\'':
  273. return "&apos;"; // ' => &apos;
  274. default:
  275. return null;
  276. }
  277. }
  278. /**
  279. * Prints XML-escaped text.
  280. *
  281. * @param str
  282. * @throws PaintException
  283. * if the paint operation failed.
  284. *
  285. */
  286. @Override
  287. public void addText(String str) throws PaintException {
  288. tag.addData("\"" + escapeJSON(str) + "\"");
  289. }
  290. @Override
  291. public void addAttribute(String name, boolean value) throws PaintException {
  292. tag.addAttribute("\"" + name + "\":" + (value ? "true" : "false"));
  293. }
  294. @Override
  295. public void addAttribute(String name, Resource value) throws PaintException {
  296. if (value == null) {
  297. throw new NullPointerException();
  298. }
  299. ClientConnector ownerConnector = openPaintables.peek();
  300. ownerConnector.getUI().getSession().getGlobalResourceHandler(true)
  301. .register(value, ownerConnector);
  302. ResourceReference reference = ResourceReference.create(value,
  303. ownerConnector, name);
  304. addAttribute(name, reference.getURL());
  305. }
  306. @Override
  307. public void addAttribute(String name, int value) throws PaintException {
  308. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  309. }
  310. @Override
  311. public void addAttribute(String name, long value) throws PaintException {
  312. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  313. }
  314. @Override
  315. public void addAttribute(String name, float value) throws PaintException {
  316. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  317. }
  318. @Override
  319. public void addAttribute(String name, double value) throws PaintException {
  320. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  321. }
  322. @Override
  323. public void addAttribute(String name, String value) throws PaintException {
  324. // In case of null data output nothing:
  325. if ((value == null) || (name == null)) {
  326. throw new NullPointerException(
  327. "Parameters must be non-null strings");
  328. }
  329. tag.addAttribute("\"" + name + "\":\"" + escapeJSON(value) + "\"");
  330. if (customLayoutArgumentsOpen && "template".equals(name)) {
  331. getUsedResources().add("layouts/" + value + ".html");
  332. }
  333. }
  334. @Override
  335. public void addAttribute(String name, Component value)
  336. throws PaintException {
  337. final String id = value.getConnectorId();
  338. addAttribute(name, id);
  339. }
  340. @Override
  341. public void addAttribute(String name, Map<?, ?> value)
  342. throws PaintException {
  343. StringBuilder sb = new StringBuilder();
  344. sb.append("\"");
  345. sb.append(name);
  346. sb.append("\":");
  347. sb.append("{");
  348. for (Iterator<?> it = value.keySet().iterator(); it.hasNext();) {
  349. Object key = it.next();
  350. Object mapValue = value.get(key);
  351. sb.append("\"");
  352. if (key instanceof ClientConnector) {
  353. sb.append(((ClientConnector) key).getConnectorId());
  354. } else {
  355. sb.append(escapeJSON(key.toString()));
  356. }
  357. sb.append("\":");
  358. if (mapValue instanceof Float || mapValue instanceof Integer
  359. || mapValue instanceof Double
  360. || mapValue instanceof Boolean
  361. || mapValue instanceof Alignment) {
  362. sb.append(mapValue);
  363. } else {
  364. sb.append("\"");
  365. sb.append(escapeJSON(mapValue.toString()));
  366. sb.append("\"");
  367. }
  368. if (it.hasNext()) {
  369. sb.append(",");
  370. }
  371. }
  372. sb.append("}");
  373. tag.addAttribute(sb.toString());
  374. }
  375. @Override
  376. public void addAttribute(String name, Object[] values) {
  377. // In case of null data output nothing:
  378. if ((values == null) || (name == null)) {
  379. throw new NullPointerException(
  380. "Parameters must be non-null strings");
  381. }
  382. final StringBuilder buf = new StringBuilder();
  383. buf.append("\"" + name + "\":[");
  384. for (int i = 0; i < values.length; i++) {
  385. if (i > 0) {
  386. buf.append(",");
  387. }
  388. buf.append("\"");
  389. buf.append(escapeJSON(values[i].toString()));
  390. buf.append("\"");
  391. }
  392. buf.append("]");
  393. tag.addAttribute(buf.toString());
  394. }
  395. @Override
  396. public void addVariable(VariableOwner owner, String name, String value)
  397. throws PaintException {
  398. tag.addVariable(new StringVariable(owner, name, escapeJSON(value)));
  399. }
  400. @Override
  401. public void addVariable(VariableOwner owner, String name, Component value)
  402. throws PaintException {
  403. tag.addVariable(new StringVariable(owner, name, value.getConnectorId()));
  404. }
  405. @Override
  406. public void addVariable(VariableOwner owner, String name, int value)
  407. throws PaintException {
  408. tag.addVariable(new IntVariable(owner, name, value));
  409. }
  410. @Override
  411. public void addVariable(VariableOwner owner, String name, long value)
  412. throws PaintException {
  413. tag.addVariable(new LongVariable(owner, name, value));
  414. }
  415. @Override
  416. public void addVariable(VariableOwner owner, String name, float value)
  417. throws PaintException {
  418. tag.addVariable(new FloatVariable(owner, name, value));
  419. }
  420. @Override
  421. public void addVariable(VariableOwner owner, String name, double value)
  422. throws PaintException {
  423. tag.addVariable(new DoubleVariable(owner, name, value));
  424. }
  425. @Override
  426. public void addVariable(VariableOwner owner, String name, boolean value)
  427. throws PaintException {
  428. tag.addVariable(new BooleanVariable(owner, name, value));
  429. }
  430. @Override
  431. public void addVariable(VariableOwner owner, String name, String[] value)
  432. throws PaintException {
  433. tag.addVariable(new ArrayVariable(owner, name, value));
  434. }
  435. /**
  436. * Adds a upload stream type variable.
  437. *
  438. * TODO not converted for JSON
  439. *
  440. * @param owner
  441. * the Listener for variable changes.
  442. * @param name
  443. * the Variable name.
  444. *
  445. * @throws PaintException
  446. * if the paint operation failed.
  447. */
  448. @Override
  449. public void addUploadStreamVariable(VariableOwner owner, String name)
  450. throws PaintException {
  451. startTag("uploadstream");
  452. addAttribute(UIDL_ARG_NAME, name);
  453. endTag("uploadstream");
  454. }
  455. /**
  456. * Prints the single text section.
  457. *
  458. * Prints full text section. The section data is escaped
  459. *
  460. * @param sectionTagName
  461. * the name of the tag.
  462. * @param sectionData
  463. * the section data to be printed.
  464. * @throws PaintException
  465. * if the paint operation failed.
  466. */
  467. @Override
  468. public void addSection(String sectionTagName, String sectionData)
  469. throws PaintException {
  470. tag.addData("{\"" + sectionTagName + "\":\"" + escapeJSON(sectionData)
  471. + "\"}");
  472. }
  473. /**
  474. * Adds XML directly to UIDL.
  475. *
  476. * @param xml
  477. * the Xml to be added.
  478. * @throws PaintException
  479. * if the paint operation failed.
  480. */
  481. @Override
  482. public void addUIDL(String xml) throws PaintException {
  483. // Ensure that the target is open
  484. if (closed) {
  485. throw new PaintException(
  486. "Attempted to write to a closed PaintTarget.");
  487. }
  488. // Make sure that the open start tag is closed before
  489. // anything is written.
  490. // Escape and write what was given
  491. if (xml != null) {
  492. tag.addData("\"" + escapeJSON(xml) + "\"");
  493. }
  494. }
  495. /**
  496. * Adds XML section with namespace.
  497. *
  498. * @param sectionTagName
  499. * the name of the tag.
  500. * @param sectionData
  501. * the section data.
  502. * @param namespace
  503. * the namespace to be added.
  504. * @throws PaintException
  505. * if the paint operation failed.
  506. *
  507. * @see com.vaadin.server.PaintTarget#addXMLSection(String, String, String)
  508. */
  509. @Override
  510. public void addXMLSection(String sectionTagName, String sectionData,
  511. String namespace) throws PaintException {
  512. // Ensure that the target is open
  513. if (closed) {
  514. throw new PaintException(
  515. "Attempted to write to a closed PaintTarget.");
  516. }
  517. startTag(sectionTagName);
  518. if (namespace != null) {
  519. addAttribute("xmlns", namespace);
  520. }
  521. if (sectionData != null) {
  522. tag.addData("\"" + escapeJSON(sectionData) + "\"");
  523. }
  524. endTag(sectionTagName);
  525. }
  526. /**
  527. * Gets the UIDL already printed to stream. Paint target must be closed
  528. * before the <code>getUIDL</code> can be called.
  529. *
  530. * @return the UIDL.
  531. */
  532. public String getUIDL() {
  533. if (closed) {
  534. return uidlBuffer.toString();
  535. }
  536. throw new IllegalStateException(
  537. "Tried to read UIDL from open PaintTarget");
  538. }
  539. /**
  540. * Closes the paint target. Paint target must be closed before the
  541. * <code>getUIDL</code> can be called. Subsequent attempts to write to paint
  542. * target. If the target was already closed, call to this function is
  543. * ignored. will generate an exception.
  544. *
  545. * @throws PaintException
  546. * if the paint operation failed.
  547. */
  548. public void close() throws PaintException {
  549. if (tag != null) {
  550. uidlBuffer.write(tag.getJSON());
  551. }
  552. flush();
  553. closed = true;
  554. }
  555. /**
  556. * Method flush.
  557. */
  558. private void flush() {
  559. uidlBuffer.flush();
  560. }
  561. /*
  562. * (non-Javadoc)
  563. *
  564. * @see com.vaadin.terminal.PaintTarget#startPaintable(com.vaadin.terminal
  565. * .Paintable, java.lang.String)
  566. */
  567. @Override
  568. public PaintStatus startPaintable(Component connector, String tagName)
  569. throws PaintException {
  570. boolean topLevelPaintable = openPaintables.isEmpty();
  571. if (getLogger().isLoggable(Level.FINE)) {
  572. getLogger().log(
  573. Level.FINE,
  574. "startPaintable for {0}@{1}",
  575. new Object[] { connector.getClass().getName(),
  576. Integer.toHexString(connector.hashCode()) });
  577. }
  578. startTag(tagName, true);
  579. openPaintables.push(connector);
  580. openPaintableTags.push(tagName);
  581. addAttribute("id", connector.getConnectorId());
  582. // Only paint top level paintables. All sub paintables are marked as
  583. // queued and painted separately later.
  584. if (!topLevelPaintable) {
  585. return PaintStatus.CACHED;
  586. }
  587. if (connector instanceof CustomLayout) {
  588. customLayoutArgumentsOpen = true;
  589. }
  590. return PaintStatus.PAINTING;
  591. }
  592. @Override
  593. public void endPaintable(Component paintable) throws PaintException {
  594. if (getLogger().isLoggable(Level.FINE)) {
  595. getLogger().log(
  596. Level.FINE,
  597. "endPaintable for {0}@{1}",
  598. new Object[] { paintable.getClass().getName(),
  599. Integer.toHexString(paintable.hashCode()) });
  600. }
  601. ClientConnector openPaintable = openPaintables.peek();
  602. if (paintable != openPaintable) {
  603. throw new PaintException("Invalid UIDL: closing wrong paintable: '"
  604. + paintable.getConnectorId() + "' expected: '"
  605. + openPaintable.getConnectorId() + "'.");
  606. }
  607. // remove paintable from the stack
  608. openPaintables.pop();
  609. String openTag = openPaintableTags.pop();
  610. endTag(openTag);
  611. }
  612. /*
  613. * (non-Javadoc)
  614. *
  615. * @see com.vaadin.terminal.PaintTarget#addCharacterData(java.lang.String )
  616. */
  617. @Override
  618. public void addCharacterData(String text) throws PaintException {
  619. if (text != null) {
  620. tag.addData(text);
  621. }
  622. }
  623. /**
  624. * This is basically a container for UI components variables, that will be
  625. * added at the end of JSON object.
  626. *
  627. * @author mattitahvonen
  628. *
  629. */
  630. class JsonTag implements Serializable {
  631. boolean firstField = false;
  632. Vector<Object> variables = new Vector<Object>();
  633. Vector<Object> children = new Vector<Object>();
  634. Vector<Object> attr = new Vector<Object>();
  635. StringBuilder data = new StringBuilder();
  636. public boolean childrenArrayOpen = false;
  637. private boolean childNode = false;
  638. private boolean tagClosed = false;
  639. public JsonTag(String tagName) {
  640. data.append("[\"" + tagName + "\"");
  641. }
  642. private void closeTag() {
  643. if (!tagClosed) {
  644. data.append(attributesAsJsonObject());
  645. data.append(getData());
  646. // Writes the end (closing) tag
  647. data.append("]");
  648. tagClosed = true;
  649. }
  650. }
  651. public String getJSON() {
  652. if (!tagClosed) {
  653. closeTag();
  654. }
  655. return data.toString();
  656. }
  657. public void openChildrenArray() {
  658. if (!childrenArrayOpen) {
  659. // append("c : [");
  660. childrenArrayOpen = true;
  661. // firstField = true;
  662. }
  663. }
  664. public void closeChildrenArray() {
  665. // append("]");
  666. // firstField = false;
  667. }
  668. public void setChildNode(boolean b) {
  669. childNode = b;
  670. }
  671. public boolean isChildNode() {
  672. return childNode;
  673. }
  674. public String startField() {
  675. if (firstField) {
  676. firstField = false;
  677. return "";
  678. } else {
  679. return ",";
  680. }
  681. }
  682. /**
  683. *
  684. * @param s
  685. * json string, object or array
  686. */
  687. public void addData(String s) {
  688. children.add(s);
  689. }
  690. public String getData() {
  691. final StringBuilder buf = new StringBuilder();
  692. final Iterator<Object> it = children.iterator();
  693. while (it.hasNext()) {
  694. buf.append(startField());
  695. buf.append(it.next());
  696. }
  697. return buf.toString();
  698. }
  699. public void addAttribute(String jsonNode) {
  700. attr.add(jsonNode);
  701. }
  702. private String attributesAsJsonObject() {
  703. final StringBuilder buf = new StringBuilder();
  704. buf.append(startField());
  705. buf.append("{");
  706. for (final Iterator<Object> iter = attr.iterator(); iter.hasNext();) {
  707. final String element = (String) iter.next();
  708. buf.append(element);
  709. if (iter.hasNext()) {
  710. buf.append(",");
  711. }
  712. }
  713. buf.append(tag.variablesAsJsonObject());
  714. buf.append("}");
  715. return buf.toString();
  716. }
  717. public void addVariable(Variable v) {
  718. variables.add(v);
  719. }
  720. private String variablesAsJsonObject() {
  721. if (variables.size() == 0) {
  722. return "";
  723. }
  724. final StringBuilder buf = new StringBuilder();
  725. buf.append(startField());
  726. buf.append("\"v\":{");
  727. final Iterator<Object> iter = variables.iterator();
  728. while (iter.hasNext()) {
  729. final Variable element = (Variable) iter.next();
  730. buf.append(element.getJsonPresentation());
  731. if (iter.hasNext()) {
  732. buf.append(",");
  733. }
  734. }
  735. buf.append("}");
  736. return buf.toString();
  737. }
  738. }
  739. abstract class Variable implements Serializable {
  740. String name;
  741. public abstract String getJsonPresentation();
  742. }
  743. class BooleanVariable extends Variable implements Serializable {
  744. boolean value;
  745. public BooleanVariable(VariableOwner owner, String name, boolean v) {
  746. value = v;
  747. this.name = name;
  748. }
  749. @Override
  750. public String getJsonPresentation() {
  751. return "\"" + name + "\":" + (value == true ? "true" : "false");
  752. }
  753. }
  754. class StringVariable extends Variable implements Serializable {
  755. String value;
  756. public StringVariable(VariableOwner owner, String name, String v) {
  757. value = v;
  758. this.name = name;
  759. }
  760. @Override
  761. public String getJsonPresentation() {
  762. return "\"" + name + "\":\"" + value + "\"";
  763. }
  764. }
  765. class IntVariable extends Variable implements Serializable {
  766. int value;
  767. public IntVariable(VariableOwner owner, String name, int v) {
  768. value = v;
  769. this.name = name;
  770. }
  771. @Override
  772. public String getJsonPresentation() {
  773. return "\"" + name + "\":" + value;
  774. }
  775. }
  776. class LongVariable extends Variable implements Serializable {
  777. long value;
  778. public LongVariable(VariableOwner owner, String name, long v) {
  779. value = v;
  780. this.name = name;
  781. }
  782. @Override
  783. public String getJsonPresentation() {
  784. return "\"" + name + "\":" + value;
  785. }
  786. }
  787. class FloatVariable extends Variable implements Serializable {
  788. float value;
  789. public FloatVariable(VariableOwner owner, String name, float v) {
  790. value = v;
  791. this.name = name;
  792. }
  793. @Override
  794. public String getJsonPresentation() {
  795. return "\"" + name + "\":" + value;
  796. }
  797. }
  798. class DoubleVariable extends Variable implements Serializable {
  799. double value;
  800. public DoubleVariable(VariableOwner owner, String name, double v) {
  801. value = v;
  802. this.name = name;
  803. }
  804. @Override
  805. public String getJsonPresentation() {
  806. return "\"" + name + "\":" + value;
  807. }
  808. }
  809. class ArrayVariable extends Variable implements Serializable {
  810. String[] value;
  811. public ArrayVariable(VariableOwner owner, String name, String[] v) {
  812. value = v;
  813. this.name = name;
  814. }
  815. @Override
  816. public String getJsonPresentation() {
  817. StringBuilder sb = new StringBuilder();
  818. sb.append("\"");
  819. sb.append(name);
  820. sb.append("\":[");
  821. for (int i = 0; i < value.length;) {
  822. sb.append("\"");
  823. sb.append(escapeJSON(value[i]));
  824. sb.append("\"");
  825. i++;
  826. if (i < value.length) {
  827. sb.append(",");
  828. }
  829. }
  830. sb.append("]");
  831. return sb.toString();
  832. }
  833. }
  834. public Set<Object> getUsedResources() {
  835. return usedResources;
  836. }
  837. @Override
  838. @SuppressWarnings("unchecked")
  839. public String getTag(ClientConnector clientConnector) {
  840. Class<? extends ClientConnector> clientConnectorClass = clientConnector
  841. .getClass();
  842. while (clientConnectorClass.isAnonymousClass()) {
  843. clientConnectorClass = (Class<? extends ClientConnector>) clientConnectorClass
  844. .getSuperclass();
  845. }
  846. Class<?> clazz = clientConnectorClass;
  847. while (!usedClientConnectors.contains(clazz)
  848. && clazz.getSuperclass() != null
  849. && ClientConnector.class.isAssignableFrom(clazz)) {
  850. usedClientConnectors.add((Class<? extends ClientConnector>) clazz);
  851. clazz = clazz.getSuperclass();
  852. }
  853. return manager.getTagForType(clientConnectorClass);
  854. }
  855. public Collection<Class<? extends ClientConnector>> getUsedClientConnectors() {
  856. return usedClientConnectors;
  857. }
  858. @Override
  859. public void addVariable(VariableOwner owner, String name,
  860. StreamVariable value) throws PaintException {
  861. String url = manager.getStreamVariableTargetUrl(
  862. (ClientConnector) owner, name, value);
  863. if (url != null) {
  864. addVariable(owner, name, url);
  865. } // else { //NOP this was just a cleanup by component }
  866. }
  867. /*
  868. * (non-Javadoc)
  869. *
  870. * @see com.vaadin.terminal.PaintTarget#isFullRepaint()
  871. */
  872. @Override
  873. public boolean isFullRepaint() {
  874. return !cacheEnabled;
  875. }
  876. private static final Logger getLogger() {
  877. return Logger.getLogger(JsonPaintTarget.class.getName());
  878. }
  879. }