/** * Gets the session the component is attached to. * * @return the session this component is attached to */ public VaadinSession getSession() { return getUI().getSession(); }
@Override public void run() { // We can acquire the lock after the request started this thread is processed // Needed to make sure that this is sent as a push message Lock lockInstance = ui.getSession().getLockInstance(); lockInstance.lock(); lockInstance.unlock(); ui.access(() -> execute(ui)); }
/** * Sets current instances for the UI and all related classes. The previously * defined values can be restored by passing the returned map to * {@link #restoreInstances(Map)}. * * * @param ui * The UI * @return A map containing the old values of the instances that this method * updated. */ public static Map<Class<?>, CurrentInstance> setCurrent(UI ui) { Map<Class<?>, CurrentInstance> old = setCurrent(ui.getSession()); old.put(UI.class, doSet(UI.class, ui)); return old; }
/** * Gets the instantiator to use for the given UI. * * @param ui * the attached UI for which to find an instantiator, not * <code>null</code> * @return the instantiator, not <code>null</code> */ static Instantiator get(UI ui) { assert ui != null; VaadinSession session = ui.getSession(); assert session != null; return session.getService().getInstantiator(); }
public void setLayoutToSession() { UI.getCurrent().getSession().setAttribute(SESSION_ATTRIBUTE_APP_LAYOUT, appLayout); }
public static AppLayout getCurrent() { return (AppLayout) UI.getCurrent().getSession().getAttribute(SESSION_ATTRIBUTE_APP_LAYOUT); }
/** * Adds an initialized UI to this session. * * @param ui * the initialized UI to add. */ public void addUI(UI ui) { checkHasLock(); if (ui.getUIId() == -1) { throw new IllegalArgumentException( "Can not add an UI that has not been initialized."); } if (ui.getSession() != this) { throw new IllegalArgumentException( "The UI belongs to a different session"); } uIs.put(ui.getUIId(), ui); }
/** * Adds the performance timing data (used by TestBench 3) to the UIDL * response. */ private JsonValue createPerformanceData(UI ui) { JsonArray timings = Json.createArray(); timings.set(0, ui.getSession().getCumulativeRequestDuration()); timings.set(1, ui.getSession().getLastRequestDuration()); return timings; }
private VaadinSession getSession() { NodeOwner owner = getNode().getOwner(); assert owner instanceof StateTree; return ((StateTree) owner).getUI().getSession(); }
private void handleInvocationData(UI ui, JsonObject invocationJson) { String type = invocationJson.getString(JsonConstants.RPC_TYPE); RpcInvocationHandler handler = getInvocationHandlers().get(type); if (handler == null) { throw new IllegalArgumentException( "Unsupported event type: " + type); } try { Optional<Runnable> handle = handler.handle(ui, invocationJson); assert !handle.isPresent() : "RPC handler " + handler.getClass().getName() + " returned a Runnable even though it shouldn't"; } catch (Exception e) { ui.getSession().getErrorHandler().error(new ErrorEvent(e)); } }
@Override public void handleError(Exception exception) { try { if (command instanceof ErrorHandlingCommand) { ErrorHandlingCommand errorHandlingCommand = (ErrorHandlingCommand) command; errorHandlingCommand.handleError(exception); } else { getSession().getErrorHandler() .error(new ErrorEvent(exception)); } } catch (Exception e) { getLogger().error(e.getMessage(), e); } } });
/** * Sets the navigation {@code handler} and the navigation {@code event} * for this action. * * @param handler * the navigation handler * @param event * the navigation event */ public void setReferences(NavigationHandler handler, NavigationEvent event) { if (event != null) { event.getUI().getSession().hasLock(); } else { assert UI.getCurrent() != null && UI.getCurrent().getSession().hasLock(); } this.handler = handler; this.event = event; }
@Override public void run() { // We can acquire the lock after the request started this thread is processed // Needed to make sure that this is sent as a push message Lock lockInstance = ui.getSession().getLockInstance(); lockInstance.lock(); lockInstance.unlock(); ui.access(() -> { Paragraph world = new Paragraph("World"); world.setId("world"); add(world); }); } }
/** * Resumes the page transition associated with the postponed event. */ public void proceed() { BeforeLeaveEvent.this.continueNavigationAction = null; if (handler != null && event != null) { if (!event.getUI().getSession().hasLock()) { throw new IllegalStateException( "The method 'proceed' may not be called without the session lock. " + "Use UI.access() to execute any UI related code from a separate thread properly"); } handler.handle(event); setReferences(null, null); } } }
/** * Creates a new bootstrap resolver based on the given request and * session. * * @param ui * the ui to resolve for */ protected BootstrapUriResolver(UI ui) { servletPathToContextRoot = ui.getInternals() .getContextRootRelativePath(); VaadinSession session = ui.getSession(); DeploymentConfiguration config = session.getConfiguration(); if (session.getBrowser().isEs6Supported()) { frontendRootUrl = config.getEs6FrontendPrefix(); } else { frontendRootUrl = config.getEs5FrontendPrefix(); } assert frontendRootUrl.endsWith("/"); assert servletPathToContextRoot.endsWith("/"); }
private void accessSynchronously(Command command, SerializableRunnable detachHandler) { Map<Class<?>, CurrentInstance> old = null; VaadinSession session = getSession(); if (session == null) { handleAccessDetach(detachHandler); return; } VaadinService.verifyNoOtherSessionLocked(session); session.lock(); try { if (getSession() == null) { // UI was detached after fetching the session but before we // acquired the lock. handleAccessDetach(detachHandler); return; } old = CurrentInstance.setCurrent(this); command.execute(); } finally { session.unlock(); if (old != null) { CurrentInstance.restoreInstances(old); } } }
@Override public int setErrorParameter(BeforeEnterEvent event, ErrorParameter<NotFoundException> parameter) { String path = event.getLocation().getPath(); String additionalInfo = ""; if (parameter.hasCustomMessage()) { additionalInfo = "Reason: " + parameter.getCustomMessage(); } boolean productionMode = event.getUI().getSession().getConfiguration() .isProductionMode(); String template = getErrorHtml(productionMode); template = template.replace("{{path}}", path); template = template.replace("{{additionalInfo}}", additionalInfo); if (template.contains("{{routes}}")) { template = template.replace("{{routes}}", getRoutes(event)); } getElement().appendChild(new Html(template).getElement()); return HttpServletResponse.SC_NOT_FOUND; }
/** * Generates the initial UIDL message which is included in the initial * bootstrap page. * * @param ui * the UI for which the UIDL should be generated * @return a JSON object with the initial UIDL message */ protected static JsonObject getInitialUidl(UI ui) { JsonObject json = new UidlWriter().createUidl(ui, false); VaadinSession session = ui.getSession(); if (session.getConfiguration().isXsrfProtectionEnabled()) { writeSecurityKeyUIDL(json, session); } writePushIdUIDL(json, session); if (getLogger().isDebugEnabled()) { getLogger().debug("Initial UIDL: {}", json.asString()); } return json; }
@Override public void setPushMode(PushMode pushMode) { if (pushMode == null) { throw new IllegalArgumentException("Push mode cannot be null"); } VaadinSession session = ui.getSession(); if (session == null) { throw new UIDetachedException( "Cannot set the push mode for a detached UI"); } session.checkHasLock(); if (pushMode.isEnabled() && !session.getService().ensurePushAvailable()) { throw new IllegalStateException( "Push is not available. See previous log messages for more information."); } PushMode oldMode = getPushConfigurationMap().getPushMode(); if (oldMode != pushMode) { getPushConfigurationMap().setPushMode(pushMode); if (!oldMode.isEnabled() && pushMode.isEnabled()) { // The push connection is initially in a disconnected state; // the client will establish the connection ui.getInternals() .setPushConnection(pushConnectionFactory.apply(ui)); } // Nothing to do here if disabling push; // the client will close the connection } }
@Override public void serviceInit(ServiceInitEvent event) { // Session event.getSource().addSessionInitListener(e -> { // DeviceInfo registry is available if (e.getSession().getAttribute(DeviceInfoRegistry.class) == null) { e.getSession().setAttribute(DeviceInfoRegistry.class, new DefaultDeviceInfoRegistry()); } }); // UI init event.getSource().addUIInitListener(e -> { if (e.getUI().getSession() != null) { // configure DeviceInfo final DeviceInfoRegistry registry = e.getUI().getSession().getAttribute(DeviceInfoRegistry.class); if (registry != null && !registry.hasDeviceInfo(e.getUI())) { final VaadinRequest request = VaadinRequest.getCurrent(); if (request != null) { registry.setDeviceInfo(e.getUI(), DeviceInfo.create(e.getUI(), request)); // log LOGGER.debug(() -> "A DeviceInfo was configured for UI with id [" + e.getUI().getUIId() + "]"); } } } }); }