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.

VaadinSession.java 49KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server;
  17. import java.io.IOException;
  18. import java.io.ObjectInputStream;
  19. import java.io.ObjectOutputStream;
  20. import java.io.Serializable;
  21. import java.lang.reflect.Method;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.Enumeration;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.LinkedList;
  28. import java.util.List;
  29. import java.util.Locale;
  30. import java.util.Map;
  31. import java.util.Queue;
  32. import java.util.Set;
  33. import java.util.UUID;
  34. import java.util.concurrent.ConcurrentLinkedQueue;
  35. import java.util.concurrent.ExecutionException;
  36. import java.util.concurrent.Future;
  37. import java.util.concurrent.FutureTask;
  38. import java.util.concurrent.locks.Lock;
  39. import java.util.concurrent.locks.ReentrantLock;
  40. import java.util.logging.Level;
  41. import java.util.logging.Logger;
  42. import javax.portlet.PortletSession;
  43. import javax.servlet.http.HttpSession;
  44. import javax.servlet.http.HttpSessionBindingEvent;
  45. import javax.servlet.http.HttpSessionBindingListener;
  46. import com.vaadin.data.util.converter.Converter;
  47. import com.vaadin.data.util.converter.ConverterFactory;
  48. import com.vaadin.data.util.converter.DefaultConverterFactory;
  49. import com.vaadin.event.EventRouter;
  50. import com.vaadin.shared.communication.PushMode;
  51. import com.vaadin.ui.AbstractField;
  52. import com.vaadin.ui.Table;
  53. import com.vaadin.ui.UI;
  54. import com.vaadin.util.CurrentInstance;
  55. import com.vaadin.util.ReflectTools;
  56. /**
  57. * Contains everything that Vaadin needs to store for a specific user. This is
  58. * typically stored in a {@link HttpSession} or {@link PortletSession}, but
  59. * others storage mechanisms might also be used.
  60. * <p>
  61. * Everything inside a {@link VaadinSession} should be serializable to ensure
  62. * compatibility with schemes using serialization for persisting the session
  63. * data.
  64. *
  65. * @author Vaadin Ltd
  66. * @since 7.0.0
  67. */
  68. @SuppressWarnings("serial")
  69. public class VaadinSession implements HttpSessionBindingListener, Serializable {
  70. /**
  71. * Encapsulates a {@link Runnable} submitted using
  72. * {@link VaadinSession#access(Runnable)}. This class is used internally by
  73. * the framework and is not intended to be directly used by application
  74. * developers.
  75. *
  76. * @since 7.1
  77. * @author Vaadin Ltd
  78. */
  79. public static class FutureAccess extends FutureTask<Void> {
  80. /**
  81. * Snapshot of all non-inheritable current instances at the time this
  82. * object was created.
  83. */
  84. private final Map<Class<?>, CurrentInstance> instances = CurrentInstance
  85. .getInstances(true);
  86. private final VaadinSession session;
  87. private Runnable runnable;
  88. /**
  89. * Creates an instance for the given runnable
  90. *
  91. * @param session
  92. * the session to which the task belongs
  93. *
  94. * @param runnable
  95. * the runnable to run when this task is purged from the
  96. * queue
  97. */
  98. public FutureAccess(VaadinSession session, Runnable runnable) {
  99. super(runnable, null);
  100. this.session = session;
  101. this.runnable = runnable;
  102. }
  103. @Override
  104. public Void get() throws InterruptedException, ExecutionException {
  105. /*
  106. * Help the developer avoid programming patterns that cause
  107. * deadlocks unless implemented very carefully. get(long, TimeUnit)
  108. * does not have the same detection since a sensible timeout should
  109. * avoid completely locking up the application.
  110. *
  111. * Even though no deadlock could occur after the runnable has been
  112. * run, the check is always done as the deterministic behavior makes
  113. * it easier to detect potential problems.
  114. */
  115. VaadinService.verifyNoOtherSessionLocked(session);
  116. return super.get();
  117. }
  118. /**
  119. * Gets the current instance values that should be used when running
  120. * this task.
  121. *
  122. * @see CurrentInstance#restoreInstances(Map)
  123. *
  124. * @return a map of current instances.
  125. */
  126. public Map<Class<?>, CurrentInstance> getCurrentInstances() {
  127. return instances;
  128. }
  129. /**
  130. * Handles exceptions thrown during the execution of this task.
  131. *
  132. * @since 7.1.8
  133. * @param exception
  134. * the thrown exception.
  135. */
  136. public void handleError(Exception exception) {
  137. try {
  138. if (runnable instanceof ErrorHandlingRunnable) {
  139. ErrorHandlingRunnable errorHandlingRunnable = (ErrorHandlingRunnable) runnable;
  140. errorHandlingRunnable.handleError(exception);
  141. } else {
  142. ErrorEvent errorEvent = new ErrorEvent(exception);
  143. ErrorHandler errorHandler = ErrorEvent
  144. .findErrorHandler(session);
  145. if (errorHandler == null) {
  146. errorHandler = new DefaultErrorHandler();
  147. }
  148. errorHandler.error(errorEvent);
  149. }
  150. } catch (Exception e) {
  151. getLogger().log(Level.SEVERE, e.getMessage(), e);
  152. }
  153. }
  154. }
  155. /**
  156. * The lifecycle state of a VaadinSession.
  157. *
  158. * @since 7.2
  159. */
  160. public enum State {
  161. /**
  162. * The session is active and accepting client requests.
  163. */
  164. OPEN,
  165. /**
  166. * The {@link VaadinSession#close() close} method has been called; the
  167. * session will be closed as soon as the current request ends.
  168. */
  169. CLOSING,
  170. /**
  171. * The session is closed; all the {@link UI}s have been removed and
  172. * {@link SessionDestroyListener}s have been called.
  173. */
  174. CLOSED;
  175. private boolean isValidChange(State newState) {
  176. return (this == OPEN && newState == CLOSING)
  177. || (this == CLOSING && newState == CLOSED);
  178. }
  179. }
  180. /**
  181. * The name of the parameter that is by default used in e.g. web.xml to
  182. * define the name of the default {@link UI} class.
  183. */
  184. // javadoc in UI should be updated if this value is changed
  185. public static final String UI_PARAMETER = "UI";
  186. private static final Method BOOTSTRAP_FRAGMENT_METHOD = ReflectTools
  187. .findMethod(BootstrapListener.class, "modifyBootstrapFragment",
  188. BootstrapFragmentResponse.class);
  189. private static final Method BOOTSTRAP_PAGE_METHOD = ReflectTools
  190. .findMethod(BootstrapListener.class, "modifyBootstrapPage",
  191. BootstrapPageResponse.class);
  192. /**
  193. * Configuration for the session.
  194. */
  195. private DeploymentConfiguration configuration;
  196. /**
  197. * Default locale of the session.
  198. */
  199. private Locale locale;
  200. /**
  201. * Session wide error handler which is used by default if an error is left
  202. * unhandled.
  203. */
  204. private ErrorHandler errorHandler = new DefaultErrorHandler();
  205. /**
  206. * The converter factory that is used to provide default converters for the
  207. * session.
  208. */
  209. private ConverterFactory converterFactory = new DefaultConverterFactory();
  210. private LinkedList<RequestHandler> requestHandlers = new LinkedList<RequestHandler>();
  211. private int nextUIId = 0;
  212. private Map<Integer, UI> uIs = new HashMap<Integer, UI>();
  213. private final Map<String, Integer> embedIdMap = new HashMap<String, Integer>();
  214. private final EventRouter eventRouter = new EventRouter();
  215. private GlobalResourceHandler globalResourceHandler;
  216. protected WebBrowser browser = new WebBrowser();
  217. private DragAndDropService dragAndDropService;
  218. private LegacyCommunicationManager communicationManager;
  219. private long cumulativeRequestDuration = 0;
  220. private long lastRequestDuration = -1;
  221. private long lastRequestTimestamp = System.currentTimeMillis();
  222. private State state = State.OPEN;
  223. private transient WrappedSession session;
  224. private final Map<String, Object> attributes = new HashMap<String, Object>();
  225. private LinkedList<UIProvider> uiProviders = new LinkedList<UIProvider>();
  226. private transient VaadinService service;
  227. private transient Lock lock;
  228. /*
  229. * Pending tasks can't be serialized and the queue should be empty when the
  230. * session is serialized as long as it doesn't happen while some other
  231. * thread has the lock.
  232. */
  233. private transient ConcurrentLinkedQueue<FutureAccess> pendingAccessQueue = new ConcurrentLinkedQueue<FutureAccess>();
  234. /**
  235. * Creates a new VaadinSession tied to a VaadinService.
  236. *
  237. * @param service
  238. * the Vaadin service for the new session
  239. */
  240. public VaadinSession(VaadinService service) {
  241. this.service = service;
  242. }
  243. /**
  244. * @see javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
  245. */
  246. @Override
  247. public void valueBound(HttpSessionBindingEvent arg0) {
  248. // We are not interested in bindings
  249. }
  250. /**
  251. * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
  252. */
  253. @Override
  254. public void valueUnbound(HttpSessionBindingEvent event) {
  255. // If we are going to be unbound from the session, the session must be
  256. // closing
  257. // Notify the service
  258. if (service == null) {
  259. getLogger()
  260. .warning(
  261. "A VaadinSession instance not associated to any service is getting unbound. "
  262. + "Session destroy events will not be fired and UIs in the session will not get detached. "
  263. + "This might happen if a session is deserialized but never used before it expires.");
  264. } else if (VaadinService.getCurrentRequest() != null
  265. && getCurrent() == this) {
  266. assert hasLock();
  267. // Ignore if the session is being moved to a different backing
  268. // session or if GAEVaadinServlet is doing its normal cleanup.
  269. if (getAttribute(VaadinService.PRESERVE_UNBOUND_SESSION_ATTRIBUTE) == Boolean.TRUE) {
  270. return;
  271. }
  272. // There is still a request in progress for this session. The
  273. // session will be destroyed after the response has been written.
  274. if (getState() == State.OPEN) {
  275. close();
  276. }
  277. } else {
  278. // We are not in a request related to this session so we can destroy
  279. // it as soon as we acquire the lock.
  280. service.fireSessionDestroy(this);
  281. }
  282. session = null;
  283. }
  284. /**
  285. * Get the web browser associated with this session.
  286. *
  287. * @return the web browser object
  288. *
  289. * @deprecated As of 7.0, use {@link Page#getWebBrowser()} instead.
  290. */
  291. @Deprecated
  292. public WebBrowser getBrowser() {
  293. assert hasLock();
  294. return browser;
  295. }
  296. /**
  297. * @return The total time spent servicing requests in this session, in
  298. * milliseconds.
  299. */
  300. public long getCumulativeRequestDuration() {
  301. assert hasLock();
  302. return cumulativeRequestDuration;
  303. }
  304. /**
  305. * Sets the time spent servicing the last request in the session and updates
  306. * the total time spent servicing requests in this session.
  307. *
  308. * @param time
  309. * The time spent in the last request, in milliseconds.
  310. */
  311. public void setLastRequestDuration(long time) {
  312. assert hasLock();
  313. lastRequestDuration = time;
  314. cumulativeRequestDuration += time;
  315. }
  316. /**
  317. * @return The time spent servicing the last request in this session, in
  318. * milliseconds.
  319. */
  320. public long getLastRequestDuration() {
  321. assert hasLock();
  322. return lastRequestDuration;
  323. }
  324. /**
  325. * Sets the time when the last UIDL request was serviced in this session.
  326. *
  327. * @param timestamp
  328. * The time when the last request was handled, in milliseconds
  329. * since the epoch.
  330. *
  331. */
  332. public void setLastRequestTimestamp(long timestamp) {
  333. assert hasLock();
  334. lastRequestTimestamp = timestamp;
  335. }
  336. /**
  337. * Returns the time when the last request was serviced in this session.
  338. *
  339. * @return The time when the last request was handled, in milliseconds since
  340. * the epoch.
  341. */
  342. public long getLastRequestTimestamp() {
  343. assert hasLock();
  344. return lastRequestTimestamp;
  345. }
  346. /**
  347. * Gets the underlying session to which this service session is currently
  348. * associated.
  349. *
  350. * @return the wrapped session for this context
  351. */
  352. public WrappedSession getSession() {
  353. /*
  354. * This is used to fetch the underlying session and there is no need for
  355. * having a lock when doing this. On the contrary this is sometimes done
  356. * to be able to lock the session.
  357. */
  358. return session;
  359. }
  360. /**
  361. * @return
  362. *
  363. * @deprecated As of 7.0. Will likely change or be removed in a future
  364. * version
  365. */
  366. @Deprecated
  367. public LegacyCommunicationManager getCommunicationManager() {
  368. assert hasLock();
  369. return communicationManager;
  370. }
  371. public DragAndDropService getDragAndDropService() {
  372. if (dragAndDropService == null) {
  373. dragAndDropService = new DragAndDropService(this);
  374. }
  375. return dragAndDropService;
  376. }
  377. /**
  378. * Loads the VaadinSession for the given service and WrappedSession from the
  379. * HTTP session.
  380. *
  381. * @param service
  382. * The service the VaadinSession is associated with
  383. * @param underlyingSession
  384. * The wrapped HTTP session for the user
  385. * @return A VaadinSession instance for the service, session combination or
  386. * null if none was found.
  387. * @deprecated as of 7.6, call
  388. * {@link VaadinService#loadSession(WrappedSession)} instead
  389. */
  390. @Deprecated
  391. public static VaadinSession getForSession(VaadinService service,
  392. WrappedSession underlyingSession) {
  393. return service.loadSession(underlyingSession);
  394. }
  395. /**
  396. * Retrieves all {@link VaadinSession}s which are stored in the given HTTP
  397. * session
  398. *
  399. * @since 7.2
  400. * @param httpSession
  401. * the HTTP session
  402. * @return the found VaadinSessions
  403. */
  404. public static Collection<VaadinSession> getAllSessions(
  405. HttpSession httpSession) {
  406. Set<VaadinSession> sessions = new HashSet<VaadinSession>();
  407. Enumeration<String> attributeNames = httpSession.getAttributeNames();
  408. while (attributeNames.hasMoreElements()) {
  409. String attributeName = attributeNames.nextElement();
  410. if (attributeName.startsWith(VaadinSession.class.getName() + ".")) {
  411. Object value = httpSession.getAttribute(attributeName);
  412. if (value instanceof VaadinSession) {
  413. sessions.add((VaadinSession) value);
  414. }
  415. }
  416. }
  417. return sessions;
  418. }
  419. /**
  420. * Removes this VaadinSession from the HTTP session.
  421. *
  422. * @param service
  423. * The service this session is associated with
  424. * @deprecated as of 7.6, call
  425. * {@link VaadinService#removeSession(WrappedSession)} instead
  426. */
  427. @Deprecated
  428. public void removeFromSession(VaadinService service) {
  429. service.removeSession(session);
  430. }
  431. /**
  432. * Stores this VaadinSession in the HTTP session.
  433. *
  434. * @param service
  435. * The service this session is associated with
  436. * @param session
  437. * The HTTP session this VaadinSession should be stored in
  438. * @deprecated as of 7.6, call
  439. * {@link VaadinService#storeSession(VaadinSession, WrappedSession)}
  440. * instead
  441. */
  442. @Deprecated
  443. public void storeInSession(VaadinService service, WrappedSession session) {
  444. service.storeSession(this, session);
  445. }
  446. /**
  447. * Updates the transient session lock from VaadinService.
  448. */
  449. private void refreshLock() {
  450. assert lock == null || lock == service.getSessionLock(session) : "Cannot change the lock from one instance to another";
  451. assert hasLock(service, session);
  452. lock = service.getSessionLock(session);
  453. }
  454. public void setCommunicationManager(
  455. LegacyCommunicationManager communicationManager) {
  456. assert hasLock();
  457. if (communicationManager == null) {
  458. throw new IllegalArgumentException("Can not set to null");
  459. }
  460. assert this.communicationManager == null : "Communication manager can only be set once";
  461. this.communicationManager = communicationManager;
  462. }
  463. public void setConfiguration(DeploymentConfiguration configuration) {
  464. assert hasLock();
  465. if (configuration == null) {
  466. throw new IllegalArgumentException("Can not set to null");
  467. }
  468. assert this.configuration == null : "Configuration can only be set once";
  469. this.configuration = configuration;
  470. }
  471. /**
  472. * Gets the configuration for this session
  473. *
  474. * @return the deployment configuration
  475. */
  476. public DeploymentConfiguration getConfiguration() {
  477. assert hasLock();
  478. return configuration;
  479. }
  480. /**
  481. * Gets the default locale for this session.
  482. *
  483. * By default this is the preferred locale of the user using the session. In
  484. * most cases it is read from the browser defaults.
  485. *
  486. * @return the locale of this session.
  487. */
  488. public Locale getLocale() {
  489. assert hasLock();
  490. if (locale != null) {
  491. return locale;
  492. }
  493. return Locale.getDefault();
  494. }
  495. /**
  496. * Sets the default locale for this session.
  497. *
  498. * By default this is the preferred locale of the user using the
  499. * application. In most cases it is read from the browser defaults.
  500. *
  501. * @param locale
  502. * the Locale object.
  503. *
  504. */
  505. public void setLocale(Locale locale) {
  506. assert hasLock();
  507. this.locale = locale;
  508. }
  509. /**
  510. * Gets the session's error handler.
  511. *
  512. * @return the current error handler
  513. */
  514. public ErrorHandler getErrorHandler() {
  515. assert hasLock();
  516. return errorHandler;
  517. }
  518. /**
  519. * Sets the session error handler.
  520. *
  521. * @param errorHandler
  522. */
  523. public void setErrorHandler(ErrorHandler errorHandler) {
  524. assert hasLock();
  525. this.errorHandler = errorHandler;
  526. }
  527. /**
  528. * Gets the {@link ConverterFactory} used to locate a suitable
  529. * {@link Converter} for fields in the session.
  530. *
  531. * See {@link #setConverterFactory(ConverterFactory)} for more details
  532. *
  533. * @return The converter factory used in the session
  534. */
  535. public ConverterFactory getConverterFactory() {
  536. assert hasLock();
  537. return converterFactory;
  538. }
  539. /**
  540. * Sets the {@link ConverterFactory} used to locate a suitable
  541. * {@link Converter} for fields in the session.
  542. * <p>
  543. * The {@link ConverterFactory} is used to find a suitable converter when
  544. * binding data to a UI component and the data type does not match the UI
  545. * component type, e.g. binding a Double to a TextField (which is based on a
  546. * String).
  547. * </p>
  548. * <p>
  549. * The {@link Converter} for an individual field can be overridden using
  550. * {@link AbstractField#setConverter(Converter)} and for individual property
  551. * ids in a {@link Table} using
  552. * {@link Table#setConverter(Object, Converter)}.
  553. * </p>
  554. * <p>
  555. * The converter factory must never be set to null.
  556. *
  557. * @param converterFactory
  558. * The converter factory used in the session
  559. */
  560. public void setConverterFactory(ConverterFactory converterFactory) {
  561. assert hasLock();
  562. this.converterFactory = converterFactory;
  563. }
  564. /**
  565. * Adds a request handler to this session. Request handlers can be added to
  566. * provide responses to requests that are not handled by the default
  567. * functionality of the framework.
  568. * <p>
  569. * Handlers are called in reverse order of addition, so the most recently
  570. * added handler will be called first.
  571. * </p>
  572. *
  573. * @param handler
  574. * the request handler to add
  575. *
  576. * @see #removeRequestHandler(RequestHandler)
  577. *
  578. * @since 7.0
  579. */
  580. public void addRequestHandler(RequestHandler handler) {
  581. assert hasLock();
  582. requestHandlers.addFirst(handler);
  583. }
  584. /**
  585. * Removes a request handler from the session.
  586. *
  587. * @param handler
  588. * the request handler to remove
  589. *
  590. * @since 7.0
  591. */
  592. public void removeRequestHandler(RequestHandler handler) {
  593. assert hasLock();
  594. requestHandlers.remove(handler);
  595. }
  596. /**
  597. * Gets the request handlers that are registered to the session. The
  598. * iteration order of the returned collection is the same as the order in
  599. * which the request handlers will be invoked when a request is handled.
  600. *
  601. * @return a collection of request handlers, with the iteration order
  602. * according to the order they would be invoked
  603. *
  604. * @see #addRequestHandler(RequestHandler)
  605. * @see #removeRequestHandler(RequestHandler)
  606. *
  607. * @since 7.0
  608. */
  609. public Collection<RequestHandler> getRequestHandlers() {
  610. assert hasLock();
  611. return Collections.unmodifiableCollection(requestHandlers);
  612. }
  613. /**
  614. * Gets the currently used session. The current session is automatically
  615. * defined when processing requests to the server and in threads started at
  616. * a point when the current session is defined (see
  617. * {@link InheritableThreadLocal}). In other cases, (e.g. from background
  618. * threads started in some other way), the current session is not
  619. * automatically defined.
  620. * <p>
  621. * The session is stored using a weak reference to avoid leaking memory in
  622. * case it is not explicitly cleared.
  623. *
  624. * @return the current session instance if available, otherwise
  625. * <code>null</code>
  626. *
  627. * @see #setCurrent(VaadinSession)
  628. *
  629. * @since 7.0
  630. */
  631. public static VaadinSession getCurrent() {
  632. return CurrentInstance.get(VaadinSession.class);
  633. }
  634. /**
  635. * Sets the thread local for the current session. This method is used by the
  636. * framework to set the current session whenever a new request is processed
  637. * and it is cleared when the request has been processed.
  638. * <p>
  639. * The application developer can also use this method to define the current
  640. * session outside the normal request handling and treads started from
  641. * request handling threads, e.g. when initiating custom background threads.
  642. * <p>
  643. * The session is stored using a weak reference to avoid leaking memory in
  644. * case it is not explicitly cleared.
  645. *
  646. * @param session
  647. * the session to set as current
  648. *
  649. * @see #getCurrent()
  650. * @see ThreadLocal
  651. *
  652. * @since 7.0
  653. */
  654. public static void setCurrent(VaadinSession session) {
  655. CurrentInstance.setInheritable(VaadinSession.class, session);
  656. }
  657. /**
  658. * Gets all the UIs of this session. This includes UIs that have been
  659. * requested but not yet initialized. UIs that receive no heartbeat requests
  660. * from the client are eventually removed from the session.
  661. *
  662. * @return a collection of UIs belonging to this application
  663. *
  664. * @since 7.0
  665. */
  666. public Collection<UI> getUIs() {
  667. assert hasLock();
  668. return Collections.unmodifiableCollection(uIs.values());
  669. }
  670. private int connectorIdSequence = 0;
  671. private final String csrfToken = UUID.randomUUID().toString();
  672. /**
  673. * Generate an id for the given Connector. Connectors must not call this
  674. * method more than once, the first time they need an id.
  675. *
  676. * @param connector
  677. * A connector that has not yet been assigned an id.
  678. * @return A new id for the connector
  679. *
  680. * @deprecated As of 7.0. Will likely change or be removed in a future
  681. * version
  682. */
  683. @Deprecated
  684. public String createConnectorId(ClientConnector connector) {
  685. assert hasLock();
  686. return String.valueOf(connectorIdSequence++);
  687. }
  688. /**
  689. * Returns a UI with the given id.
  690. * <p>
  691. * This is meant for framework internal use.
  692. * </p>
  693. *
  694. * @param uiId
  695. * The UI id
  696. * @return The UI with the given id or null if not found
  697. */
  698. public UI getUIById(int uiId) {
  699. assert hasLock();
  700. return uIs.get(uiId);
  701. }
  702. /**
  703. * Checks if the current thread has exclusive access to this VaadinSession
  704. *
  705. * @return true if the thread has exclusive access, false otherwise
  706. * @since 7.1
  707. */
  708. public boolean hasLock() {
  709. ReentrantLock l = ((ReentrantLock) getLockInstance());
  710. return l.isHeldByCurrentThread();
  711. }
  712. /**
  713. * Checks if the current thread has exclusive access to the given
  714. * WrappedSession.
  715. *
  716. * @return true if this thread has exclusive access, false otherwise
  717. * @since 7.6
  718. */
  719. protected static boolean hasLock(VaadinService service,
  720. WrappedSession session) {
  721. ReentrantLock l = (ReentrantLock) service.getSessionLock(session);
  722. return l.isHeldByCurrentThread();
  723. }
  724. /**
  725. * Adds a listener that will be invoked when the bootstrap HTML is about to
  726. * be generated. This can be used to modify the contents of the HTML that
  727. * loads the Vaadin application in the browser and the HTTP headers that are
  728. * included in the response serving the HTML.
  729. *
  730. * @see BootstrapListener#modifyBootstrapFragment(BootstrapFragmentResponse)
  731. * @see BootstrapListener#modifyBootstrapPage(BootstrapPageResponse)
  732. *
  733. * @param listener
  734. * the bootstrap listener to add
  735. */
  736. public void addBootstrapListener(BootstrapListener listener) {
  737. assert hasLock();
  738. eventRouter.addListener(BootstrapFragmentResponse.class, listener,
  739. BOOTSTRAP_FRAGMENT_METHOD);
  740. eventRouter.addListener(BootstrapPageResponse.class, listener,
  741. BOOTSTRAP_PAGE_METHOD);
  742. }
  743. /**
  744. * Remove a bootstrap listener that was previously added.
  745. *
  746. * @see #addBootstrapListener(BootstrapListener)
  747. *
  748. * @param listener
  749. * the bootstrap listener to remove
  750. */
  751. public void removeBootstrapListener(BootstrapListener listener) {
  752. assert hasLock();
  753. eventRouter.removeListener(BootstrapFragmentResponse.class, listener,
  754. BOOTSTRAP_FRAGMENT_METHOD);
  755. eventRouter.removeListener(BootstrapPageResponse.class, listener,
  756. BOOTSTRAP_PAGE_METHOD);
  757. }
  758. /**
  759. * Fires a bootstrap event to all registered listeners. There are currently
  760. * two supported events, both inheriting from {@link BootstrapResponse}:
  761. * {@link BootstrapFragmentResponse} and {@link BootstrapPageResponse}.
  762. *
  763. * @param response
  764. * the bootstrap response event for which listeners should be
  765. * fired
  766. *
  767. * @deprecated As of 7.0. Will likely change or be removed in a future
  768. * version
  769. */
  770. @Deprecated
  771. public void modifyBootstrapResponse(BootstrapResponse response) {
  772. assert hasLock();
  773. eventRouter.fireEvent(response);
  774. }
  775. /**
  776. * Called by the framework to remove an UI instance from the session because
  777. * it has been closed.
  778. *
  779. * @param ui
  780. * the UI to remove
  781. */
  782. public void removeUI(UI ui) {
  783. assert hasLock();
  784. assert UI.getCurrent() == ui;
  785. Integer id = Integer.valueOf(ui.getUIId());
  786. ui.setSession(null);
  787. uIs.remove(id);
  788. String embedId = ui.getEmbedId();
  789. if (embedId != null && id.equals(embedIdMap.get(embedId))) {
  790. embedIdMap.remove(embedId);
  791. }
  792. }
  793. /**
  794. * Gets this session's global resource handler that takes care of serving
  795. * connector resources that are not served by any single connector because
  796. * e.g. because they are served with strong caching or because of legacy
  797. * reasons.
  798. *
  799. * @param createOnDemand
  800. * <code>true</code> if a resource handler should be initialized
  801. * if there is no handler associated with this application.
  802. * </code>false</code> if </code>null</code> should be returned
  803. * if there is no registered handler.
  804. * @return this session's global resource handler, or <code>null</code> if
  805. * there is no handler and the createOnDemand parameter is
  806. * <code>false</code>.
  807. *
  808. * @since 7.0.0
  809. */
  810. public GlobalResourceHandler getGlobalResourceHandler(boolean createOnDemand) {
  811. assert hasLock();
  812. if (globalResourceHandler == null && createOnDemand) {
  813. globalResourceHandler = new GlobalResourceHandler();
  814. addRequestHandler(globalResourceHandler);
  815. }
  816. return globalResourceHandler;
  817. }
  818. /**
  819. * Gets the {@link Lock} instance that is used for protecting the data of
  820. * this session from concurrent access.
  821. * <p>
  822. * The <code>Lock</code> can be used to gain more control than what is
  823. * available only using {@link #lock()} and {@link #unlock()}. The returned
  824. * instance is not guaranteed to support any other features of the
  825. * <code>Lock</code> interface than {@link Lock#lock()} and
  826. * {@link Lock#unlock()}.
  827. *
  828. * @return the <code>Lock</code> that is used for synchronization, never
  829. * <code>null</code>
  830. *
  831. * @see #lock()
  832. * @see Lock
  833. */
  834. public Lock getLockInstance() {
  835. return lock;
  836. }
  837. /**
  838. * Locks this session to protect its data from concurrent access. Accessing
  839. * the UI state from outside the normal request handling should always lock
  840. * the session and unlock it when done. The preferred way to ensure locking
  841. * is done correctly is to wrap your code using {@link UI#access(Runnable)}
  842. * (or {@link VaadinSession#access(Runnable)} if you are only touching the
  843. * session and not any UI), e.g.:
  844. *
  845. * <pre>
  846. * myUI.access(new Runnable() {
  847. * &#064;Override
  848. * public void run() {
  849. * // Here it is safe to update the UI.
  850. * // UI.getCurrent can also be used
  851. * myUI.getContent().setCaption(&quot;Changed safely&quot;);
  852. * }
  853. * });
  854. * </pre>
  855. *
  856. * If you for whatever reason want to do locking manually, you should do it
  857. * like:
  858. *
  859. * <pre>
  860. * session.lock();
  861. * try {
  862. * doSomething();
  863. * } finally {
  864. * session.unlock();
  865. * }
  866. * </pre>
  867. *
  868. * This method will block until the lock can be retrieved.
  869. * <p>
  870. * {@link #getLockInstance()} can be used if more control over the locking
  871. * is required.
  872. *
  873. * @see #unlock()
  874. * @see #getLockInstance()
  875. * @see #hasLock()
  876. */
  877. public void lock() {
  878. getLockInstance().lock();
  879. }
  880. /**
  881. * Unlocks this session. This method should always be used in a finally
  882. * block after {@link #lock()} to ensure that the lock is always released.
  883. * <p>
  884. * For UIs in this session that have its push mode set to
  885. * {@link PushMode#AUTOMATIC automatic}, pending changes will be pushed to
  886. * their respective clients.
  887. *
  888. * @see #lock()
  889. * @see UI#push()
  890. */
  891. public void unlock() {
  892. assert hasLock();
  893. boolean ultimateRelease = false;
  894. try {
  895. /*
  896. * Run pending tasks and push if the reentrant lock will actually be
  897. * released by this unlock() invocation.
  898. */
  899. if (((ReentrantLock) getLockInstance()).getHoldCount() == 1) {
  900. ultimateRelease = true;
  901. getService().runPendingAccessTasks(this);
  902. for (UI ui : getUIs()) {
  903. if (ui.getPushConfiguration().getPushMode() == PushMode.AUTOMATIC) {
  904. Map<Class<?>, CurrentInstance> oldCurrent = CurrentInstance
  905. .setCurrent(ui);
  906. try {
  907. ui.push();
  908. } finally {
  909. CurrentInstance.restoreInstances(oldCurrent);
  910. }
  911. }
  912. }
  913. }
  914. } finally {
  915. getLockInstance().unlock();
  916. }
  917. /*
  918. * If the session is locked when a new access task is added, it is
  919. * assumed that the queue will be purged when the lock is released. This
  920. * might however not happen if a task is enqueued between the moment
  921. * when unlock() purges the queue and the moment when the lock is
  922. * actually released. This means that the queue should be purged again
  923. * if it is not empty after unlocking.
  924. */
  925. if (ultimateRelease && !getPendingAccessQueue().isEmpty()) {
  926. getService().ensureAccessQueuePurged(this);
  927. }
  928. }
  929. /**
  930. * Stores a value in this service session. This can be used to associate
  931. * data with the current user so that it can be retrieved at a later point
  932. * from some other part of the application. Setting the value to
  933. * <code>null</code> clears the stored value.
  934. *
  935. * @see #getAttribute(String)
  936. *
  937. * @param name
  938. * the name to associate the value with, can not be
  939. * <code>null</code>
  940. * @param value
  941. * the value to associate with the name, or <code>null</code> to
  942. * remove a previous association.
  943. */
  944. public void setAttribute(String name, Object value) {
  945. assert hasLock();
  946. if (name == null) {
  947. throw new IllegalArgumentException("name can not be null");
  948. }
  949. if (value != null) {
  950. attributes.put(name, value);
  951. } else {
  952. attributes.remove(name);
  953. }
  954. }
  955. /**
  956. * Stores a value in this service session. This can be used to associate
  957. * data with the current user so that it can be retrieved at a later point
  958. * from some other part of the application. Setting the value to
  959. * <code>null</code> clears the stored value.
  960. * <p>
  961. * The fully qualified name of the type is used as the name when storing the
  962. * value. The outcome of calling this method is thus the same as if calling<br />
  963. * <br />
  964. * <code>setAttribute(type.getName(), value);</code>
  965. *
  966. * @see #getAttribute(Class)
  967. * @see #setAttribute(String, Object)
  968. *
  969. * @param type
  970. * the type that the stored value represents, can not be null
  971. * @param value
  972. * the value to associate with the type, or <code>null</code> to
  973. * remove a previous association.
  974. */
  975. public <T> void setAttribute(Class<T> type, T value) {
  976. assert hasLock();
  977. if (type == null) {
  978. throw new IllegalArgumentException("type can not be null");
  979. }
  980. if (value != null && !type.isInstance(value)) {
  981. throw new IllegalArgumentException("value of type "
  982. + type.getName() + " expected but got "
  983. + value.getClass().getName());
  984. }
  985. setAttribute(type.getName(), value);
  986. }
  987. /**
  988. * Gets a stored attribute value. If a value has been stored for the
  989. * session, that value is returned. If no value is stored for the name,
  990. * <code>null</code> is returned.
  991. *
  992. * @see #setAttribute(String, Object)
  993. *
  994. * @param name
  995. * the name of the value to get, can not be <code>null</code>.
  996. * @return the value, or <code>null</code> if no value has been stored or if
  997. * it has been set to null.
  998. */
  999. public Object getAttribute(String name) {
  1000. assert hasLock();
  1001. if (name == null) {
  1002. throw new IllegalArgumentException("name can not be null");
  1003. }
  1004. return attributes.get(name);
  1005. }
  1006. /**
  1007. * Gets a stored attribute value. If a value has been stored for the
  1008. * session, that value is returned. If no value is stored for the name,
  1009. * <code>null</code> is returned.
  1010. * <p>
  1011. * The fully qualified name of the type is used as the name when getting the
  1012. * value. The outcome of calling this method is thus the same as if calling<br />
  1013. * <br />
  1014. * <code>getAttribute(type.getName());</code>
  1015. *
  1016. * @see #setAttribute(Class, Object)
  1017. * @see #getAttribute(String)
  1018. *
  1019. * @param type
  1020. * the type of the value to get, can not be <code>null</code>.
  1021. * @return the value, or <code>null</code> if no value has been stored or if
  1022. * it has been set to null.
  1023. */
  1024. public <T> T getAttribute(Class<T> type) {
  1025. assert hasLock();
  1026. if (type == null) {
  1027. throw new IllegalArgumentException("type can not be null");
  1028. }
  1029. Object value = getAttribute(type.getName());
  1030. if (value == null) {
  1031. return null;
  1032. } else {
  1033. return type.cast(value);
  1034. }
  1035. }
  1036. /**
  1037. * Creates a new unique id for a UI.
  1038. *
  1039. * @return a unique UI id
  1040. */
  1041. public int getNextUIid() {
  1042. assert hasLock();
  1043. return nextUIId++;
  1044. }
  1045. /**
  1046. * Adds an initialized UI to this session.
  1047. *
  1048. * @param ui
  1049. * the initialized UI to add.
  1050. */
  1051. public void addUI(UI ui) {
  1052. assert hasLock();
  1053. if (ui.getUIId() == -1) {
  1054. throw new IllegalArgumentException(
  1055. "Can not add an UI that has not been initialized.");
  1056. }
  1057. if (ui.getSession() != this) {
  1058. throw new IllegalArgumentException(
  1059. "The UI belongs to a different session");
  1060. }
  1061. Integer uiId = Integer.valueOf(ui.getUIId());
  1062. uIs.put(uiId, ui);
  1063. String embedId = ui.getEmbedId();
  1064. if (embedId != null) {
  1065. Integer previousUiId = embedIdMap.put(embedId, uiId);
  1066. if (previousUiId != null) {
  1067. UI previousUi = uIs.get(previousUiId);
  1068. assert previousUi != null
  1069. && embedId.equals(previousUi.getEmbedId()) : "UI id map and embed id map not in sync";
  1070. // Will fire cleanup events at the end of the request handling.
  1071. previousUi.close();
  1072. }
  1073. }
  1074. }
  1075. /**
  1076. * Adds a UI provider to this session.
  1077. *
  1078. * @param uiProvider
  1079. * the UI provider that should be added
  1080. */
  1081. public void addUIProvider(UIProvider uiProvider) {
  1082. assert hasLock();
  1083. uiProviders.addFirst(uiProvider);
  1084. }
  1085. /**
  1086. * Removes a UI provider association from this session.
  1087. *
  1088. * @param uiProvider
  1089. * the UI provider that should be removed
  1090. */
  1091. public void removeUIProvider(UIProvider uiProvider) {
  1092. assert hasLock();
  1093. uiProviders.remove(uiProvider);
  1094. }
  1095. /**
  1096. * Gets the UI providers configured for this session.
  1097. *
  1098. * @return an unmodifiable list of UI providers
  1099. */
  1100. public List<UIProvider> getUIProviders() {
  1101. assert hasLock();
  1102. return Collections.unmodifiableList(uiProviders);
  1103. }
  1104. public VaadinService getService() {
  1105. return service;
  1106. }
  1107. /**
  1108. * Sets this session to be closed and all UI state to be discarded at the
  1109. * end of the current request, or at the end of the next request if there is
  1110. * no ongoing one.
  1111. * <p>
  1112. * After the session has been discarded, any UIs that have been left open
  1113. * will give a Session Expired error and a new session will be created for
  1114. * serving new UIs.
  1115. * <p>
  1116. * To avoid causing out of sync errors, you should typically redirect to
  1117. * some other page using {@link Page#setLocation(String)} to make the
  1118. * browser unload the invalidated UI.
  1119. *
  1120. * @see SystemMessages#getSessionExpiredCaption()
  1121. *
  1122. */
  1123. public void close() {
  1124. assert hasLock();
  1125. state = State.CLOSING;
  1126. }
  1127. /**
  1128. * Returns whether this session is marked to be closed. Note that this
  1129. * method also returns true if the session is actually already closed.
  1130. *
  1131. * @see #close()
  1132. *
  1133. * @deprecated As of 7.2, use
  1134. * <code>{@link #getState() getState() != State.OPEN}</code>
  1135. * instead.
  1136. *
  1137. * @return true if this session is marked to be closed, false otherwise
  1138. */
  1139. @Deprecated
  1140. public boolean isClosing() {
  1141. assert hasLock();
  1142. return state == State.CLOSING || state == State.CLOSED;
  1143. }
  1144. /**
  1145. * Returns the lifecycle state of this session.
  1146. *
  1147. * @since 7.2
  1148. * @return the current state
  1149. */
  1150. public State getState() {
  1151. assert hasLock();
  1152. return state;
  1153. }
  1154. /**
  1155. * Sets the lifecycle state of this session. The allowed transitions are
  1156. * OPEN to CLOSING and CLOSING to CLOSED.
  1157. *
  1158. * @since 7.2
  1159. * @param state
  1160. * the new state
  1161. */
  1162. protected void setState(State state) {
  1163. assert hasLock();
  1164. assert this.state.isValidChange(state) : "Invalid session state change "
  1165. + this.state + "->" + state;
  1166. this.state = state;
  1167. }
  1168. private static final Logger getLogger() {
  1169. return Logger.getLogger(VaadinSession.class.getName());
  1170. }
  1171. /**
  1172. * Locks this session and runs the provided Runnable right away.
  1173. * <p>
  1174. * It is generally recommended to use {@link #access(Runnable)} instead of
  1175. * this method for accessing a session from a different thread as
  1176. * {@link #access(Runnable)} can be used while holding the lock of another
  1177. * session. To avoid causing deadlocks, this methods throws an exception if
  1178. * it is detected than another session is also locked by the current thread.
  1179. * </p>
  1180. * <p>
  1181. * This method behaves differently than {@link #access(Runnable)} in some
  1182. * situations:
  1183. * <ul>
  1184. * <li>If the current thread is currently holding the lock of this session,
  1185. * {@link #accessSynchronously(Runnable)} runs the task right away whereas
  1186. * {@link #access(Runnable)} defers the task to a later point in time.</li>
  1187. * <li>If some other thread is currently holding the lock for this session,
  1188. * {@link #accessSynchronously(Runnable)} blocks while waiting for the lock
  1189. * to be available whereas {@link #access(Runnable)} defers the task to a
  1190. * later point in time.</li>
  1191. * </ul>
  1192. * </p>
  1193. *
  1194. * @param runnable
  1195. * the runnable which accesses the session
  1196. *
  1197. * @throws IllegalStateException
  1198. * if the current thread holds the lock for another session
  1199. *
  1200. * @since 7.1
  1201. *
  1202. * @see #lock()
  1203. * @see #getCurrent()
  1204. * @see #access(Runnable)
  1205. * @see UI#accessSynchronously(Runnable)
  1206. */
  1207. public void accessSynchronously(Runnable runnable) {
  1208. VaadinService.verifyNoOtherSessionLocked(this);
  1209. Map<Class<?>, CurrentInstance> old = null;
  1210. lock();
  1211. try {
  1212. old = CurrentInstance.setCurrent(this);
  1213. runnable.run();
  1214. } finally {
  1215. unlock();
  1216. if (old != null) {
  1217. CurrentInstance.restoreInstances(old);
  1218. }
  1219. }
  1220. }
  1221. /**
  1222. * Provides exclusive access to this session from outside a request handling
  1223. * thread.
  1224. * <p>
  1225. * The given runnable is executed while holding the session lock to ensure
  1226. * exclusive access to this session. If this session is not locked, the lock
  1227. * will be acquired and the runnable is run right away. If this session is
  1228. * currently locked, the runnable will be run before that lock is released.
  1229. * </p>
  1230. * <p>
  1231. * RPC handlers for components inside this session do not need to use this
  1232. * method as the session is automatically locked by the framework during RPC
  1233. * handling.
  1234. * </p>
  1235. * <p>
  1236. * Please note that the runnable might be invoked on a different thread or
  1237. * later on the current thread, which means that custom thread locals might
  1238. * not have the expected values when the runnable is executed. Inheritable
  1239. * values in {@link CurrentInstance} will have the same values as when this
  1240. * method was invoked. {@link VaadinSession#getCurrent()} and
  1241. * {@link VaadinService#getCurrent()} are set according to this session
  1242. * before executing the runnable. Non-inheritable CurrentInstance values
  1243. * including {@link VaadinService#getCurrentRequest()} and
  1244. * {@link VaadinService#getCurrentResponse()} will not be defined.
  1245. * </p>
  1246. * <p>
  1247. * The returned future can be used to check for task completion and to
  1248. * cancel the task. To help avoiding deadlocks, {@link Future#get()} throws
  1249. * an exception if it is detected that the current thread holds the lock for
  1250. * some other session.
  1251. * </p>
  1252. *
  1253. * @see #lock()
  1254. * @see #getCurrent()
  1255. * @see #accessSynchronously(Runnable)
  1256. * @see UI#access(Runnable)
  1257. *
  1258. * @since 7.1
  1259. *
  1260. * @param runnable
  1261. * the runnable which accesses the session
  1262. * @return a future that can be used to check for task completion and to
  1263. * cancel the task
  1264. */
  1265. public Future<Void> access(Runnable runnable) {
  1266. return getService().accessSession(this, runnable);
  1267. }
  1268. /**
  1269. * Gets the queue of tasks submitted using {@link #access(Runnable)}. It is
  1270. * safe to call this method and access the returned queue without holding
  1271. * the {@link #lock() session lock}.
  1272. *
  1273. * @since 7.1
  1274. *
  1275. * @return the queue of pending access tasks
  1276. */
  1277. public Queue<FutureAccess> getPendingAccessQueue() {
  1278. return pendingAccessQueue;
  1279. }
  1280. /**
  1281. * Gets the CSRF token (aka double submit cookie) that is used to protect
  1282. * against Cross Site Request Forgery attacks.
  1283. *
  1284. * @since 7.1
  1285. * @return the csrf token string
  1286. */
  1287. public String getCsrfToken() {
  1288. assert hasLock();
  1289. return csrfToken;
  1290. }
  1291. /**
  1292. * Override default deserialization logic to account for transient
  1293. * {@link #pendingAccessQueue}.
  1294. */
  1295. private void readObject(ObjectInputStream stream) throws IOException,
  1296. ClassNotFoundException {
  1297. Map<Class<?>, CurrentInstance> old = CurrentInstance.setCurrent(this);
  1298. try {
  1299. stream.defaultReadObject();
  1300. pendingAccessQueue = new ConcurrentLinkedQueue<FutureAccess>();
  1301. } finally {
  1302. CurrentInstance.restoreInstances(old);
  1303. }
  1304. }
  1305. /**
  1306. * Override default serialization logic to avoid
  1307. * ConcurrentModificationException if the contents are modified while
  1308. * serialization is reading them.
  1309. */
  1310. private void writeObject(ObjectOutputStream out) throws IOException {
  1311. Lock lock = this.lock;
  1312. if (lock != null) {
  1313. lock.lock();
  1314. }
  1315. try {
  1316. out.defaultWriteObject();
  1317. } finally {
  1318. if (lock != null) {
  1319. lock.unlock();
  1320. }
  1321. }
  1322. }
  1323. /**
  1324. * Finds the UI with the corresponding embed id.
  1325. *
  1326. * @since 7.2
  1327. * @param embedId
  1328. * the embed id
  1329. * @return the UI with the corresponding embed id, or <code>null</code> if
  1330. * no UI is found
  1331. *
  1332. * @see UI#getEmbedId()
  1333. */
  1334. public UI getUIByEmbedId(String embedId) {
  1335. Integer uiId = embedIdMap.get(embedId);
  1336. if (uiId == null) {
  1337. return null;
  1338. } else {
  1339. return getUIById(uiId.intValue());
  1340. }
  1341. }
  1342. /**
  1343. * Refreshes the transient fields of the session to ensure they are up to
  1344. * date.
  1345. * <p>
  1346. * Called internally by the framework.
  1347. *
  1348. * @since 7.6
  1349. * @param wrappedSession
  1350. * the session this VaadinSession is stored in
  1351. * @param vaadinService
  1352. * the service associated with this VaadinSession
  1353. */
  1354. public void refreshTransients(WrappedSession wrappedSession,
  1355. VaadinService vaadinService) {
  1356. session = wrappedSession;
  1357. service = vaadinService;
  1358. refreshLock();
  1359. }
  1360. }