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.

ConnectorTracker.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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.ui;
  17. import java.io.IOException;
  18. import java.io.Serializable;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.LinkedList;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.UUID;
  28. import java.util.logging.Level;
  29. import java.util.logging.Logger;
  30. import com.vaadin.server.AbstractClientConnector;
  31. import com.vaadin.server.ClientConnector;
  32. import com.vaadin.server.DragAndDropService;
  33. import com.vaadin.server.GlobalResourceHandler;
  34. import com.vaadin.server.LegacyCommunicationManager;
  35. import com.vaadin.server.StreamVariable;
  36. import com.vaadin.server.VaadinRequest;
  37. import com.vaadin.server.VaadinService;
  38. import com.vaadin.server.communication.ConnectorHierarchyWriter;
  39. import elemental.json.Json;
  40. import elemental.json.JsonException;
  41. import elemental.json.JsonObject;
  42. /**
  43. * A class which takes care of book keeping of {@link ClientConnector}s for a
  44. * UI.
  45. * <p>
  46. * Provides {@link #getConnector(String)} which can be used to lookup a
  47. * connector from its id. This is for framework use only and should not be
  48. * needed in applications.
  49. * </p>
  50. * <p>
  51. * Tracks which {@link ClientConnector}s are dirty so they can be updated to the
  52. * client when the following response is sent. A connector is dirty when an
  53. * operation has been performed on it on the server and as a result of this
  54. * operation new information needs to be sent to its
  55. * {@link com.vaadin.client.ServerConnector}.
  56. * </p>
  57. *
  58. * @author Vaadin Ltd
  59. * @since 7.0.0
  60. *
  61. */
  62. public class ConnectorTracker implements Serializable {
  63. private final HashMap<String, ClientConnector> connectorIdToConnector = new HashMap<>();
  64. private final Set<ClientConnector> dirtyConnectors = new HashSet<>();
  65. private final Set<ClientConnector> uninitializedConnectors = new HashSet<>();
  66. /**
  67. * Connectors that have been unregistered and should be cleaned up the next
  68. * time {@link #cleanConnectorMap()} is invoked unless they have been
  69. * registered again.
  70. */
  71. private final Set<ClientConnector> unregisteredConnectors = new HashSet<>();
  72. private boolean writingResponse = false;
  73. private final UI uI;
  74. private transient Map<ClientConnector, JsonObject> diffStates = new HashMap<>();
  75. /** Maps connectorIds to a map of named StreamVariables */
  76. private Map<String, Map<String, StreamVariable>> pidToNameToStreamVariable;
  77. private Map<StreamVariable, String> streamVariableToSeckey;
  78. private int currentSyncId = 0;
  79. /**
  80. * Gets a logger for this class
  81. *
  82. * @return A logger instance for logging within this class
  83. *
  84. */
  85. private static Logger getLogger() {
  86. return Logger.getLogger(ConnectorTracker.class.getName());
  87. }
  88. /**
  89. * Creates a new ConnectorTracker for the given uI. A tracker is always
  90. * attached to a uI and the uI cannot be changed during the lifetime of a
  91. * {@link ConnectorTracker}.
  92. *
  93. * @param uI
  94. * The uI to attach to. Cannot be null.
  95. */
  96. public ConnectorTracker(UI uI) {
  97. this.uI = uI;
  98. }
  99. /**
  100. * Register the given connector.
  101. * <p>
  102. * The lookup method {@link #getConnector(String)} only returns registered
  103. * connectors.
  104. * </p>
  105. *
  106. * @param connector
  107. * The connector to register.
  108. */
  109. public void registerConnector(ClientConnector connector) {
  110. boolean wasUnregistered = unregisteredConnectors.remove(connector);
  111. String connectorId = connector.getConnectorId();
  112. ClientConnector previouslyRegistered = connectorIdToConnector
  113. .get(connectorId);
  114. if (previouslyRegistered == null) {
  115. connectorIdToConnector.put(connectorId, connector);
  116. uninitializedConnectors.add(connector);
  117. if (getLogger().isLoggable(Level.FINE)) {
  118. getLogger().log(Level.FINE, "Registered {0} ({1})",
  119. new Object[] { connector.getClass().getSimpleName(),
  120. connectorId });
  121. }
  122. } else if (previouslyRegistered != connector) {
  123. throw new RuntimeException("A connector with id " + connectorId
  124. + " is already registered!");
  125. } else if (!wasUnregistered) {
  126. getLogger().log(Level.WARNING,
  127. "An already registered connector was registered again: {0} ({1})",
  128. new Object[] { connector.getClass().getSimpleName(),
  129. connectorId });
  130. }
  131. dirtyConnectors.add(connector);
  132. }
  133. /**
  134. * Unregister the given connector.
  135. *
  136. * <p>
  137. * The lookup method {@link #getConnector(String)} only returns registered
  138. * connectors.
  139. * </p>
  140. *
  141. * @param connector
  142. * The connector to unregister
  143. */
  144. public void unregisterConnector(ClientConnector connector) {
  145. String connectorId = connector.getConnectorId();
  146. if (!connectorIdToConnector.containsKey(connectorId)) {
  147. getLogger().log(Level.WARNING,
  148. "Tried to unregister {0} ({1}) which is not registered",
  149. new Object[] { connector.getClass().getSimpleName(),
  150. connectorId });
  151. return;
  152. }
  153. if (connectorIdToConnector.get(connectorId) != connector) {
  154. throw new RuntimeException("The given connector with id "
  155. + connectorId
  156. + " is not the one that was registered for that id");
  157. }
  158. dirtyConnectors.remove(connector);
  159. if (unregisteredConnectors.add(connector)) {
  160. if (getLogger().isLoggable(Level.FINE)) {
  161. getLogger().log(Level.FINE, "Unregistered {0} ({1})",
  162. new Object[] { connector.getClass().getSimpleName(),
  163. connectorId });
  164. }
  165. } else {
  166. getLogger().log(Level.WARNING,
  167. "Unregistered {0} ({1}) that was already unregistered.",
  168. new Object[] { connector.getClass().getSimpleName(),
  169. connectorId });
  170. }
  171. }
  172. /**
  173. * Checks whether the given connector has already been initialized in the
  174. * browser. The given connector should be registered with this connector
  175. * tracker.
  176. *
  177. * @param connector
  178. * the client connector to check
  179. * @return <code>true</code> if the initial state has previously been sent
  180. * to the browser, <code>false</code> if the client-side doesn't
  181. * already know anything about the connector.
  182. */
  183. public boolean isClientSideInitialized(ClientConnector connector) {
  184. assert connectorIdToConnector.get(connector
  185. .getConnectorId()) == connector : "Connector should be registered with this ConnectorTracker";
  186. return !uninitializedConnectors.contains(connector);
  187. }
  188. /**
  189. * Marks the given connector as initialized, meaning that the client-side
  190. * state has been initialized for the connector.
  191. *
  192. * @see #isClientSideInitialized(ClientConnector)
  193. *
  194. * @param connector
  195. * the connector that should be marked as initialized
  196. */
  197. public void markClientSideInitialized(ClientConnector connector) {
  198. uninitializedConnectors.remove(connector);
  199. }
  200. /**
  201. * Marks all currently registered connectors as uninitialized. This should
  202. * be done when the client-side has been reset but the server-side state is
  203. * retained.
  204. *
  205. * @see #isClientSideInitialized(ClientConnector)
  206. */
  207. public void markAllClientSidesUninitialized() {
  208. uninitializedConnectors.addAll(connectorIdToConnector.values());
  209. diffStates.clear();
  210. }
  211. /**
  212. * Gets a connector by its id.
  213. *
  214. * @param connectorId
  215. * The connector id to look for
  216. * @return The connector with the given id or null if no connector has the
  217. * given id
  218. */
  219. public ClientConnector getConnector(String connectorId) {
  220. ClientConnector connector = connectorIdToConnector.get(connectorId);
  221. // Ignore connectors that have been unregistered but not yet cleaned up
  222. if (unregisteredConnectors.contains(connector)) {
  223. return null;
  224. } else if (connector != null) {
  225. return connector;
  226. } else {
  227. DragAndDropService service = uI.getSession()
  228. .getDragAndDropService();
  229. if (connectorId.equals(service.getConnectorId())) {
  230. return service;
  231. }
  232. }
  233. return null;
  234. }
  235. /**
  236. * Cleans the connector map from all connectors that are no longer attached
  237. * to the application. This should only be called by the framework.
  238. */
  239. public void cleanConnectorMap() {
  240. if (!unregisteredConnectors.isEmpty()) {
  241. removeUnregisteredConnectors();
  242. }
  243. // Do this expensive check only with assertions enabled
  244. assert isHierarchyComplete() : "The connector hierarchy is corrupted. "
  245. + "Check for missing calls to super.setParent(), super.attach() and super.detach() "
  246. + "and that all custom component containers call child.setParent(this) when a child is added and child.setParent(null) when the child is no longer used. "
  247. + "See previous log messages for details.";
  248. // remove detached components from paintableIdMap so they
  249. // can be GC'ed
  250. Iterator<ClientConnector> iterator = connectorIdToConnector.values()
  251. .iterator();
  252. GlobalResourceHandler globalResourceHandler = uI.getSession()
  253. .getGlobalResourceHandler(false);
  254. while (iterator.hasNext()) {
  255. ClientConnector connector = iterator.next();
  256. assert connector != null;
  257. if (connector.getUI() != uI) {
  258. // If connector is no longer part of this uI,
  259. // remove it from the map. If it is re-attached to the
  260. // application at some point it will be re-added through
  261. // registerConnector(connector)
  262. // This code should never be called as cleanup should take place
  263. // in detach()
  264. getLogger().log(Level.WARNING,
  265. "cleanConnectorMap unregistered connector {0}. This should have been done when the connector was detached.",
  266. getConnectorAndParentInfo(connector));
  267. if (globalResourceHandler != null) {
  268. globalResourceHandler.unregisterConnector(connector);
  269. }
  270. uninitializedConnectors.remove(connector);
  271. diffStates.remove(connector);
  272. iterator.remove();
  273. } else if (!uninitializedConnectors.contains(connector)
  274. && !LegacyCommunicationManager
  275. .isConnectorVisibleToClient(connector)) {
  276. uninitializedConnectors.add(connector);
  277. diffStates.remove(connector);
  278. assert isRemovalSentToClient(connector) : "Connector "
  279. + connector + " (id = " + connector.getConnectorId()
  280. + ") is no longer visible to the client, but no corresponding hierarchy change is being sent.";
  281. if (getLogger().isLoggable(Level.FINE)) {
  282. getLogger().log(Level.FINE,
  283. "cleanConnectorMap removed state for {0} as it is not visible",
  284. getConnectorAndParentInfo(connector));
  285. }
  286. }
  287. }
  288. cleanStreamVariables();
  289. }
  290. private boolean isRemovalSentToClient(ClientConnector connector) {
  291. VaadinRequest request = VaadinService.getCurrentRequest();
  292. if (request == null) {
  293. // Probably run from a unit test without normal request handling
  294. return true;
  295. }
  296. String attributeName = ConnectorHierarchyWriter.class.getName()
  297. + ".hierarchyInfo";
  298. Object hierarchyInfoObj = request.getAttribute(attributeName);
  299. if (hierarchyInfoObj instanceof JsonObject) {
  300. JsonObject hierachyInfo = (JsonObject) hierarchyInfoObj;
  301. ClientConnector firstVisibleParent = findFirstVisibleParent(
  302. connector);
  303. if (firstVisibleParent == null) {
  304. // Connector is detached, not our business
  305. return true;
  306. }
  307. if (!hierachyInfo.hasKey(firstVisibleParent.getConnectorId())) {
  308. /*
  309. * No hierarchy change about to be sent, but this might be
  310. * because of an optimization that omits explicit hierarchy
  311. * changes for empty connectors that have state changes.
  312. */
  313. if (hasVisibleChild(firstVisibleParent)) {
  314. // Not the optimization case if the parent has visible
  315. // children
  316. return false;
  317. }
  318. attributeName = ConnectorHierarchyWriter.class.getName()
  319. + ".stateUpdateConnectors";
  320. Object stateUpdateConnectorsObj = request
  321. .getAttribute(attributeName);
  322. if (stateUpdateConnectorsObj instanceof Set<?>) {
  323. Set<?> stateUpdateConnectors = (Set<?>) stateUpdateConnectorsObj;
  324. if (!stateUpdateConnectors
  325. .contains(firstVisibleParent.getConnectorId())) {
  326. // Not the optimization case if the parent is not marked
  327. // as dirty
  328. return false;
  329. }
  330. } else {
  331. getLogger().warning("Request attribute " + attributeName
  332. + " is not a Set");
  333. }
  334. }
  335. } else {
  336. getLogger().warning("Request attribute " + attributeName
  337. + " is not a JsonObject");
  338. }
  339. return true;
  340. }
  341. private static boolean hasVisibleChild(ClientConnector parent) {
  342. Iterator<? extends ClientConnector> iterator = AbstractClientConnector
  343. .getAllChildrenIterable(parent).iterator();
  344. while (iterator.hasNext()) {
  345. ClientConnector child = iterator.next();
  346. if (LegacyCommunicationManager.isConnectorVisibleToClient(child)) {
  347. return true;
  348. }
  349. }
  350. return false;
  351. }
  352. private ClientConnector findFirstVisibleParent(ClientConnector connector) {
  353. while (connector != null) {
  354. connector = connector.getParent();
  355. if (LegacyCommunicationManager
  356. .isConnectorVisibleToClient(connector)) {
  357. return connector;
  358. }
  359. }
  360. return null;
  361. }
  362. private void removeUnregisteredConnectors() {
  363. GlobalResourceHandler globalResourceHandler = uI.getSession()
  364. .getGlobalResourceHandler(false);
  365. for (ClientConnector connector : unregisteredConnectors) {
  366. ClientConnector removedConnector = connectorIdToConnector
  367. .remove(connector.getConnectorId());
  368. assert removedConnector == connector;
  369. if (globalResourceHandler != null) {
  370. globalResourceHandler.unregisterConnector(connector);
  371. }
  372. uninitializedConnectors.remove(connector);
  373. diffStates.remove(connector);
  374. }
  375. unregisteredConnectors.clear();
  376. }
  377. private boolean isHierarchyComplete() {
  378. boolean noErrors = true;
  379. Set<ClientConnector> danglingConnectors = new HashSet<>(
  380. connectorIdToConnector.values());
  381. LinkedList<ClientConnector> stack = new LinkedList<>();
  382. stack.add(uI);
  383. while (!stack.isEmpty()) {
  384. ClientConnector connector = stack.pop();
  385. danglingConnectors.remove(connector);
  386. Iterable<? extends ClientConnector> children = AbstractClientConnector
  387. .getAllChildrenIterable(connector);
  388. for (ClientConnector child : children) {
  389. stack.add(child);
  390. if (!connector.equals(child.getParent())) {
  391. noErrors = false;
  392. getLogger().log(Level.WARNING,
  393. "{0} claims that {1} is its child, but the child claims {2} is its parent.",
  394. new Object[] { getConnectorString(connector),
  395. getConnectorString(child),
  396. getConnectorString(child.getParent()) });
  397. }
  398. }
  399. }
  400. for (ClientConnector dangling : danglingConnectors) {
  401. noErrors = false;
  402. getLogger().log(Level.WARNING,
  403. "{0} claims that {1} is its parent, but the parent does not acknowledge the parenthood.",
  404. new Object[] { getConnectorString(dangling),
  405. getConnectorString(dangling.getParent()) });
  406. }
  407. return noErrors;
  408. }
  409. /**
  410. * Mark the connector as dirty. This should not be done while the response
  411. * is being written.
  412. *
  413. * @see #getDirtyConnectors()
  414. * @see #isWritingResponse()
  415. *
  416. * @param connector
  417. * The connector that should be marked clean.
  418. */
  419. public void markDirty(ClientConnector connector) {
  420. if (isWritingResponse()) {
  421. throw new IllegalStateException(
  422. "A connector should not be marked as dirty while a response is being written.");
  423. }
  424. if (getLogger().isLoggable(Level.FINE)) {
  425. if (!dirtyConnectors.contains(connector)) {
  426. getLogger().log(Level.FINE, "{0} is now dirty",
  427. getConnectorAndParentInfo(connector));
  428. }
  429. }
  430. dirtyConnectors.add(connector);
  431. }
  432. /**
  433. * Mark the connector as clean.
  434. *
  435. * @param connector
  436. * The connector that should be marked clean.
  437. */
  438. public void markClean(ClientConnector connector) {
  439. if (getLogger().isLoggable(Level.FINE)) {
  440. if (dirtyConnectors.contains(connector)) {
  441. getLogger().log(Level.FINE, "{0} is no longer dirty",
  442. getConnectorAndParentInfo(connector));
  443. }
  444. }
  445. dirtyConnectors.remove(connector);
  446. }
  447. /**
  448. * Returns {@link #getConnectorString(ClientConnector)} for the connector
  449. * and its parent (if it has a parent).
  450. *
  451. * @param connector
  452. * The connector
  453. * @return A string describing the connector and its parent
  454. */
  455. private String getConnectorAndParentInfo(ClientConnector connector) {
  456. String message = getConnectorString(connector);
  457. if (connector.getParent() != null) {
  458. message += " (parent: " + getConnectorString(connector.getParent())
  459. + ")";
  460. }
  461. return message;
  462. }
  463. /**
  464. * Returns a string with the connector name and id. Useful mostly for
  465. * debugging and logging.
  466. *
  467. * @param connector
  468. * The connector
  469. * @return A string that describes the connector
  470. */
  471. private String getConnectorString(ClientConnector connector) {
  472. if (connector == null) {
  473. return "(null)";
  474. }
  475. String connectorId;
  476. try {
  477. connectorId = connector.getConnectorId();
  478. } catch (RuntimeException e) {
  479. // This happens if the connector is not attached to the application.
  480. // SHOULD not happen in this case but theoretically can.
  481. connectorId = "@" + Integer.toHexString(connector.hashCode());
  482. }
  483. return connector.getClass().getName() + "(" + connectorId + ")";
  484. }
  485. /**
  486. * Mark all connectors in this uI as dirty.
  487. */
  488. public void markAllConnectorsDirty() {
  489. markConnectorsDirtyRecursively(uI);
  490. getLogger().fine("All connectors are now dirty");
  491. }
  492. /**
  493. * Mark all connectors in this uI as clean.
  494. */
  495. public void markAllConnectorsClean() {
  496. dirtyConnectors.clear();
  497. getLogger().fine("All connectors are now clean");
  498. }
  499. /**
  500. * Marks all visible connectors dirty, starting from the given connector and
  501. * going downwards in the hierarchy.
  502. *
  503. * @param c
  504. * The component to start iterating downwards from
  505. */
  506. private void markConnectorsDirtyRecursively(ClientConnector c) {
  507. if (c instanceof Component && !((Component) c).isVisible()) {
  508. return;
  509. }
  510. markDirty(c);
  511. for (ClientConnector child : AbstractClientConnector
  512. .getAllChildrenIterable(c)) {
  513. markConnectorsDirtyRecursively(child);
  514. }
  515. }
  516. /**
  517. * Returns a collection of all connectors which have been marked as dirty.
  518. * <p>
  519. * The state and pending RPC calls for dirty connectors are sent to the
  520. * client in the following request.
  521. * </p>
  522. *
  523. * @return A collection of all dirty connectors for this uI. This list may
  524. * contain invisible connectors.
  525. */
  526. public Collection<ClientConnector> getDirtyConnectors() {
  527. return dirtyConnectors;
  528. }
  529. /**
  530. * Checks if there a dirty connectors.
  531. *
  532. * @return true if there are dirty connectors, false otherwise
  533. */
  534. public boolean hasDirtyConnectors() {
  535. return !getDirtyConnectors().isEmpty();
  536. }
  537. /**
  538. * Returns a collection of those {@link #getDirtyConnectors() dirty
  539. * connectors} that are actually visible to the client.
  540. *
  541. * @return A list of dirty and visible connectors.
  542. */
  543. public ArrayList<ClientConnector> getDirtyVisibleConnectors() {
  544. Collection<ClientConnector> dirtyConnectors = getDirtyConnectors();
  545. ArrayList<ClientConnector> dirtyVisibleConnectors = new ArrayList<>(
  546. dirtyConnectors.size());
  547. for (ClientConnector c : dirtyConnectors) {
  548. if (LegacyCommunicationManager.isConnectorVisibleToClient(c)) {
  549. dirtyVisibleConnectors.add(c);
  550. }
  551. }
  552. return dirtyVisibleConnectors;
  553. }
  554. public JsonObject getDiffState(ClientConnector connector) {
  555. assert getConnector(connector.getConnectorId()) == connector;
  556. return diffStates.get(connector);
  557. }
  558. public void setDiffState(ClientConnector connector, JsonObject diffState) {
  559. assert getConnector(connector.getConnectorId()) == connector;
  560. diffStates.put(connector, diffState);
  561. }
  562. public boolean isDirty(ClientConnector connector) {
  563. return dirtyConnectors.contains(connector);
  564. }
  565. /**
  566. * Checks whether the response is currently being written. Connectors can
  567. * not be marked as dirty when a response is being written.
  568. *
  569. * @see #setWritingResponse(boolean)
  570. * @see #markDirty(ClientConnector)
  571. *
  572. * @return <code>true</code> if the response is currently being written,
  573. * <code>false</code> if outside the response writing phase.
  574. */
  575. public boolean isWritingResponse() {
  576. return writingResponse;
  577. }
  578. /**
  579. * Sets the current response write status. Connectors can not be marked as
  580. * dirty when the response is written.
  581. * <p>
  582. * This method has a side-effect of incrementing the sync id by one (see
  583. * {@link #getCurrentSyncId()}), if {@link #isWritingResponse()} returns
  584. * <code>true</code> and <code>writingResponse</code> is set to
  585. * <code>false</code>.
  586. *
  587. * @param writingResponse
  588. * the new response status.
  589. *
  590. * @see #markDirty(ClientConnector)
  591. * @see #isWritingResponse()
  592. * @see #getCurrentSyncId()
  593. *
  594. * @throws IllegalArgumentException
  595. * if the new response status is the same as the previous value.
  596. * This is done to help detecting problems caused by missed
  597. * invocations of this method.
  598. */
  599. public void setWritingResponse(boolean writingResponse) {
  600. if (this.writingResponse == writingResponse) {
  601. throw new IllegalArgumentException(
  602. "The old value is same as the new value");
  603. }
  604. /*
  605. * the right hand side of the && is unnecessary here because of the
  606. * if-clause above, but rigorous coding is always rigorous coding.
  607. */
  608. if (!writingResponse && this.writingResponse) {
  609. // Bump sync id when done writing - the client is not expected to
  610. // know about anything happening after this moment.
  611. currentSyncId++;
  612. }
  613. this.writingResponse = writingResponse;
  614. }
  615. /* Special serialization to JsonObjects which are not serializable */
  616. private void writeObject(java.io.ObjectOutputStream out)
  617. throws IOException {
  618. out.defaultWriteObject();
  619. // Convert JsonObjects in diff state to String representation as
  620. // JsonObject is not serializable
  621. HashMap<ClientConnector, String> stringDiffStates = new HashMap<>(
  622. diffStates.size() * 2);
  623. for (ClientConnector key : diffStates.keySet()) {
  624. stringDiffStates.put(key, diffStates.get(key).toString());
  625. }
  626. out.writeObject(stringDiffStates);
  627. }
  628. /* Special serialization to JsonObjects which are not serializable */
  629. private void readObject(java.io.ObjectInputStream in)
  630. throws IOException, ClassNotFoundException {
  631. in.defaultReadObject();
  632. // Read String versions of JsonObjects and parse into JsonObjects as
  633. // JsonObject is not serializable
  634. diffStates = new HashMap<>();
  635. @SuppressWarnings("unchecked")
  636. HashMap<ClientConnector, String> stringDiffStates = (HashMap<ClientConnector, String>) in
  637. .readObject();
  638. diffStates = new HashMap<>(stringDiffStates.size() * 2);
  639. for (ClientConnector key : stringDiffStates.keySet()) {
  640. try {
  641. diffStates.put(key, Json.parse(stringDiffStates.get(key)));
  642. } catch (JsonException e) {
  643. throw new IOException(e);
  644. }
  645. }
  646. }
  647. /**
  648. * Checks if the indicated connector has a StreamVariable of the given name
  649. * and returns the variable if one is found.
  650. *
  651. * @param connectorId
  652. * @param variableName
  653. * @return variable if a matching one exists, otherwise null
  654. */
  655. public StreamVariable getStreamVariable(String connectorId,
  656. String variableName) {
  657. if (pidToNameToStreamVariable == null) {
  658. return null;
  659. }
  660. Map<String, StreamVariable> map = pidToNameToStreamVariable
  661. .get(connectorId);
  662. if (map == null) {
  663. return null;
  664. }
  665. StreamVariable streamVariable = map.get(variableName);
  666. return streamVariable;
  667. }
  668. /**
  669. * Adds a StreamVariable of the given name to the indicated connector.
  670. *
  671. * @param connectorId
  672. * @param variableName
  673. * @param variable
  674. */
  675. public void addStreamVariable(String connectorId, String variableName,
  676. StreamVariable variable) {
  677. assert getConnector(connectorId) != null;
  678. if (pidToNameToStreamVariable == null) {
  679. pidToNameToStreamVariable = new HashMap<>();
  680. }
  681. Map<String, StreamVariable> nameToStreamVariable = pidToNameToStreamVariable
  682. .get(connectorId);
  683. if (nameToStreamVariable == null) {
  684. nameToStreamVariable = new HashMap<>();
  685. pidToNameToStreamVariable.put(connectorId, nameToStreamVariable);
  686. }
  687. nameToStreamVariable.put(variableName, variable);
  688. if (streamVariableToSeckey == null) {
  689. streamVariableToSeckey = new HashMap<>();
  690. }
  691. String seckey = streamVariableToSeckey.get(variable);
  692. if (seckey == null) {
  693. /*
  694. * Despite section 6 of RFC 4122, this particular use of UUID *is*
  695. * adequate for security capabilities. Type 4 UUIDs contain 122 bits
  696. * of random data, and UUID.randomUUID() is defined to use a
  697. * cryptographically secure random generator.
  698. */
  699. seckey = UUID.randomUUID().toString();
  700. streamVariableToSeckey.put(variable, seckey);
  701. }
  702. }
  703. /**
  704. * Removes StreamVariables that belong to connectors that are no longer
  705. * attached to the session.
  706. */
  707. private void cleanStreamVariables() {
  708. if (pidToNameToStreamVariable != null) {
  709. ConnectorTracker connectorTracker = uI.getConnectorTracker();
  710. Iterator<String> iterator = pidToNameToStreamVariable.keySet()
  711. .iterator();
  712. while (iterator.hasNext()) {
  713. String connectorId = iterator.next();
  714. if (connectorTracker.getConnector(connectorId) == null) {
  715. // Owner is no longer attached to the session
  716. Map<String, StreamVariable> removed = pidToNameToStreamVariable
  717. .get(connectorId);
  718. for (String key : removed.keySet()) {
  719. streamVariableToSeckey.remove(removed.get(key));
  720. }
  721. iterator.remove();
  722. }
  723. }
  724. }
  725. }
  726. /**
  727. * Removes any StreamVariable of the given name from the indicated
  728. * connector.
  729. *
  730. * @param connectorId
  731. * @param variableName
  732. */
  733. public void cleanStreamVariable(String connectorId, String variableName) {
  734. if (pidToNameToStreamVariable == null) {
  735. return;
  736. }
  737. Map<String, StreamVariable> nameToStreamVar = pidToNameToStreamVariable
  738. .get(connectorId);
  739. nameToStreamVar.remove(variableName);
  740. if (nameToStreamVar.isEmpty()) {
  741. pidToNameToStreamVariable.remove(connectorId);
  742. }
  743. }
  744. /**
  745. * Returns the security key associated with the given StreamVariable.
  746. *
  747. * @param variable
  748. * @return matching security key if one exists, null otherwise
  749. */
  750. public String getSeckey(StreamVariable variable) {
  751. if (streamVariableToSeckey == null) {
  752. return null;
  753. }
  754. return streamVariableToSeckey.get(variable);
  755. }
  756. /**
  757. * Gets the most recently generated server sync id.
  758. * <p>
  759. * The sync id is incremented by one whenever a new response is being
  760. * written. This id is then sent over to the client. The client then adds
  761. * the most recent sync id to each communication packet it sends back to the
  762. * server. This way, the server knows at what state the client is when the
  763. * packet is sent. If the state has changed on the server side since that,
  764. * the server can try to adjust the way it handles the actions from the
  765. * client side.
  766. * <p>
  767. * The sync id value <code>-1</code> is ignored to facilitate testing with
  768. * pre-recorded requests.
  769. *
  770. * @see #setWritingResponse(boolean)
  771. * @see #connectorWasPresentAsRequestWasSent(String, long)
  772. * @since 7.2
  773. * @return the current sync id
  774. */
  775. public int getCurrentSyncId() {
  776. return currentSyncId;
  777. }
  778. }