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.

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