選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ConnectorTracker.java 33KB

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