com.vaadin.flow.server.VaadinSession Java Examples

The following examples show how to use com.vaadin.flow.server.VaadinSession. 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: RemoveFallbackChunkInfo.java    From flow with Apache License 2.0 6 votes vote down vote up
boolean handleRequest(VaadinSession session, VaadinRequest request,
        VaadinResponse response) {
    VaadinServletRequest servletRequest = (VaadinServletRequest) request;
    HttpServletRequest httpRequest = servletRequest.getHttpServletRequest();
    String query = httpRequest.getQueryString();
    if ("drop-fallback".equals(query)) {
        // self check
        FallbackChunk chunk = session.getService().getContext()
                .getAttribute(FallbackChunk.class);

        if (chunk == null) {
            throw new RuntimeException(
                    "Vaadin context has no fallback chunk data");
        }

        // remove fallback chunk data to that the chunk won't be loaded
        session.getService().getContext()
                .removeAttribute(FallbackChunk.class);
    }
    return false;
}
 
Example #2
Source File: ExtendedClientDetailsTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void differentNavigatorPlatformDetails_isIPadReturnsExpectedValue() {
    ExtendBuilder detailsBuilder = new ExtendBuilder();

    ExtendedClientDetails details = detailsBuilder.buildDetails();
    Assert.assertFalse("Linux is not an iPad", details.isIPad());

    detailsBuilder.setNavigatorPlatform("iPad");
    details = detailsBuilder.buildDetails();

    Assert.assertTrue("'iPad' is an iPad", details.isIPad());

    VaadinSession session = Mockito.mock(VaadinSession.class);
    CurrentInstance.setCurrent(session);

    detailsBuilder.setNavigatorPlatform(null);
    details = detailsBuilder.buildDetails();

    CurrentInstance.clearAll();
}
 
Example #3
Source File: HeartbeatHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a heartbeat request for the given session. Reads the GET
 * parameter named {@link ApplicationConstants#UI_ID_PARAMETER} to identify
 * the UI. If the UI is found in the session, sets it
 * {@link UIInternals#getLastHeartbeatTimestamp() heartbeat timestamp} to
 * the current time. Otherwise, writes a HTTP Not Found error to the
 * response.
 */
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
        VaadinRequest request, VaadinResponse response) throws IOException {
    UI ui = session.getService().findUI(request);
    if (ui != null) {
        ui.getInternals()
                .setLastHeartbeatTimestamp(System.currentTimeMillis());
        // Ensure that the browser does not cache heartbeat responses.
        // iOS 6 Safari requires this (#10370)
        response.setHeader("Cache-Control", "no-cache");
        // If Content-Type is not set, browsers assume text/html and may
        // complain about the empty response body (#12182)
        response.setHeader("Content-Type", "text/plain");
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                "UI not found");
    }

    return true;
}
 
Example #4
Source File: PwaHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request,
        VaadinResponse response) throws IOException {
    String requestUri = request.getPathInfo();

    if (pwaRegistry.getPwaConfiguration().isEnabled()) {
        if (requestHandlerMap.containsKey(requestUri)) {
            return requestHandlerMap.get(requestUri).handleRequest(session,
                    request, response);
        } else if (requestUri != null && requestUri
                .startsWith("/" + PwaRegistry.WORKBOX_FOLDER)) {

            // allow only files under workbox_folder
            String resourceName = PwaRegistry.WORKBOX_FOLDER + requestUri
                    // remove the extra '/'
                    .substring(PwaRegistry.WORKBOX_FOLDER.length() + 1)
                    .replaceAll("/", "");
            return handleWorkboxResource(resourceName, response);
        }

    }
    return false;
}
 
Example #5
Source File: WebComponentBootstrapHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
        VaadinRequest request, VaadinResponse response) throws IOException {
    // Find UI class
    Class<? extends UI> uiClass = getUIClass(request);

    BootstrapContext context = createAndInitUI(uiClass, request, response,
            session);

    HandlerHelper.setResponseNoCacheHeaders(response::setHeader,
            response::setDateHeader);

    String serviceUrl = getServiceUrl(request, response);

    Document document = getPageBuilder().getBootstrapPage(context);
    writeBootstrapPage(response, document.head(), serviceUrl);
    return true;
}
 
Example #6
Source File: VertxVaadinService.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Override
public String getMainDivId(VaadinSession session, VaadinRequest request) {
    String appId;
    // Have to check due to VertxBootstrapHandler tricks
    if (request instanceof VertxVaadinRequest) {
        appId = ((VertxVaadinRequest) request).getRoutingContext().mountPoint();
    } else {
        appId = request.getContextPath();
    }

    if (appId == null || "".equals(appId) || "/".equals(appId)) {
        appId = "ROOT";
    }
    appId = appId.replaceAll("[^a-zA-Z0-9]", "");
    // Add hashCode to the end, so that it is still (sort of)
    // predictable, but indicates that it should not be used in CSS
    // and
    // such:
    int hashCode = appId.hashCode();
    if (hashCode < 0) {
        hashCode = -hashCode;
    }
    appId = appId + "-" + hashCode;
    return appId;
}
 
Example #7
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Streams content from a multipart request to given StreamVariable.
 * <p>
 * This method takes care of locking the session as needed and does not
 * assume the caller has locked the session. This allows the session to be
 * locked only when needed and not when handling the upload data.
 *
 * @param session
 *            The session containing the stream variable
 * @param request
 *            The upload request
 * @param response
 *            The upload response
 * @param streamReceiver
 *            the receiver containing the destination stream variable
 * @param owner
 *            The owner of the stream
 * @throws IOException
 *             If there is a problem reading the request or writing the
 *             response
 */
protected void doHandleMultipartFileUpload(VaadinSession session,
        VaadinRequest request, VaadinResponse response,
        StreamReceiver streamReceiver, StateNode owner) throws IOException {
    boolean success = false;
    try {
        if (hasParts(request)) {
            success = handleMultipartFileUploadFromParts(session, request,
                    streamReceiver, owner);
        } else {
            success = handleMultipartFileUploadFromInputStream(session,
                    request, streamReceiver, owner);
        }
    } catch (Exception exception) {
        session.lock();
        try {
            session.getErrorHandler().error(new ErrorEvent(exception));
        } finally {
            session.unlock();
        }
    }
    sendUploadResponse(response, success);
}
 
Example #8
Source File: RouteConfigurationTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void configurationForSessionRegistry_buildsWithCorrectRegistry() {
    SessionRouteRegistry registry = getRegistry(session);
    registry.update(() -> {
        registry.setRoute("", MyRoute.class, Collections.emptyList());
        registry.setRoute("path", Secondary.class, Collections.emptyList());
    });

    try {
        VaadinSession.setCurrent(session);
        session.lock();
        RouteConfiguration routeConfiguration = RouteConfiguration
                .forSessionScope();

        Assert.assertEquals(
                "After unlock registry should be updated for others to configure with new data",
                2, routeConfiguration.getAvailableRoutes().size());
    } finally {
        session.unlock();
        CurrentInstance.clearAll();
    }
}
 
Example #9
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private boolean handleMultipartFileUploadFromParts(VaadinSession session,
        VaadinRequest request, StreamReceiver streamReceiver,
        StateNode owner) throws IOException {
    // If we try to parse the request now, we will get an exception
    // since it has already been parsed and turned into Parts.
    boolean success = true;
    try {
        Iterator<Part> iter = getParts(request).iterator();
        while (iter.hasNext()) {
            Part part = iter.next();
            boolean partSuccess = handleStream(session, streamReceiver,
                    owner, part);
            success = success && partSuccess;
        }
    } catch (Exception e) {
        success = false;
        // This should only happen if the request is not a multipart
        // request and this we have already checked in hasParts().
        getLogger().warn("File upload failed.", e);
    }
    return success;
}
 
Example #10
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 #11
Source File: PushErrorHandlingUI.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
protected void init(VaadinRequest request) {
    getPushConfiguration().setPushMode(PushMode.AUTOMATIC);

    VaadinSession.getCurrent().setErrorHandler(event -> {
        Div div = new Div();
        div.addClassName("error");
        div.setText("An error! " + event.getThrowable().getClass());
        add(div);
    });

    final NativeButton button = new NativeButton("Click for NPE!",
            event -> {
                ((String) null).length(); // Null-pointer exception
            });
    button.setId("npeButton");
    add(button);

}
 
Example #12
Source File: ComponentTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    divWithTextComponent = new TestComponent(
            ElementFactory.createDiv("Test component"));
    parentDivComponent = new TestComponent(ElementFactory.createDiv());
    child1SpanComponent = new TestComponent(
            ElementFactory.createSpan("Span"));
    child2InputComponent = new TestComponent(ElementFactory.createInput());
    parentDivComponent.getElement().appendChild(
            child1SpanComponent.getElement(),
            child2InputComponent.getElement());

    mocks = new MockServletServiceSessionSetup();

    VaadinSession session = mocks.getSession();
    UI ui = new UI() {
        @Override
        public VaadinSession getSession() {
            return session;
        }
    };
    ui.getInternals().setSession(session);

    UI.setCurrent(ui);
}
 
Example #13
Source File: WebComponentBootstrapHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void writeBootstrapPage_devmodeGizmoIsDisabled()
        throws IOException, ServiceException {
    TestWebComponentBootstrapHandler handler = new TestWebComponentBootstrapHandler();
    VaadinServletService service = new MockVaadinServletService();
    service.init();
    VaadinSession session = new MockVaadinSession(service);
    session.lock();
    session.setConfiguration(service.getDeploymentConfiguration());
    MockDeploymentConfiguration config = (MockDeploymentConfiguration) service
            .getDeploymentConfiguration();
    config.setEnableDevServer(false);

    VaadinServletRequest request = Mockito.mock(VaadinServletRequest.class);
    Mockito.when(request.getService()).thenReturn(service);
    Mockito.when(request.getServletPath()).thenReturn("/");
    VaadinResponse response = getMockResponse(null);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Mockito.when(response.getOutputStream()).thenReturn(stream);

    handler.synchronizedHandleRequest(session, request, response);

    String result = stream.toString(StandardCharsets.UTF_8.name());
    Assert.assertTrue(result.contains("\\\"devmodeGizmoEnabled\\\": false"));
}
 
Example #14
Source File: WebComponentWrapperTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private static WebComponentUI constructWebComponentUI(
        Element wrapperElement) {
    WebComponentUI ui = mock(WebComponentUI.class);
    when(ui.getUI()).thenReturn(Optional.of(ui));
    Element body = new Element("body");
    when(ui.getElement()).thenReturn(body);

    UIInternals internals = new UIInternals(ui);
    internals.setSession(
            new AlwaysLockedVaadinSession(mock(VaadinService.class)));
    when(ui.getInternals()).thenReturn(internals);

    Component parent = new Parent();
    parent.getElement().appendVirtualChild(wrapperElement);

    VaadinSession session = mock(VaadinSession.class);
    DeploymentConfiguration configuration = mock(
            DeploymentConfiguration.class);

    when(ui.getSession()).thenReturn(session);
    when(session.getConfiguration()).thenReturn(configuration);
    when(configuration.getWebComponentDisconnect()).thenReturn(1);

    return ui;
}
 
Example #15
Source File: AbstractListDataViewListenerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private static VaadinSession findOrcreateSession() {
    VaadinSession session = VaadinSession.getCurrent();
    if (session == null) {
        session = new AlwaysLockedVaadinSession(null);
        VaadinSession.setCurrent(session);
    }
    return session;
}
 
Example #16
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean handleStream(VaadinSession session,
        StreamReceiver streamReceiver, StateNode owner, Part part)
        throws IOException {
    String name = part.getSubmittedFileName();
    InputStream stream = part.getInputStream();
    try {
        return handleFileUploadValidationAndData(session, stream,
                streamReceiver, name, part.getContentType(), part.getSize(),
                owner);
    } catch (UploadException e) {
        session.getErrorHandler().error(new ErrorEvent(e));
    }
    return false;
}
 
Example #17
Source File: SerializationTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void testVaadinSession() throws Exception {
    VaadinSession session = new VaadinSession(null);

    session = serializeAndDeserialize(session);

    assertNotNull(
            "Pending access queue was not recreated after deserialization",
            session.getPendingAccessQueue());
}
 
Example #18
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Before
public void setUp() throws SecurityException,
        IllegalArgumentException {
    executionOrder.clear();
    executionParams.clear();

    VaadinSession session = Mockito.mock(VaadinSession.class);
    ui = new UI() {
        private Page page = new Page(this) {

            @Override
            public PendingJavaScriptResult executeJs(String expression,
                    Serializable... parameters) {
                executionOrder.add(expression);
                executionParams.add(parameters);
                return null;
            }
        };

        @Override
        public VaadinSession getSession() {
            return session;
        }

        @Override
        public Page getPage() {
            return page;
        }
    };
    VaadinService service = Mockito.mock(VaadinService.class);
    when(session.getService()).thenReturn(service);
    DefaultInstantiator instantiator = new DefaultInstantiator(service);
    when(service.getInstantiator()).thenReturn(instantiator);
    UI.setCurrent(ui);
}
 
Example #19
Source File: RouterTestServlet.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    Location location = event.getUI().getInternals()
            .getActiveViewLocation();
    if (!location.getPath().isEmpty()) {
        VaadinSession.getCurrent().getSession().invalidate();
    }
}
 
Example #20
Source File: PendingJavaScriptResult.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a typed completable future that will be completed with the result
 * of the execution. It will be completed asynchronously when the result of
 * the execution is sent back to the server. It is not possible to
 * synchronously wait for the result of the execution while holding the
 * session lock since the request handling thread that makes the result
 * available will also need to lock the session.
 * <p>
 * A completable future can only be created before the execution has been
 * sent to the browser.
 *
 * @param targetType
 *            the type to convert the JavaScript return value to, not
 *            <code>null</code>
 *
 * @return a completable future that will be completed based on the
 *         execution results, not <code>null</code>
 */
default <T> CompletableFuture<T> toCompletableFuture(Class<T> targetType) {
    if (targetType == null) {
        throw new IllegalArgumentException("Target type cannot be null");
    }

    /*
     * Assuming that subscription is only done for the currently locked
     * session. This is quite safe since you cannot subscribe any more after
     * the request has been sent to the client.
     *
     * This is the only way of catching the potentially common case of
     * blocking on a pending result for an element that hasn't yet even been
     * attached to a session.
     */
    VaadinSession session = VaadinSession.getCurrent();

    CompletableFuture<T> completableFuture = new DeadlockDetectingCompletableFuture<>(
            session);

    then(value -> {
        T convertedValue = JsonCodec.decodeAs(value, targetType);
        completableFuture.complete(convertedValue);
    }, errorValue -> {
        JavaScriptException exception = new JavaScriptException(errorValue);
        completableFuture.completeExceptionally(exception);
    });

    return completableFuture;
}
 
Example #21
Source File: Router.java    From flow with Apache License 2.0 5 votes vote down vote up
public RouteRegistry getRegistry() {
    // If we have a session then return the session registry
    // else return router registry
    if (VaadinSession.getCurrent() != null) {
        return SessionRouteRegistry
                .getSessionRegistry(VaadinSession.getCurrent());
    }
    return registry;
}
 
Example #22
Source File: AbstractNavigationStateRenderer.java    From flow with Apache License 2.0 5 votes vote down vote up
static Optional<ArrayList<HasElement>> getPreservedChain(
        VaadinSession session, String windowName, Location location) {
    final PreservedComponentCache cache = session
            .getAttribute(PreservedComponentCache.class);
    if (cache != null && cache.containsKey(windowName) && cache
            .get(windowName).getFirst().equals(location.getPath())) {
        return Optional.of(cache.get(windowName).getSecond());
    } else {
        return Optional.empty();
    }
}
 
Example #23
Source File: PushConfiguration.java    From flow with Apache License 2.0 5 votes vote down vote up
@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
    }
}
 
Example #24
Source File: InternalErrorView.java    From flow with Apache License 2.0 5 votes vote down vote up
public InternalErrorView() {
    Div message = new Div();
    message.setId("message");

    NativeButton updateMessageButton = createButton("Update", "update",
            event -> message.setText("Updated"));

    NativeButton closeSessionButton = createButton("Close session",
            "close-session",
            event -> VaadinSession.getCurrent().close());

    NativeButton enableNotificationButton = createButton(
            "Enable session expired notification", "enable-notification",
            event -> enableSessionExpiredNotification());

    NativeButton causeExceptionButton = createButton("Cause exception",
            "cause-exception",
            event -> showInternalError());

    NativeButton resetSystemMessagesButton = createButton(
            "Reset system messages", "reset-system-messages",
            event -> resetSystemMessages());

    add(message, updateMessageButton, closeSessionButton,
            enableNotificationButton, causeExceptionButton,
            resetSystemMessagesButton);
}
 
Example #25
Source File: PushHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
void connectionLost(AtmosphereResourceEvent event) {
    VaadinSession session = null;
    try {
        session = handleConnectionLost(event);
    } finally {
        if (session != null) {
            session.access(CurrentInstance::clearAll);
        }
    }
}
 
Example #26
Source File: RouteConfigurationTest.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get registry by handing the session lock correctly.
 *
 * @param session target vaadin session
 * @return session route registry for session if exists or new.
 */
private SessionRouteRegistry getRegistry(VaadinSession session) {
    try {
        session.lock();
        return (SessionRouteRegistry) SessionRouteRegistry
                .getSessionRegistry(session);
    } finally {
        session.unlock();
    }
}
 
Example #27
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private void cleanStreamVariable(VaadinSession session,
        StreamReceiver streamReceiver) {
    session.lock();
    try {
        session.getResourceRegistry().unregisterResource(streamReceiver);
    } finally {
        session.unlock();
    }
}
 
Example #28
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private boolean handleFileUploadValidationAndData(VaadinSession session,
        InputStream inputStream, StreamReceiver streamReceiver,
        String filename, String mimeType, long contentLength,
        StateNode node) throws UploadException {
    session.lock();
    try {
        if (node == null) {
            throw new UploadException(
                    "File upload ignored because the node for the stream variable was not found");
        }
        if (!node.isAttached()) {
            throw new UploadException("Warning: file upload ignored for "
                    + node.getId() + " because the component was disabled");
        }
    } finally {
        session.unlock();
    }
    try {
        // Store ui reference so we can do cleanup even if node is
        // detached in some event handler
        Pair<Boolean, UploadStatus> result = streamToReceiver(session,
                inputStream, streamReceiver, filename, mimeType,
                contentLength);
        if (result.getFirst()) {
            cleanStreamVariable(session, streamReceiver);
        }
        return result.getSecond() == UploadStatus.OK;
    } catch (Exception e) {
        session.lock();
        try {
            session.getErrorHandler().error(new ErrorEvent(e));
        } finally {
            session.unlock();
        }
    }
    return false;
}
 
Example #29
Source File: MockUI.java    From flow with Apache License 2.0 5 votes vote down vote up
private static VaadinSession findOrCreateSession() {
    VaadinSession session = VaadinSession.getCurrent();
    if (session == null) {
        session = createSession();
    }
    return session;
}
 
Example #30
Source File: AbstractDnDUnitTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    DefaultDeploymentConfiguration configuration = new DefaultDeploymentConfiguration(
            VaadinServlet.class, new Properties());

    VaadinService service = Mockito.mock(VaadinService.class);
    Mockito.when(service.resolveResource(Mockito.anyString()))
            .thenReturn("");

    VaadinSession session = Mockito.mock(VaadinSession.class);
    Mockito.when(session.getConfiguration()).thenReturn(configuration);
    Mockito.when(session.getService()).thenReturn(service);

    ui = new MockUI(session);
}