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

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