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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  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.findMethod(
  190. 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().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(
  269. 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(
  451. session) : "Cannot change the lock from one instance to another";
  452. assert hasLock(service, session);
  453. lock = service.getSessionLock(session);
  454. }
  455. public void setCommunicationManager(
  456. LegacyCommunicationManager communicationManager) {
  457. assert hasLock();
  458. if (communicationManager == null) {
  459. throw new IllegalArgumentException("Can not set to null");
  460. }
  461. assert this.communicationManager == null : "Communication manager can only be set once";
  462. this.communicationManager = communicationManager;
  463. }
  464. public void setConfiguration(DeploymentConfiguration configuration) {
  465. assert hasLock();
  466. if (configuration == null) {
  467. throw new IllegalArgumentException("Can not set to null");
  468. }
  469. assert this.configuration == null : "Configuration can only be set once";
  470. this.configuration = configuration;
  471. }
  472. /**
  473. * Gets the configuration for this session
  474. *
  475. * @return the deployment configuration
  476. */
  477. public DeploymentConfiguration getConfiguration() {
  478. assert hasLock();
  479. return configuration;
  480. }
  481. /**
  482. * Gets the default locale for this session.
  483. *
  484. * By default this is the preferred locale of the user using the session. In
  485. * most cases it is read from the browser defaults.
  486. *
  487. * @return the locale of this session.
  488. */
  489. public Locale getLocale() {
  490. assert hasLock();
  491. if (locale != null) {
  492. return locale;
  493. }
  494. return Locale.getDefault();
  495. }
  496. /**
  497. * Sets the default locale for this session.
  498. *
  499. * By default this is the preferred locale of the user using the
  500. * application. In most cases it is read from the browser defaults.
  501. *
  502. * @param locale
  503. * the Locale object.
  504. *
  505. */
  506. public void setLocale(Locale locale) {
  507. assert hasLock();
  508. this.locale = locale;
  509. }
  510. /**
  511. * Gets the session's error handler.
  512. *
  513. * @return the current error handler
  514. */
  515. public ErrorHandler getErrorHandler() {
  516. assert hasLock();
  517. return errorHandler;
  518. }
  519. /**
  520. * Sets the session error handler.
  521. *
  522. * @param errorHandler
  523. */
  524. public void setErrorHandler(ErrorHandler errorHandler) {
  525. assert hasLock();
  526. this.errorHandler = errorHandler;
  527. }
  528. /**
  529. * Gets the {@link ConverterFactory} used to locate a suitable
  530. * {@link Converter} for fields in the session.
  531. *
  532. * See {@link #setConverterFactory(ConverterFactory)} for more details
  533. *
  534. * @return The converter factory used in the session
  535. */
  536. public ConverterFactory getConverterFactory() {
  537. assert hasLock();
  538. return converterFactory;
  539. }
  540. /**
  541. * Sets the {@link ConverterFactory} used to locate a suitable
  542. * {@link Converter} for fields in the session.
  543. * <p>
  544. * The {@link ConverterFactory} is used to find a suitable converter when
  545. * binding data to a UI component and the data type does not match the UI
  546. * component type, e.g. binding a Double to a TextField (which is based on a
  547. * String).
  548. * </p>
  549. * <p>
  550. * The {@link Converter} for an individual field can be overridden using
  551. * {@link AbstractField#setConverter(Converter)} and for individual property
  552. * ids in a {@link Table} using
  553. * {@link Table#setConverter(Object, Converter)}.
  554. * </p>
  555. * <p>
  556. * The converter factory must never be set to null.
  557. *
  558. * @param converterFactory
  559. * The converter factory used in the session
  560. */
  561. public void setConverterFactory(ConverterFactory converterFactory) {
  562. assert hasLock();
  563. this.converterFactory = converterFactory;
  564. }
  565. /**
  566. * Adds a request handler to this session. Request handlers can be added to
  567. * provide responses to requests that are not handled by the default
  568. * functionality of the framework.
  569. * <p>
  570. * Handlers are called in reverse order of addition, so the most recently
  571. * added handler will be called first.
  572. * </p>
  573. *
  574. * @param handler
  575. * the request handler to add
  576. *
  577. * @see #removeRequestHandler(RequestHandler)
  578. *
  579. * @since 7.0
  580. */
  581. public void addRequestHandler(RequestHandler handler) {
  582. assert hasLock();
  583. requestHandlers.addFirst(handler);
  584. }
  585. /**
  586. * Removes a request handler from the session.
  587. *
  588. * @param handler
  589. * the request handler to remove
  590. *
  591. * @since 7.0
  592. */
  593. public void removeRequestHandler(RequestHandler handler) {
  594. assert hasLock();
  595. requestHandlers.remove(handler);
  596. }
  597. /**
  598. * Gets the request handlers that are registered to the session. The
  599. * iteration order of the returned collection is the same as the order in
  600. * which the request handlers will be invoked when a request is handled.
  601. *
  602. * @return a collection of request handlers, with the iteration order
  603. * according to the order they would be invoked
  604. *
  605. * @see #addRequestHandler(RequestHandler)
  606. * @see #removeRequestHandler(RequestHandler)
  607. *
  608. * @since 7.0
  609. */
  610. public Collection<RequestHandler> getRequestHandlers() {
  611. assert hasLock();
  612. return Collections.unmodifiableCollection(requestHandlers);
  613. }
  614. /**
  615. * Gets the currently used session. The current session is automatically
  616. * defined when processing requests to the server and in threads started at
  617. * a point when the current session is defined (see
  618. * {@link InheritableThreadLocal}). In other cases, (e.g. from background
  619. * threads started in some other way), the current session is not
  620. * automatically defined.
  621. * <p>
  622. * The session is stored using a weak reference to avoid leaking memory in
  623. * case it is not explicitly cleared.
  624. *
  625. * @return the current session instance if available, otherwise
  626. * <code>null</code>
  627. *
  628. * @see #setCurrent(VaadinSession)
  629. *
  630. * @since 7.0
  631. */
  632. public static VaadinSession getCurrent() {
  633. return CurrentInstance.get(VaadinSession.class);
  634. }
  635. /**
  636. * Sets the thread local for the current session. This method is used by the
  637. * framework to set the current session whenever a new request is processed
  638. * and it is cleared when the request has been processed.
  639. * <p>
  640. * The application developer can also use this method to define the current
  641. * session outside the normal request handling and treads started from
  642. * request handling threads, e.g. when initiating custom background threads.
  643. * <p>
  644. * The session is stored using a weak reference to avoid leaking memory in
  645. * case it is not explicitly cleared.
  646. *
  647. * @param session
  648. * the session to set as current
  649. *
  650. * @see #getCurrent()
  651. * @see ThreadLocal
  652. *
  653. * @since 7.0
  654. */
  655. public static void setCurrent(VaadinSession session) {
  656. CurrentInstance.setInheritable(VaadinSession.class, session);
  657. }
  658. /**
  659. * Gets all the UIs of this session. This includes UIs that have been
  660. * requested but not yet initialized. UIs that receive no heartbeat requests
  661. * from the client are eventually removed from the session.
  662. *
  663. * @return a collection of UIs belonging to this application
  664. *
  665. * @since 7.0
  666. */
  667. public Collection<UI> getUIs() {
  668. assert hasLock();
  669. return Collections.unmodifiableCollection(uIs.values());
  670. }
  671. private int connectorIdSequence = 0;
  672. private final String csrfToken = UUID.randomUUID().toString();
  673. private final String pushId = UUID.randomUUID().toString();
  674. /**
  675. * Generate an id for the given Connector. Connectors must not call this
  676. * method more than once, the first time they need an id.
  677. *
  678. * @param connector
  679. * A connector that has not yet been assigned an id.
  680. * @return A new id for the connector
  681. *
  682. * @deprecated As of 7.0. Will likely change or be removed in a future
  683. * version
  684. */
  685. @Deprecated
  686. public String createConnectorId(ClientConnector connector) {
  687. assert hasLock();
  688. return String.valueOf(connectorIdSequence++);
  689. }
  690. /**
  691. * Returns a UI with the given id.
  692. * <p>
  693. * This is meant for framework internal use.
  694. * </p>
  695. *
  696. * @param uiId
  697. * The UI id
  698. * @return The UI with the given id or null if not found
  699. */
  700. public UI getUIById(int uiId) {
  701. assert hasLock();
  702. return uIs.get(uiId);
  703. }
  704. /**
  705. * Checks if the current thread has exclusive access to this VaadinSession
  706. *
  707. * @return true if the thread has exclusive access, false otherwise
  708. * @since 7.1
  709. */
  710. public boolean hasLock() {
  711. ReentrantLock l = ((ReentrantLock) getLockInstance());
  712. return l.isHeldByCurrentThread();
  713. }
  714. /**
  715. * Checks if the current thread has exclusive access to the given
  716. * WrappedSession.
  717. *
  718. * @return true if this thread has exclusive access, false otherwise
  719. * @since 7.6
  720. */
  721. protected static boolean hasLock(VaadinService service,
  722. WrappedSession session) {
  723. ReentrantLock l = (ReentrantLock) service.getSessionLock(session);
  724. return l.isHeldByCurrentThread();
  725. }
  726. /**
  727. * Adds a listener that will be invoked when the bootstrap HTML is about to
  728. * be generated. This can be used to modify the contents of the HTML that
  729. * loads the Vaadin application in the browser and the HTTP headers that are
  730. * included in the response serving the HTML.
  731. *
  732. * @see BootstrapListener#modifyBootstrapFragment(BootstrapFragmentResponse)
  733. * @see BootstrapListener#modifyBootstrapPage(BootstrapPageResponse)
  734. *
  735. * @param listener
  736. * the bootstrap listener to add
  737. */
  738. public void addBootstrapListener(BootstrapListener listener) {
  739. assert hasLock();
  740. eventRouter.addListener(BootstrapFragmentResponse.class, listener,
  741. BOOTSTRAP_FRAGMENT_METHOD);
  742. eventRouter.addListener(BootstrapPageResponse.class, listener,
  743. BOOTSTRAP_PAGE_METHOD);
  744. }
  745. /**
  746. * Remove a bootstrap listener that was previously added.
  747. *
  748. * @see #addBootstrapListener(BootstrapListener)
  749. *
  750. * @param listener
  751. * the bootstrap listener to remove
  752. */
  753. public void removeBootstrapListener(BootstrapListener listener) {
  754. assert hasLock();
  755. eventRouter.removeListener(BootstrapFragmentResponse.class, listener,
  756. BOOTSTRAP_FRAGMENT_METHOD);
  757. eventRouter.removeListener(BootstrapPageResponse.class, listener,
  758. BOOTSTRAP_PAGE_METHOD);
  759. }
  760. /**
  761. * Fires a bootstrap event to all registered listeners. There are currently
  762. * two supported events, both inheriting from {@link BootstrapResponse}:
  763. * {@link BootstrapFragmentResponse} and {@link BootstrapPageResponse}.
  764. *
  765. * @param response
  766. * the bootstrap response event for which listeners should be
  767. * fired
  768. *
  769. * @deprecated As of 7.0. Will likely change or be removed in a future
  770. * version
  771. */
  772. @Deprecated
  773. public void modifyBootstrapResponse(BootstrapResponse response) {
  774. assert hasLock();
  775. eventRouter.fireEvent(response);
  776. }
  777. /**
  778. * Called by the framework to remove an UI instance from the session because
  779. * it has been closed.
  780. *
  781. * @param ui
  782. * the UI to remove
  783. */
  784. public void removeUI(UI ui) {
  785. assert hasLock();
  786. assert UI.getCurrent() == ui;
  787. Integer id = Integer.valueOf(ui.getUIId());
  788. ui.setSession(null);
  789. uIs.remove(id);
  790. String embedId = ui.getEmbedId();
  791. if (embedId != null && id.equals(embedIdMap.get(embedId))) {
  792. embedIdMap.remove(embedId);
  793. }
  794. }
  795. /**
  796. * Gets this session's global resource handler that takes care of serving
  797. * connector resources that are not served by any single connector because
  798. * e.g. because they are served with strong caching or because of legacy
  799. * reasons.
  800. *
  801. * @param createOnDemand
  802. * <code>true</code> if a resource handler should be initialized
  803. * if there is no handler associated with this application,
  804. * <code>false</code> if <code>null</code> should be returned if
  805. * there is no registered handler.
  806. * @return this session's global resource handler, or <code>null</code> if
  807. * there is no handler and the createOnDemand parameter is
  808. * <code>false</code>.
  809. *
  810. * @since 7.0.0
  811. */
  812. public GlobalResourceHandler getGlobalResourceHandler(
  813. boolean createOnDemand) {
  814. assert hasLock();
  815. if (globalResourceHandler == null && createOnDemand) {
  816. globalResourceHandler = new GlobalResourceHandler();
  817. addRequestHandler(globalResourceHandler);
  818. }
  819. return globalResourceHandler;
  820. }
  821. /**
  822. * Gets the {@link Lock} instance that is used for protecting the data of
  823. * this session from concurrent access.
  824. * <p>
  825. * The <code>Lock</code> can be used to gain more control than what is
  826. * available only using {@link #lock()} and {@link #unlock()}. The returned
  827. * instance is not guaranteed to support any other features of the
  828. * <code>Lock</code> interface than {@link Lock#lock()} and
  829. * {@link Lock#unlock()}.
  830. *
  831. * @return the <code>Lock</code> that is used for synchronization, never
  832. * <code>null</code>
  833. *
  834. * @see #lock()
  835. * @see Lock
  836. */
  837. public Lock getLockInstance() {
  838. return lock;
  839. }
  840. /**
  841. * Locks this session to protect its data from concurrent access. Accessing
  842. * the UI state from outside the normal request handling should always lock
  843. * the session and unlock it when done. The preferred way to ensure locking
  844. * is done correctly is to wrap your code using {@link UI#access(Runnable)}
  845. * (or {@link VaadinSession#access(Runnable)} if you are only touching the
  846. * session and not any UI), e.g.:
  847. *
  848. * <pre>
  849. * myUI.access(new Runnable() {
  850. * &#064;Override
  851. * public void run() {
  852. * // Here it is safe to update the UI.
  853. * // UI.getCurrent can also be used
  854. * myUI.getContent().setCaption(&quot;Changed safely&quot;);
  855. * }
  856. * });
  857. * </pre>
  858. *
  859. * If you for whatever reason want to do locking manually, you should do it
  860. * like:
  861. *
  862. * <pre>
  863. * session.lock();
  864. * try {
  865. * doSomething();
  866. * } finally {
  867. * session.unlock();
  868. * }
  869. * </pre>
  870. *
  871. * This method will block until the lock can be retrieved.
  872. * <p>
  873. * {@link #getLockInstance()} can be used if more control over the locking
  874. * is required.
  875. *
  876. * @see #unlock()
  877. * @see #getLockInstance()
  878. * @see #hasLock()
  879. */
  880. public void lock() {
  881. getLockInstance().lock();
  882. }
  883. /**
  884. * Unlocks this session. This method should always be used in a finally
  885. * block after {@link #lock()} to ensure that the lock is always released.
  886. * <p>
  887. * For UIs in this session that have its push mode set to
  888. * {@link PushMode#AUTOMATIC automatic}, pending changes will be pushed to
  889. * their respective clients.
  890. *
  891. * @see #lock()
  892. * @see UI#push()
  893. */
  894. public void unlock() {
  895. assert hasLock();
  896. boolean ultimateRelease = false;
  897. try {
  898. /*
  899. * Run pending tasks and push if the reentrant lock will actually be
  900. * released by this unlock() invocation.
  901. */
  902. if (((ReentrantLock) getLockInstance()).getHoldCount() == 1) {
  903. ultimateRelease = true;
  904. getService().runPendingAccessTasks(this);
  905. for (UI ui : getUIs()) {
  906. if (ui.getPushConfiguration()
  907. .getPushMode() == PushMode.AUTOMATIC) {
  908. Map<Class<?>, CurrentInstance> oldCurrent = CurrentInstance
  909. .setCurrent(ui);
  910. try {
  911. ui.push();
  912. } finally {
  913. CurrentInstance.restoreInstances(oldCurrent);
  914. }
  915. }
  916. try {
  917. ui.getConnectorTracker().cleanConnectorMap();
  918. } catch (Exception e) {
  919. getLogger().log(Level.SEVERE,
  920. "Exception while cleaning connector map for ui "
  921. + ui.getUIId(),
  922. e);
  923. } catch (AssertionError e) {
  924. getLogger().log(Level.SEVERE,
  925. "Exception while cleaning connector map for ui "
  926. + ui.getUIId(),
  927. e);
  928. }
  929. }
  930. }
  931. } finally {
  932. getLockInstance().unlock();
  933. }
  934. /*
  935. * If the session is locked when a new access task is added, it is
  936. * assumed that the queue will be purged when the lock is released. This
  937. * might however not happen if a task is enqueued between the moment
  938. * when unlock() purges the queue and the moment when the lock is
  939. * actually released. This means that the queue should be purged again
  940. * if it is not empty after unlocking.
  941. */
  942. if (ultimateRelease && !getPendingAccessQueue().isEmpty()) {
  943. getService().ensureAccessQueuePurged(this);
  944. }
  945. }
  946. /**
  947. * Stores a value in this service session. This can be used to associate
  948. * data with the current user so that it can be retrieved at a later point
  949. * from some other part of the application. Setting the value to
  950. * <code>null</code> clears the stored value.
  951. *
  952. * @see #getAttribute(String)
  953. *
  954. * @param name
  955. * the name to associate the value with, can not be
  956. * <code>null</code>
  957. * @param value
  958. * the value to associate with the name, or <code>null</code> to
  959. * remove a previous association.
  960. */
  961. public void setAttribute(String name, Object value) {
  962. assert hasLock();
  963. if (name == null) {
  964. throw new IllegalArgumentException("name can not be null");
  965. }
  966. if (value != null) {
  967. attributes.put(name, value);
  968. } else {
  969. attributes.remove(name);
  970. }
  971. }
  972. /**
  973. * Stores a value in this service session. This can be used to associate
  974. * data with the current user so that it can be retrieved at a later point
  975. * from some other part of the application. Setting the value to
  976. * <code>null</code> clears the stored value.
  977. * <p>
  978. * The fully qualified name of the type is used as the name when storing the
  979. * value. The outcome of calling this method is thus the same as if
  980. * calling<br />
  981. * <br />
  982. * <code>setAttribute(type.getName(), value);</code>
  983. *
  984. * @see #getAttribute(Class)
  985. * @see #setAttribute(String, Object)
  986. *
  987. * @param type
  988. * the type that the stored value represents, can not be null
  989. * @param value
  990. * the value to associate with the type, or <code>null</code> to
  991. * remove a previous association.
  992. */
  993. public <T> void setAttribute(Class<T> type, T value) {
  994. assert hasLock();
  995. if (type == null) {
  996. throw new IllegalArgumentException("type can not be null");
  997. }
  998. if (value != null && !type.isInstance(value)) {
  999. throw new IllegalArgumentException("value of type " + type.getName()
  1000. + " expected but got " + value.getClass().getName());
  1001. }
  1002. setAttribute(type.getName(), value);
  1003. }
  1004. /**
  1005. * Gets a stored attribute value. If a value has been stored for the
  1006. * session, that value is returned. If no value is stored for the name,
  1007. * <code>null</code> is returned.
  1008. *
  1009. * @see #setAttribute(String, Object)
  1010. *
  1011. * @param name
  1012. * the name of the value to get, can not be <code>null</code>.
  1013. * @return the value, or <code>null</code> if no value has been stored or if
  1014. * it has been set to null.
  1015. */
  1016. public Object getAttribute(String name) {
  1017. assert hasLock();
  1018. if (name == null) {
  1019. throw new IllegalArgumentException("name can not be null");
  1020. }
  1021. return attributes.get(name);
  1022. }
  1023. /**
  1024. * Gets a stored attribute value. If a value has been stored for the
  1025. * session, that value is returned. If no value is stored for the name,
  1026. * <code>null</code> is returned.
  1027. * <p>
  1028. * The fully qualified name of the type is used as the name when getting the
  1029. * value. The outcome of calling this method is thus the same as if
  1030. * calling<br />
  1031. * <br />
  1032. * <code>getAttribute(type.getName());</code>
  1033. *
  1034. * @see #setAttribute(Class, Object)
  1035. * @see #getAttribute(String)
  1036. *
  1037. * @param type
  1038. * the type of the value to get, can not be <code>null</code>.
  1039. * @return the value, or <code>null</code> if no value has been stored or if
  1040. * it has been set to null.
  1041. */
  1042. public <T> T getAttribute(Class<T> type) {
  1043. assert hasLock();
  1044. if (type == null) {
  1045. throw new IllegalArgumentException("type can not be null");
  1046. }
  1047. Object value = getAttribute(type.getName());
  1048. if (value == null) {
  1049. return null;
  1050. } else {
  1051. return type.cast(value);
  1052. }
  1053. }
  1054. /**
  1055. * Creates a new unique id for a UI.
  1056. *
  1057. * @return a unique UI id
  1058. */
  1059. public int getNextUIid() {
  1060. assert hasLock();
  1061. return nextUIId++;
  1062. }
  1063. /**
  1064. * Adds an initialized UI to this session.
  1065. *
  1066. * @param ui
  1067. * the initialized UI to add.
  1068. */
  1069. public void addUI(UI ui) {
  1070. assert hasLock();
  1071. if (ui.getUIId() == -1) {
  1072. throw new IllegalArgumentException(
  1073. "Can not add an UI that has not been initialized.");
  1074. }
  1075. if (ui.getSession() != this) {
  1076. throw new IllegalArgumentException(
  1077. "The UI belongs to a different session");
  1078. }
  1079. Integer uiId = Integer.valueOf(ui.getUIId());
  1080. uIs.put(uiId, ui);
  1081. String embedId = ui.getEmbedId();
  1082. if (embedId != null) {
  1083. Integer previousUiId = embedIdMap.put(embedId, uiId);
  1084. if (previousUiId != null) {
  1085. UI previousUi = uIs.get(previousUiId);
  1086. assert previousUi != null && embedId.equals(previousUi
  1087. .getEmbedId()) : "UI id map and embed id map not in sync";
  1088. // Will fire cleanup events at the end of the request handling.
  1089. previousUi.close();
  1090. }
  1091. }
  1092. }
  1093. /**
  1094. * Adds a UI provider to this session.
  1095. *
  1096. * @param uiProvider
  1097. * the UI provider that should be added
  1098. */
  1099. public void addUIProvider(UIProvider uiProvider) {
  1100. assert hasLock();
  1101. uiProviders.addFirst(uiProvider);
  1102. }
  1103. /**
  1104. * Removes a UI provider association from this session.
  1105. *
  1106. * @param uiProvider
  1107. * the UI provider that should be removed
  1108. */
  1109. public void removeUIProvider(UIProvider uiProvider) {
  1110. assert hasLock();
  1111. uiProviders.remove(uiProvider);
  1112. }
  1113. /**
  1114. * Gets the UI providers configured for this session.
  1115. *
  1116. * @return an unmodifiable list of UI providers
  1117. */
  1118. public List<UIProvider> getUIProviders() {
  1119. assert hasLock();
  1120. return Collections.unmodifiableList(uiProviders);
  1121. }
  1122. public VaadinService getService() {
  1123. return service;
  1124. }
  1125. /**
  1126. * Sets this session to be closed and all UI state to be discarded at the
  1127. * end of the current request, or at the end of the next request if there is
  1128. * no ongoing one.
  1129. * <p>
  1130. * After the session has been discarded, any UIs that have been left open
  1131. * will give a Session Expired error and a new session will be created for
  1132. * serving new UIs.
  1133. * <p>
  1134. * To avoid causing out of sync errors, you should typically redirect to
  1135. * some other page using {@link Page#setLocation(String)} to make the
  1136. * browser unload the invalidated UI.
  1137. *
  1138. * @see SystemMessages#getSessionExpiredCaption()
  1139. *
  1140. */
  1141. public void close() {
  1142. assert hasLock();
  1143. state = State.CLOSING;
  1144. }
  1145. /**
  1146. * Returns whether this session is marked to be closed. Note that this
  1147. * method also returns true if the session is actually already closed.
  1148. *
  1149. * @see #close()
  1150. *
  1151. * @deprecated As of 7.2, use
  1152. * <code>{@link #getState() getState() != State.OPEN}</code>
  1153. * instead.
  1154. *
  1155. * @return true if this session is marked to be closed, false otherwise
  1156. */
  1157. @Deprecated
  1158. public boolean isClosing() {
  1159. assert hasLock();
  1160. return state == State.CLOSING || state == State.CLOSED;
  1161. }
  1162. /**
  1163. * Returns the lifecycle state of this session.
  1164. *
  1165. * @since 7.2
  1166. * @return the current state
  1167. */
  1168. public State getState() {
  1169. assert hasLock();
  1170. return state;
  1171. }
  1172. /**
  1173. * Sets the lifecycle state of this session. The allowed transitions are
  1174. * OPEN to CLOSING and CLOSING to CLOSED.
  1175. *
  1176. * @since 7.2
  1177. * @param state
  1178. * the new state
  1179. */
  1180. protected void setState(State state) {
  1181. assert hasLock();
  1182. assert this.state.isValidChange(state) : "Invalid session state change "
  1183. + this.state + "->" + state;
  1184. this.state = state;
  1185. }
  1186. private static final Logger getLogger() {
  1187. return Logger.getLogger(VaadinSession.class.getName());
  1188. }
  1189. /**
  1190. * Locks this session and runs the provided Runnable right away.
  1191. * <p>
  1192. * It is generally recommended to use {@link #access(Runnable)} instead of
  1193. * this method for accessing a session from a different thread as
  1194. * {@link #access(Runnable)} can be used while holding the lock of another
  1195. * session. To avoid causing deadlocks, this methods throws an exception if
  1196. * it is detected than another session is also locked by the current thread.
  1197. * </p>
  1198. * <p>
  1199. * This method behaves differently than {@link #access(Runnable)} in some
  1200. * situations:
  1201. * <ul>
  1202. * <li>If the current thread is currently holding the lock of this session,
  1203. * {@link #accessSynchronously(Runnable)} runs the task right away whereas
  1204. * {@link #access(Runnable)} defers the task to a later point in time.</li>
  1205. * <li>If some other thread is currently holding the lock for this session,
  1206. * {@link #accessSynchronously(Runnable)} blocks while waiting for the lock
  1207. * to be available whereas {@link #access(Runnable)} defers the task to a
  1208. * later point in time.</li>
  1209. * </ul>
  1210. * </p>
  1211. *
  1212. * @param runnable
  1213. * the runnable which accesses the session
  1214. *
  1215. * @throws IllegalStateException
  1216. * if the current thread holds the lock for another session
  1217. *
  1218. * @since 7.1
  1219. *
  1220. * @see #lock()
  1221. * @see #getCurrent()
  1222. * @see #access(Runnable)
  1223. * @see UI#accessSynchronously(Runnable)
  1224. */
  1225. public void accessSynchronously(Runnable runnable) {
  1226. VaadinService.verifyNoOtherSessionLocked(this);
  1227. Map<Class<?>, CurrentInstance> old = null;
  1228. lock();
  1229. try {
  1230. old = CurrentInstance.setCurrent(this);
  1231. runnable.run();
  1232. } finally {
  1233. unlock();
  1234. if (old != null) {
  1235. CurrentInstance.restoreInstances(old);
  1236. }
  1237. }
  1238. }
  1239. /**
  1240. * Provides exclusive access to this session from outside a request handling
  1241. * thread.
  1242. * <p>
  1243. * The given runnable is executed while holding the session lock to ensure
  1244. * exclusive access to this session. If this session is not locked, the lock
  1245. * will be acquired and the runnable is run right away. If this session is
  1246. * currently locked, the runnable will be run before that lock is released.
  1247. * </p>
  1248. * <p>
  1249. * RPC handlers for components inside this session do not need to use this
  1250. * method as the session is automatically locked by the framework during RPC
  1251. * handling.
  1252. * </p>
  1253. * <p>
  1254. * Please note that the runnable might be invoked on a different thread or
  1255. * later on the current thread, which means that custom thread locals might
  1256. * not have the expected values when the runnable is executed. Inheritable
  1257. * values in {@link CurrentInstance} will have the same values as when this
  1258. * method was invoked. {@link VaadinSession#getCurrent()} and
  1259. * {@link VaadinService#getCurrent()} are set according to this session
  1260. * before executing the runnable. Non-inheritable CurrentInstance values
  1261. * including {@link VaadinService#getCurrentRequest()} and
  1262. * {@link VaadinService#getCurrentResponse()} will not be defined.
  1263. * </p>
  1264. * <p>
  1265. * The returned future can be used to check for task completion and to
  1266. * cancel the task. To help avoiding deadlocks, {@link Future#get()} throws
  1267. * an exception if it is detected that the current thread holds the lock for
  1268. * some other session.
  1269. * </p>
  1270. *
  1271. * @see #lock()
  1272. * @see #getCurrent()
  1273. * @see #accessSynchronously(Runnable)
  1274. * @see UI#access(Runnable)
  1275. *
  1276. * @since 7.1
  1277. *
  1278. * @param runnable
  1279. * the runnable which accesses the session
  1280. * @return a future that can be used to check for task completion and to
  1281. * cancel the task
  1282. */
  1283. public Future<Void> access(Runnable runnable) {
  1284. return getService().accessSession(this, runnable);
  1285. }
  1286. /**
  1287. * Gets the queue of tasks submitted using {@link #access(Runnable)}. It is
  1288. * safe to call this method and access the returned queue without holding
  1289. * the {@link #lock() session lock}.
  1290. *
  1291. * @since 7.1
  1292. *
  1293. * @return the queue of pending access tasks
  1294. */
  1295. public Queue<FutureAccess> getPendingAccessQueue() {
  1296. return pendingAccessQueue;
  1297. }
  1298. /**
  1299. * Gets the CSRF token (aka double submit cookie) that is used to protect
  1300. * against Cross Site Request Forgery attacks.
  1301. *
  1302. * @since 7.1
  1303. * @return the csrf token string
  1304. */
  1305. public String getCsrfToken() {
  1306. assert hasLock();
  1307. return csrfToken;
  1308. }
  1309. /**
  1310. * Gets the push connection identifier for this session. Used when
  1311. * establishing a push connection with the client.
  1312. *
  1313. * @return the push connection identifier string
  1314. * @since 7.7.11
  1315. */
  1316. public String getPushId() {
  1317. assert hasLock();
  1318. return pushId;
  1319. }
  1320. /**
  1321. * Override default deserialization logic to account for transient
  1322. * {@link #pendingAccessQueue}.
  1323. */
  1324. private void readObject(ObjectInputStream stream)
  1325. throws IOException, ClassNotFoundException {
  1326. Map<Class<?>, CurrentInstance> old = CurrentInstance.setCurrent(this);
  1327. try {
  1328. stream.defaultReadObject();
  1329. pendingAccessQueue = new ConcurrentLinkedQueue<FutureAccess>();
  1330. } finally {
  1331. CurrentInstance.restoreInstances(old);
  1332. }
  1333. }
  1334. /**
  1335. * Override default serialization logic to avoid
  1336. * ConcurrentModificationException if the contents are modified while
  1337. * serialization is reading them.
  1338. */
  1339. private void writeObject(ObjectOutputStream out) throws IOException {
  1340. Lock lock = this.lock;
  1341. if (lock != null) {
  1342. lock.lock();
  1343. }
  1344. try {
  1345. out.defaultWriteObject();
  1346. } finally {
  1347. if (lock != null) {
  1348. lock.unlock();
  1349. }
  1350. }
  1351. }
  1352. /**
  1353. * Finds the UI with the corresponding embed id.
  1354. *
  1355. * @since 7.2
  1356. * @param embedId
  1357. * the embed id
  1358. * @return the UI with the corresponding embed id, or <code>null</code> if
  1359. * no UI is found
  1360. *
  1361. * @see UI#getEmbedId()
  1362. */
  1363. public UI getUIByEmbedId(String embedId) {
  1364. Integer uiId = embedIdMap.get(embedId);
  1365. if (uiId == null) {
  1366. return null;
  1367. } else {
  1368. return getUIById(uiId.intValue());
  1369. }
  1370. }
  1371. /**
  1372. * Refreshes the transient fields of the session to ensure they are up to
  1373. * date.
  1374. * <p>
  1375. * Called internally by the framework.
  1376. *
  1377. * @since 7.6
  1378. * @param wrappedSession
  1379. * the session this VaadinSession is stored in
  1380. * @param vaadinService
  1381. * the service associated with this VaadinSession
  1382. */
  1383. public void refreshTransients(WrappedSession wrappedSession,
  1384. VaadinService vaadinService) {
  1385. session = wrappedSession;
  1386. service = vaadinService;
  1387. refreshLock();
  1388. }
  1389. }