Java Code Examples for com.vaadin.flow.component.UI#getSession()

The following examples show how to use com.vaadin.flow.component.UI#getSession() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Invoke this method with the chain that needs to be preserved after
 * {@link #handle(NavigationEvent)} method created it.
 */
private void setPreservedChain(ArrayList<HasElement> chain,
        NavigationEvent event) {

    final Location location = event.getLocation();
    final UI ui = event.getUI();
    final VaadinSession session = ui.getSession();

    final ExtendedClientDetails extendedClientDetails = ui.getInternals()
            .getExtendedClientDetails();

    if (extendedClientDetails == null) {
        // We need first to retrieve the window name in order to cache the
        // component chain for later potential refreshes.
        ui.getPage().retrieveExtendedClientDetails(
                details -> setPreservedChain(session,
                        details.getWindowName(), location, chain));

    } else {
        final String windowName = extendedClientDetails.getWindowName();
        setPreservedChain(session, windowName, location, chain);
    }
}
 
Example 2
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 6 votes vote down vote up
private static void clearAllPreservedChains(UI ui) {
    final VaadinSession session = ui.getSession();
    // Note that this check is always false if @PreserveOnRefresh has not
    // been used at all, avoiding the round-trip overhead.
    if (hasPreservedChain(session)) {
        ui.getPage().retrieveExtendedClientDetails(details -> {
            final String windowName = ui.getInternals()
                    .getExtendedClientDetails().getWindowName();
            final PreservedComponentCache cache = session
                    .getAttribute(PreservedComponentCache.class);
            if (cache != null) {
                cache.remove(windowName);
            }
        });
    }
}
 
Example 3
Source File: VaadinSession.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: BootstrapHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * 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
 */
private JsonObject getInitialUidl(UI ui) {
    JsonObject json = new UidlWriter().createUidl(ui, false);

    VaadinSession session = ui.getSession();
    if (session.getConfiguration().isXsrfProtectionEnabled()) {
        writeSecurityKeyUIDL(json, ui);
    }
    writePushIdUIDL(json, session);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Initial UIDL: {}", json.asString());
    }
    return json;
}
 
Example 5
Source File: BootstrapHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * 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, ui);
    }
    writePushIdUIDL(json, session);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Initial UIDL: {}", json.asString());
    }
    return json;
}
 
Example 6
Source File: UidlWriter.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a JSON object containing all pending changes to the given UI.
 *
 * @param ui
 *            The {@link UI} whose changes to write
 * @param async
 *            True if this message is sent by the server asynchronously,
 *            false if it is a response to a client message
 * @param resync
 *            True iff the client should be asked to resynchronize
 * @return JSON object containing the UIDL response
 */
public JsonObject createUidl(UI ui, boolean async, boolean resync) {
    JsonObject response = Json.createObject();

    UIInternals uiInternals = ui.getInternals();

    VaadinSession session = ui.getSession();
    VaadinService service = session.getService();

    // Purge pending access calls as they might produce additional changes
    // to write out
    service.runPendingAccessTasks(session);

    // Paints components
    getLogger().debug("* Creating response to client");

    int syncId = service.getDeploymentConfiguration().isSyncIdCheckEnabled()
            ? uiInternals.getServerSyncId()
            : -1;

    response.put(ApplicationConstants.SERVER_SYNC_ID, syncId);
    if (resync) {
        response.put(ApplicationConstants.RESYNCHRONIZE_ID, true);
    }
    int nextClientToServerMessageId = uiInternals
            .getLastProcessedClientToServerId() + 1;
    response.put(ApplicationConstants.CLIENT_TO_SERVER_ID,
            nextClientToServerMessageId);

    SystemMessages messages = ui.getSession().getService()
            .getSystemMessages(ui.getLocale(), null);

    JsonObject meta = new MetadataWriter().createMetadata(ui, false, async,
            messages);
    if (meta.keys().length > 0) {
        response.put("meta", meta);
    }

    JsonArray stateChanges = Json.createArray();

    encodeChanges(ui, stateChanges);

    populateDependencies(response, uiInternals.getDependencyList(),
            new ResolveContext(service, session.getBrowser()));

    if (uiInternals.getConstantPool().hasNewConstants()) {
        response.put("constants",
                uiInternals.getConstantPool().dumpConstants());
    }
    if (stateChanges.length() != 0) {
        response.put("changes", stateChanges);
    }

    List<PendingJavaScriptInvocation> executeJavaScriptList = uiInternals
            .dumpPendingJavaScriptInvocations();
    if (!executeJavaScriptList.isEmpty()) {
        response.put(JsonConstants.UIDL_KEY_EXECUTE,
                encodeExecuteJavaScriptList(executeJavaScriptList));
    }
    if (ui.getSession().getService().getDeploymentConfiguration()
            .isRequestTiming()) {
        response.put("timings", createPerformanceData(ui));
    }
    uiInternals.incrementServerId();
    return response;
}
 
Example 7
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Checks if there exists a cached component chain of the route location in
 * the current window.
 *
 * If retrieving the window name requires another round-trip, schedule it
 * and make a new call to the handle {@link #handle(NavigationEvent)} in the
 * callback. In this case, this method returns {@link Optional#empty()}.
 *
 * If the chain is missing and needs to be created this method returns an
 * {@link Optional} wrapping an empty {@link ArrayList}.
 */
private Optional<ArrayList<HasElement>> getPreservedChain(
        NavigationEvent event) {
    final Location location = event.getLocation();
    final UI ui = event.getUI();
    final VaadinSession session = ui.getSession();

    if (ui.getInternals().getExtendedClientDetails() == null) {
        if (hasPreservedChainOfLocation(session, location)) {
            // We may have a cached instance for this location, but we
            // need to retrieve the window name before we can determine
            // this, so execute a client-side request.
            ui.getPage().retrieveExtendedClientDetails(
                    details -> handle(event));
            return Optional.empty();
        }
    } else {
        final String windowName = ui.getInternals()
                .getExtendedClientDetails().getWindowName();
        final Optional<ArrayList<HasElement>> maybePreserved = getPreservedChain(
                session, windowName, event.getLocation());
        if (maybePreserved.isPresent()) {
            // Re-use preserved chain for this route
            ArrayList<HasElement> chain = maybePreserved.get();
            final HasElement root = chain.get(chain.size() - 1);
            final Component component = (Component) chain.get(0);
            final Optional<UI> maybePrevUI = component.getUI();

            if (maybePrevUI.isPresent() && maybePrevUI.get().equals(ui)) {
                return Optional.of(chain);
            }

            // Remove the top-level component from the tree
            root.getElement().removeFromTree();

            // Transfer all remaining UI child elements (typically dialogs
            // and notifications) to the new UI
            maybePrevUI.ifPresent(prevUi -> {
                ui.getInternals().moveElementsFrom(prevUi);
                prevUi.close();
            });

            return Optional.of(chain);
        }
    }

    return Optional.of(new ArrayList<>(0));
}
 
Example 8
Source File: InfoView.java    From flow with Apache License 2.0 4 votes vote down vote up
private void update(UI ui) {
    VaadinSession session = ui.getSession();
    WebBrowser webBrowser = session.getBrowser();
    DeploymentConfiguration deploymentConfiguration = session
            .getConfiguration();
    List<String> device = new ArrayList<>();
    List<String> os = new ArrayList<>();
    List<String> browser = new ArrayList<>();

    removeAll();
    add(new NativeButton("Refresh", e -> {
        update(ui);
    }));

    header("Browser");
    info("Address", webBrowser.getAddress());

    add(device, "Android", webBrowser.isAndroid());
    add(device, "iPhone", webBrowser.isIPhone());
    add(device, "Windows Phone", webBrowser.isWindowsPhone());

    info("Device", device.stream().collect(Collectors.joining(", ")));

    add(os, "Linux", webBrowser.isLinux());
    add(os, "Mac", webBrowser.isMacOSX());
    add(os, "Windows", webBrowser.isWindows());

    info("Os", os.stream().collect(Collectors.joining(", ")));

    add(browser, "Chrome", webBrowser.isChrome());
    add(browser, "Edge", webBrowser.isEdge());
    add(browser, "Firefox", webBrowser.isFirefox());
    add(browser, "IE", webBrowser.isIE());
    add(browser, "Safari", webBrowser.isSafari());

    info("Browser", browser.stream().collect(Collectors.joining(", ")));

    if (webBrowser.isTooOldToFunctionProperly()) {
        header("Browser is too old to function properly");
    }
    info("User-agent", webBrowser.getBrowserApplication());
    info("Browser major", webBrowser.getBrowserMajorVersion());
    info("Browser minor", webBrowser.getBrowserMinorVersion());
    info("Locale", webBrowser.getLocale());

    info("Secure connection (https)", webBrowser.isSecureConnection());

    separator();

    header("Push configuration");
    info("Push mode", ui.getPushConfiguration().getPushMode());
    info("Push transport", ui.getPushConfiguration().getTransport());

    separator();

    header("Deployment configuration");
    info("Heartbeat interval",
            deploymentConfiguration.getHeartbeatInterval());
    info("UI class", deploymentConfiguration.getUIClassName());
    info("Close idle sessions",
            deploymentConfiguration.isCloseIdleSessions());
    info("Send URLs as parameters",
            deploymentConfiguration.isSendUrlsAsParameters());
    info("Sync id enabled", deploymentConfiguration.isSyncIdCheckEnabled());
    info("XSRF protection enabled",
            deploymentConfiguration.isXsrfProtectionEnabled());
    info("Production mode", deploymentConfiguration.isProductionMode());

}
 
Example 9
Source File: BootstrapHandler.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new bootstrap resolver based on the given ui.
 *
 * @param ui
 *            the ui to resolve for
 */
protected BootstrapUriResolver(UI ui) {
    this(ui.getInternals().getContextRootRelativePath(),
            ui.getSession());
}