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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server;
  17. import java.io.PrintWriter;
  18. import java.io.Serializable;
  19. import java.io.Writer;
  20. import java.util.ArrayDeque;
  21. import java.util.ArrayList;
  22. import java.util.Collection;
  23. import java.util.Deque;
  24. import java.util.HashSet;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;
  29. import java.util.logging.Level;
  30. import java.util.logging.Logger;
  31. import com.vaadin.ui.Alignment;
  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 Vaadin Ltd.
  41. * @since 5.0
  42. */
  43. @SuppressWarnings("serial")
  44. public class JsonPaintTarget implements PaintTarget {
  45. /* Document type declarations */
  46. private final static String UIDL_ARG_NAME = "name";
  47. private final Deque<String> mOpenTags;
  48. private final Deque<JsonTag> openJsonTags;
  49. // these match each other element-wise
  50. private final Deque<ClientConnector> openPaintables;
  51. private final Deque<String> openPaintableTags;
  52. private final PrintWriter uidlBuffer;
  53. private boolean closed = false;
  54. private final LegacyCommunicationManager manager;
  55. private int changes = 0;
  56. private final Set<Object> usedResources = new HashSet<>();
  57. private boolean customLayoutArgumentsOpen = false;
  58. private JsonTag tag;
  59. private boolean cacheEnabled = false;
  60. private final Set<Class<? extends ClientConnector>> usedClientConnectors = new HashSet<>();
  61. /**
  62. * Creates a new JsonPaintTarget.
  63. *
  64. * @param manager
  65. * @param outWriter
  66. * A character-output stream.
  67. * @param cachingRequired
  68. * true if this is not a full repaint, i.e. caches are to be
  69. * used.
  70. * @throws PaintException
  71. * if the paint operation failed.
  72. */
  73. public JsonPaintTarget(LegacyCommunicationManager manager, Writer outWriter,
  74. boolean cachingRequired) throws PaintException {
  75. this.manager = manager;
  76. // Sets the target for UIDL writing
  77. uidlBuffer = new PrintWriter(outWriter);
  78. // Initialize tag-writing
  79. mOpenTags = new ArrayDeque<>();
  80. openJsonTags = new ArrayDeque<>();
  81. openPaintables = new ArrayDeque<>();
  82. openPaintableTags = new ArrayDeque<>();
  83. cacheEnabled = cachingRequired;
  84. }
  85. @Override
  86. public void startTag(String tagName) throws PaintException {
  87. startTag(tagName, false);
  88. }
  89. /**
  90. * Prints the element start tag.
  91. *
  92. * <pre>
  93. * Todo:
  94. * Checking of input values
  95. *
  96. * </pre>
  97. *
  98. * @param tagName
  99. * the name of the start tag.
  100. * @throws PaintException
  101. * if the paint operation failed.
  102. *
  103. */
  104. public void startTag(String tagName, boolean isChildNode)
  105. throws PaintException {
  106. // In case of null data output nothing:
  107. if (tagName == null) {
  108. throw new NullPointerException();
  109. }
  110. // Ensures that the target is open
  111. if (closed) {
  112. throw new PaintException(
  113. "Attempted to write to a closed PaintTarget.");
  114. }
  115. if (tag != null) {
  116. openJsonTags.push(tag);
  117. }
  118. // Checks tagName and attributes here
  119. mOpenTags.push(tagName);
  120. tag = new JsonTag(tagName);
  121. customLayoutArgumentsOpen = false;
  122. }
  123. /**
  124. * Prints the element end tag.
  125. *
  126. * If the parent tag is closed before every child tag is closed an
  127. * PaintException is raised.
  128. *
  129. * @param tagName
  130. * the name of the end tag.
  131. * @throws PaintException
  132. * if the paint operation failed.
  133. */
  134. @Override
  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. parent.addData(tag.getJSON());
  154. tag = parent;
  155. } else {
  156. changes++;
  157. uidlBuffer.print(((changes > 1) ? "," : "") + tag.getJSON());
  158. tag = null;
  159. }
  160. }
  161. /**
  162. * Substitutes the XML sensitive characters with predefined XML entities.
  163. *
  164. * @param xml
  165. * the String to be substituted.
  166. * @return A new string instance where all occurrences of XML sensitive
  167. * characters are substituted with entities.
  168. */
  169. static public String escapeXML(String xml) {
  170. if (xml == null || xml.length() <= 0) {
  171. return "";
  172. }
  173. return escapeXML(new StringBuilder(xml)).toString();
  174. }
  175. /**
  176. * Substitutes the XML sensitive characters with predefined XML entities.
  177. *
  178. * @param xml
  179. * the String to be substituted.
  180. * @return A new StringBuilder instance where all occurrences of XML
  181. * sensitive characters are substituted with entities.
  182. *
  183. */
  184. static StringBuilder escapeXML(StringBuilder xml) {
  185. if (xml == null || xml.length() <= 0) {
  186. return new StringBuilder("");
  187. }
  188. final StringBuilder result = new StringBuilder(xml.length() * 2);
  189. for (int i = 0; i < xml.length(); i++) {
  190. final char c = xml.charAt(i);
  191. final String s = toXmlChar(c);
  192. if (s != null) {
  193. result.append(s);
  194. } else {
  195. result.append(c);
  196. }
  197. }
  198. return result;
  199. }
  200. /**
  201. * Escapes the given string so it can safely be used as a JSON string.
  202. *
  203. * @param s
  204. * The string to escape
  205. * @return Escaped version of the string
  206. */
  207. static public String escapeJSON(String s) {
  208. // FIXME: Move this method to another class as other classes use it
  209. // also.
  210. if (s == null) {
  211. return "";
  212. }
  213. final StringBuilder sb = new StringBuilder();
  214. for (int i = 0; i < s.length(); i++) {
  215. final char ch = s.charAt(i);
  216. switch (ch) {
  217. case '"':
  218. sb.append("\\\"");
  219. break;
  220. case '\\':
  221. sb.append("\\\\");
  222. break;
  223. case '\b':
  224. sb.append("\\b");
  225. break;
  226. case '\f':
  227. sb.append("\\f");
  228. break;
  229. case '\n':
  230. sb.append("\\n");
  231. break;
  232. case '\r':
  233. sb.append("\\r");
  234. break;
  235. case '\t':
  236. sb.append("\\t");
  237. break;
  238. case '/':
  239. sb.append("\\/");
  240. break;
  241. default:
  242. if (ch >= '\u0000' && ch <= '\u001F') {
  243. final String ss = Integer.toHexString(ch);
  244. sb.append("\\u");
  245. for (int k = 0; k < 4 - ss.length(); k++) {
  246. sb.append('0');
  247. }
  248. sb.append(ss.toUpperCase());
  249. } else {
  250. sb.append(ch);
  251. }
  252. }
  253. }
  254. return sb.toString();
  255. }
  256. /**
  257. * Substitutes a XML sensitive character with predefined XML entity.
  258. *
  259. * @param c
  260. * the Character to be replaced with an entity.
  261. * @return String of the entity or null if character is not to be replaced
  262. * with an entity.
  263. */
  264. private static String toXmlChar(char c) {
  265. switch (c) {
  266. case '&':
  267. return "&amp;"; // & => &amp;
  268. case '>':
  269. return "&gt;"; // > => &gt;
  270. case '<':
  271. return "&lt;"; // < => &lt;
  272. case '"':
  273. return "&quot;"; // " => &quot;
  274. case '\'':
  275. return "&apos;"; // ' => &apos;
  276. default:
  277. return null;
  278. }
  279. }
  280. /**
  281. * Prints XML-escaped text.
  282. *
  283. * @param str
  284. * @throws PaintException
  285. * if the paint operation failed.
  286. *
  287. */
  288. @Override
  289. public void addText(String str) throws PaintException {
  290. tag.addData("\"" + escapeJSON(str) + "\"");
  291. }
  292. @Override
  293. public void addAttribute(String name, boolean value) throws PaintException {
  294. tag.addAttribute("\"" + name + "\":" + (value ? "true" : "false"));
  295. }
  296. @Override
  297. public void addAttribute(String name, Resource value)
  298. throws PaintException {
  299. if (value == null) {
  300. throw new NullPointerException();
  301. }
  302. ClientConnector ownerConnector = openPaintables.peek();
  303. ownerConnector.getUI().getSession().getGlobalResourceHandler(true)
  304. .register(value, ownerConnector);
  305. ResourceReference reference = ResourceReference.create(value,
  306. ownerConnector, name);
  307. addAttribute(name, reference.getURL());
  308. }
  309. @Override
  310. public void addAttribute(String name, int value) throws PaintException {
  311. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  312. }
  313. @Override
  314. public void addAttribute(String name, long value) throws PaintException {
  315. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  316. }
  317. @Override
  318. public void addAttribute(String name, float value) throws PaintException {
  319. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  320. }
  321. @Override
  322. public void addAttribute(String name, double value) throws PaintException {
  323. tag.addAttribute("\"" + name + "\":" + String.valueOf(value));
  324. }
  325. @Override
  326. public void addAttribute(String name, String value) throws PaintException {
  327. // In case of null data output nothing:
  328. if ((value == null) || (name == null)) {
  329. throw new NullPointerException(
  330. "Parameters must be non-null strings");
  331. }
  332. tag.addAttribute("\"" + name + "\":\"" + escapeJSON(value) + "\"");
  333. if (customLayoutArgumentsOpen && "template".equals(name)) {
  334. getUsedResources().add("layouts/" + value + ".html");
  335. }
  336. }
  337. @Override
  338. public void addAttribute(String name, Component value)
  339. throws PaintException {
  340. final String id = value.getConnectorId();
  341. addAttribute(name, id);
  342. }
  343. @Override
  344. public void addAttribute(String name, Map<?, ?> value)
  345. throws PaintException {
  346. StringBuilder sb = new StringBuilder();
  347. sb.append("\"");
  348. sb.append(name);
  349. sb.append("\":");
  350. sb.append("{");
  351. for (Iterator<?> it = value.keySet().iterator(); it.hasNext();) {
  352. Object key = it.next();
  353. Object mapValue = value.get(key);
  354. sb.append("\"");
  355. if (key instanceof ClientConnector) {
  356. sb.append(((ClientConnector) key).getConnectorId());
  357. } else {
  358. sb.append(escapeJSON(key.toString()));
  359. }
  360. sb.append("\":");
  361. if (mapValue instanceof Float || mapValue instanceof Integer
  362. || mapValue instanceof Double || mapValue instanceof Boolean
  363. || mapValue instanceof Alignment) {
  364. sb.append(mapValue);
  365. } else {
  366. sb.append("\"");
  367. sb.append(escapeJSON(mapValue.toString()));
  368. sb.append("\"");
  369. }
  370. if (it.hasNext()) {
  371. sb.append(",");
  372. }
  373. }
  374. sb.append("}");
  375. tag.addAttribute(sb.toString());
  376. }
  377. @Override
  378. public void addAttribute(String name, Object[] values) {
  379. // In case of null data output nothing:
  380. if ((values == null) || (name == null)) {
  381. throw new NullPointerException(
  382. "Parameters must be non-null strings");
  383. }
  384. final StringBuilder buf = new StringBuilder();
  385. buf.append("\"").append(name).append("\":[");
  386. for (int i = 0; i < values.length; i++) {
  387. if (i > 0) {
  388. buf.append(",");
  389. }
  390. buf.append("\"");
  391. buf.append(escapeJSON(values[i].toString()));
  392. buf.append("\"");
  393. }
  394. buf.append("]");
  395. tag.addAttribute(buf.toString());
  396. }
  397. @Override
  398. public void addVariable(VariableOwner owner, String name, String value)
  399. throws PaintException {
  400. tag.addVariable(new StringVariable(owner, name, escapeJSON(value)));
  401. }
  402. @Override
  403. public void addVariable(VariableOwner owner, String name, Component value)
  404. throws PaintException {
  405. tag.addVariable(
  406. new StringVariable(owner, name, value.getConnectorId()));
  407. }
  408. @Override
  409. public void addVariable(VariableOwner owner, String name, int value)
  410. throws PaintException {
  411. tag.addVariable(new IntVariable(owner, name, value));
  412. }
  413. @Override
  414. public void addVariable(VariableOwner owner, String name, long value)
  415. throws PaintException {
  416. tag.addVariable(new LongVariable(owner, name, value));
  417. }
  418. @Override
  419. public void addVariable(VariableOwner owner, String name, float value)
  420. throws PaintException {
  421. tag.addVariable(new FloatVariable(owner, name, value));
  422. }
  423. @Override
  424. public void addVariable(VariableOwner owner, String name, double value)
  425. throws PaintException {
  426. tag.addVariable(new DoubleVariable(owner, name, value));
  427. }
  428. @Override
  429. public void addVariable(VariableOwner owner, String name, boolean value)
  430. throws PaintException {
  431. tag.addVariable(new BooleanVariable(owner, name, value));
  432. }
  433. @Override
  434. public void addVariable(VariableOwner owner, String name, String[] value)
  435. throws PaintException {
  436. tag.addVariable(new ArrayVariable(owner, name, value));
  437. }
  438. /**
  439. * Adds a upload stream type variable.
  440. *
  441. * TODO not converted for JSON
  442. *
  443. * @param owner
  444. * the Listener for variable changes.
  445. * @param name
  446. * the Variable name.
  447. *
  448. * @throws PaintException
  449. * if the paint operation failed.
  450. */
  451. @Override
  452. public void addUploadStreamVariable(VariableOwner owner, String name)
  453. throws PaintException {
  454. startTag("uploadstream");
  455. addAttribute(UIDL_ARG_NAME, name);
  456. endTag("uploadstream");
  457. }
  458. /**
  459. * Prints the single text section.
  460. *
  461. * Prints full text section. The section data is escaped
  462. *
  463. * @param sectionTagName
  464. * the name of the tag.
  465. * @param sectionData
  466. * the section data to be printed.
  467. * @throws PaintException
  468. * if the paint operation failed.
  469. */
  470. @Override
  471. public void addSection(String sectionTagName, String sectionData)
  472. throws PaintException {
  473. tag.addData("{\"" + sectionTagName + "\":\"" + escapeJSON(sectionData)
  474. + "\"}");
  475. }
  476. /**
  477. * Adds XML directly to UIDL.
  478. *
  479. * @param xml
  480. * the Xml to be added.
  481. * @throws PaintException
  482. * if the paint operation failed.
  483. */
  484. @Override
  485. public void addUIDL(String xml) throws PaintException {
  486. // Ensure that the target is open
  487. if (closed) {
  488. throw new PaintException(
  489. "Attempted to write to a closed PaintTarget.");
  490. }
  491. // Make sure that the open start tag is closed before
  492. // anything is written.
  493. // Escape and write what was given
  494. if (xml != null) {
  495. tag.addData("\"" + escapeJSON(xml) + "\"");
  496. }
  497. }
  498. /**
  499. * Adds XML section with namespace.
  500. *
  501. * @param sectionTagName
  502. * the name of the tag.
  503. * @param sectionData
  504. * the section data.
  505. * @param namespace
  506. * the namespace to be added.
  507. * @throws PaintException
  508. * if the paint operation failed.
  509. *
  510. * @see com.vaadin.server.PaintTarget#addXMLSection(String, String, String)
  511. */
  512. @Override
  513. public void addXMLSection(String sectionTagName, String sectionData,
  514. String namespace) throws PaintException {
  515. // Ensure that the target is open
  516. if (closed) {
  517. throw new PaintException(
  518. "Attempted to write to a closed PaintTarget.");
  519. }
  520. startTag(sectionTagName);
  521. if (namespace != null) {
  522. addAttribute("xmlns", namespace);
  523. }
  524. if (sectionData != null) {
  525. tag.addData("\"" + escapeJSON(sectionData) + "\"");
  526. }
  527. endTag(sectionTagName);
  528. }
  529. /**
  530. * Gets the UIDL already printed to stream. Paint target must be closed
  531. * before the <code>getUIDL</code> can be called.
  532. *
  533. * @return the UIDL.
  534. */
  535. public String getUIDL() {
  536. if (closed) {
  537. return uidlBuffer.toString();
  538. }
  539. throw new IllegalStateException(
  540. "Tried to read UIDL from open PaintTarget");
  541. }
  542. /**
  543. * Closes the paint target. Paint target must be closed before the
  544. * <code>getUIDL</code> can be called. Subsequent attempts to write to paint
  545. * target. If the target was already closed, call to this function is
  546. * ignored. will generate an exception.
  547. *
  548. * @throws PaintException
  549. * if the paint operation failed.
  550. */
  551. public void close() throws PaintException {
  552. if (tag != null) {
  553. uidlBuffer.write(tag.getJSON());
  554. }
  555. flush();
  556. closed = true;
  557. }
  558. /**
  559. * Method flush.
  560. */
  561. private void flush() {
  562. uidlBuffer.flush();
  563. }
  564. /*
  565. * (non-Javadoc)
  566. *
  567. * @see com.vaadin.terminal.PaintTarget#startPaintable(com.vaadin.terminal
  568. * .Paintable, java.lang.String)
  569. */
  570. @Override
  571. public PaintStatus startPaintable(Component connector, String tagName)
  572. throws PaintException {
  573. boolean topLevelPaintable = openPaintables.isEmpty();
  574. if (getLogger().isLoggable(Level.FINE)) {
  575. getLogger().log(Level.FINE, "startPaintable for {0}@{1}",
  576. new Object[] { connector.getClass().getName(),
  577. Integer.toHexString(connector.hashCode()) });
  578. }
  579. startTag(tagName, true);
  580. openPaintables.push(connector);
  581. openPaintableTags.push(tagName);
  582. addAttribute("id", connector.getConnectorId());
  583. // Only paint top level paintables. All sub paintables are marked as
  584. // queued and painted separately later.
  585. if (!topLevelPaintable) {
  586. return PaintStatus.CACHED;
  587. }
  588. if (connector instanceof CustomLayout) {
  589. customLayoutArgumentsOpen = true;
  590. }
  591. return PaintStatus.PAINTING;
  592. }
  593. @Override
  594. public void endPaintable(Component paintable) throws PaintException {
  595. if (getLogger().isLoggable(Level.FINE)) {
  596. getLogger().log(Level.FINE, "endPaintable for {0}@{1}",
  597. new Object[] { paintable.getClass().getName(),
  598. Integer.toHexString(paintable.hashCode()) });
  599. }
  600. ClientConnector openPaintable = openPaintables.peek();
  601. if (paintable != openPaintable) {
  602. throw new PaintException("Invalid UIDL: closing wrong paintable: '"
  603. + paintable.getConnectorId() + "' expected: '"
  604. + openPaintable.getConnectorId() + "'.");
  605. }
  606. // remove paintable from the stack
  607. openPaintables.pop();
  608. String openTag = openPaintableTags.pop();
  609. endTag(openTag);
  610. }
  611. /*
  612. * (non-Javadoc)
  613. *
  614. * @see com.vaadin.terminal.PaintTarget#addCharacterData(java.lang.String )
  615. */
  616. @Override
  617. public void addCharacterData(String text) throws PaintException {
  618. if (text != null) {
  619. tag.addData(text);
  620. }
  621. }
  622. /**
  623. * This is basically a container for UI components variables, that will be
  624. * added at the end of JSON object.
  625. *
  626. * @author mattitahvonen
  627. *
  628. */
  629. class JsonTag implements Serializable {
  630. boolean firstField = false;
  631. List<Object> variables = new ArrayList<>();
  632. List<Object> children = new ArrayList<>();
  633. List<Object> attr = new ArrayList<>();
  634. StringBuilder data = new StringBuilder();
  635. public boolean childrenArrayOpen = false;
  636. private boolean childNode = false;
  637. private boolean tagClosed = false;
  638. public JsonTag(String tagName) {
  639. data.append("[\"").append(tagName).append("\"");
  640. }
  641. private void closeTag() {
  642. if (!tagClosed) {
  643. data.append(attributesAsJsonObject());
  644. data.append(getData());
  645. // Writes the end (closing) tag
  646. data.append("]");
  647. tagClosed = true;
  648. }
  649. }
  650. public String getJSON() {
  651. if (!tagClosed) {
  652. closeTag();
  653. }
  654. return data.toString();
  655. }
  656. public void openChildrenArray() {
  657. if (!childrenArrayOpen) {
  658. // append("c : [");
  659. childrenArrayOpen = true;
  660. // firstField = true;
  661. }
  662. }
  663. public void closeChildrenArray() {
  664. // append("]");
  665. // firstField = false;
  666. }
  667. public void setChildNode(boolean b) {
  668. childNode = b;
  669. }
  670. public boolean isChildNode() {
  671. return childNode;
  672. }
  673. public String startField() {
  674. if (firstField) {
  675. firstField = false;
  676. return "";
  677. } else {
  678. return ",";
  679. }
  680. }
  681. /**
  682. *
  683. * @param s
  684. * json string, object or array
  685. */
  686. public void addData(String s) {
  687. children.add(s);
  688. }
  689. public String getData() {
  690. final StringBuilder buf = new StringBuilder();
  691. final Iterator<Object> it = children.iterator();
  692. while (it.hasNext()) {
  693. buf.append(startField());
  694. buf.append(it.next());
  695. }
  696. return buf.toString();
  697. }
  698. public void addAttribute(String jsonNode) {
  699. attr.add(jsonNode);
  700. }
  701. private String attributesAsJsonObject() {
  702. final StringBuilder buf = new StringBuilder();
  703. buf.append(startField());
  704. buf.append("{");
  705. for (final Iterator<Object> iter = attr.iterator(); iter
  706. .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.isEmpty()) {
  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((ClientConnector) owner,
  862. 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. }