Search in sources :

Example 36 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class AccessAnnotationCheckerTest method hasMethodAccessUsingCurrentRequest.

@Test
public void hasMethodAccessUsingCurrentRequest() throws Exception {
    try {
        CurrentInstance.set(VaadinRequest.class, new VaadinServletRequest(createRequest(USER_PRINCIPAL), null));
        Assert.assertTrue(accessAnnotationChecker.hasAccess(PermitAllClass.class.getMethod("permitAll")));
    } finally {
        CurrentInstance.clearAll();
    }
}
Also used : VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) Test(org.junit.Test)

Example 37 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class InvalidUrlTest method initUI.

private static void initUI(UI ui, String initialLocation, ArgumentCaptor<Integer> statusCodeCaptor) throws InvalidRouteConfigurationException, ServiceException {
    VaadinServletRequest request = Mockito.mock(VaadinServletRequest.class);
    VaadinResponse response = Mockito.mock(VaadinResponse.class);
    String pathInfo;
    if (initialLocation.isEmpty()) {
        pathInfo = null;
    } else {
        Assert.assertFalse(initialLocation.startsWith("/"));
        pathInfo = "/" + initialLocation;
    }
    Mockito.when(request.getPathInfo()).thenReturn(pathInfo);
    VaadinService service = new MockVaadinServletService() {

        @Override
        public VaadinContext getContext() {
            return new MockVaadinContext();
        }
    };
    service.setCurrentInstances(request, response);
    MockVaadinSession session = new AlwaysLockedVaadinSession(service);
    DeploymentConfiguration config = Mockito.mock(DeploymentConfiguration.class);
    Mockito.when(config.isProductionMode()).thenReturn(false);
    session.lock();
    session.setConfiguration(config);
    ui.getInternals().setSession(session);
    RouteConfiguration routeConfiguration = RouteConfiguration.forRegistry(ui.getRouter().getRegistry());
    routeConfiguration.update(() -> {
        routeConfiguration.getHandledRegistry().clean();
        Arrays.asList(UITest.RootNavigationTarget.class, UITest.FooBarNavigationTarget.class).forEach(routeConfiguration::setAnnotatedRoute);
    });
    ui.doInit(request, 0);
    ui.getRouter().initializeUI(ui, BootstrapHandlerTest.requestToLocation(request));
    session.unlock();
    if (statusCodeCaptor != null) {
        Mockito.verify(response).setStatus(statusCodeCaptor.capture());
    }
}
Also used : MockVaadinContext(com.vaadin.flow.server.MockVaadinContext) MockVaadinServletService(com.vaadin.flow.server.MockVaadinServletService) RouteConfiguration(com.vaadin.flow.router.RouteConfiguration) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) VaadinResponse(com.vaadin.flow.server.VaadinResponse) MockVaadinSession(com.vaadin.flow.server.MockVaadinSession) AlwaysLockedVaadinSession(com.vaadin.tests.util.AlwaysLockedVaadinSession) VaadinService(com.vaadin.flow.server.VaadinService) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration)

Example 38 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class StreamResourceHandler method handleRequest.

/**
 * Handle sending for a stream resource request.
 *
 * @param session
 *            session for the request
 * @param request
 *            request to handle
 * @param response
 *            response object to which a response can be written.
 * @param streamResource
 *            stream resource that handles data writer
 *
 * @throws IOException
 *             if an IO error occurred
 */
public void handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response, StreamResource streamResource) throws IOException {
    StreamResourceWriter writer;
    session.lock();
    try {
        ServletContext context = ((VaadinServletRequest) request).getServletContext();
        response.setContentType(streamResource.getContentTypeResolver().apply(streamResource, context));
        response.setCacheTime(streamResource.getCacheTime());
        streamResource.getHeaders().forEach((name, value) -> response.setHeader(name, value));
        writer = streamResource.getWriter();
        if (writer == null) {
            throw new IOException("Stream resource produces null input stream");
        }
    } catch (Exception exception) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw exception;
    } finally {
        session.unlock();
    }
    // don't use here "try resource" syntax sugar because in case there is
    // an exception the {@code outputStream} will be closed before "catch"
    // block which sets the status code and this code will not have any
    // effect being called after closing the stream (see #8740).
    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        writer.accept(outputStream, session);
    } catch (Exception exception) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw exception;
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
Also used : OutputStream(java.io.OutputStream) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) StreamResourceWriter(com.vaadin.flow.server.StreamResourceWriter) IOException(java.io.IOException)

Example 39 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class PushHandler method handleConnectionLost.

private VaadinSession handleConnectionLost(AtmosphereResourceEvent event) {
    if (event == null) {
        getLogger().error("Could not get event. This should never happen.");
        return null;
    }
    // We don't want to use callWithUi here, as it assumes there's a client
    // request active and does requestStart and requestEnd among other
    // things.
    AtmosphereResource resource = event.getResource();
    if (resource == null) {
        return null;
    }
    // In development mode we may have a live-reload push channel
    // that should be closed.
    Optional<BrowserLiveReload> liveReload = BrowserLiveReloadAccessor.getLiveReloadFromService(service);
    if (isDebugWindowConnection(resource) && liveReload.isPresent() && liveReload.get().isLiveReload(resource)) {
        liveReload.get().onDisconnect(resource);
        return null;
    }
    VaadinServletRequest vaadinRequest = new VaadinServletRequest(resource.getRequest(), service);
    VaadinSession session = null;
    try {
        session = service.findVaadinSession(vaadinRequest);
    } catch (SessionExpiredException e) {
        // This happens at least if the server is restarted without
        // preserving the session. After restart the client reconnects, gets
        // a session expired notification and then closes the connection and
        // ends up here
        getLogger().debug("Session expired before push disconnect event was received", e);
        return session;
    }
    UI ui;
    session.lock();
    try {
        VaadinSession.setCurrent(session);
        // Sets UI.currentInstance
        ui = service.findUI(vaadinRequest);
        if (ui == null) {
            /*
                 * UI not found, could be because FF has asynchronously closed
                 * the websocket connection and Atmosphere has already done
                 * cleanup of the request attributes.
                 *
                 * In that case, we still have a chance of finding the right UI
                 * by iterating through the UIs in the session looking for one
                 * using the same AtmosphereResource.
                 */
            ui = findUiUsingResource(resource, session.getUIs());
            if (ui == null) {
                getLogger().debug("Could not get UI. This should never happen," + " except when reloading in Firefox and Chrome -" + " see http://dev.vaadin.com/ticket/14251.");
                return session;
            } else {
                getLogger().info("No UI was found based on data in the request," + " but a slower lookup based on the AtmosphereResource succeeded." + " See http://dev.vaadin.com/ticket/14251 for more details.");
            }
        }
        PushMode pushMode = ui.getPushConfiguration().getPushMode();
        AtmospherePushConnection pushConnection = getConnectionForUI(ui);
        String id = resource.uuid();
        if (pushConnection == null) {
            getLogger().warn("Could not find push connection to close: {} with transport {}", id, resource.transport());
        } else {
            if (!pushMode.isEnabled()) {
                /*
                     * The client is expected to close the connection after push
                     * mode has been set to disabled.
                     */
                getLogger().debug("Connection closed for resource {}", id);
            } else {
                /*
                     * Unexpected cancel, e.g. if the user closes the browser
                     * tab.
                     */
                getLogger().debug("Connection unexpectedly closed for resource {} with transport {}", id, resource.transport());
            }
            pushConnection.connectionLost();
        }
    } catch (final Exception e) {
        callErrorHandler(session, e);
    } finally {
        try {
            session.unlock();
        } catch (Exception e) {
            getLogger().warn("Error while unlocking session", e);
        // can't call ErrorHandler, we (hopefully) don't have a lock
        }
    }
    return session;
}
Also used : VaadinSession(com.vaadin.flow.server.VaadinSession) UI(com.vaadin.flow.component.UI) AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest) BrowserLiveReload(com.vaadin.flow.internal.BrowserLiveReload) SessionExpiredException(com.vaadin.flow.server.SessionExpiredException) InvalidUIDLSecurityKeyException(com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException) JsonException(elemental.json.JsonException) SessionExpiredException(com.vaadin.flow.server.SessionExpiredException) IOException(java.io.IOException) PushMode(com.vaadin.flow.shared.communication.PushMode)

Example 40 with VaadinServletRequest

use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.

the class PushHandler method callWithService.

/**
 * Invokes a command with the current service set.
 *
 * @param resource
 *            the atmosphere resource for the current request
 * @param command
 *            the command to run
 */
void callWithService(final AtmosphereResource resource, final Consumer<AtmosphereRequest> command) {
    AtmosphereRequest req = resource.getRequest();
    VaadinServletRequest vaadinRequest = new VaadinServletRequest(req, service);
    service.setCurrentInstances(vaadinRequest, null);
    try {
        command.accept(req);
    } finally {
        CurrentInstance.clearAll();
    }
}
Also used : AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) VaadinServletRequest(com.vaadin.flow.server.VaadinServletRequest)

Aggregations

VaadinServletRequest (com.vaadin.flow.server.VaadinServletRequest)40 Test (org.junit.Test)19 VaadinSession (com.vaadin.flow.server.VaadinSession)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 VaadinServletService (com.vaadin.flow.server.VaadinServletService)8 IOException (java.io.IOException)7 DeploymentConfiguration (com.vaadin.flow.function.DeploymentConfiguration)6 MockVaadinServletService (com.vaadin.flow.server.MockVaadinServletService)6 MockVaadinSession (com.vaadin.flow.server.MockVaadinSession)6 VaadinRequest (com.vaadin.flow.server.VaadinRequest)6 VaadinResponse (com.vaadin.flow.server.VaadinResponse)6 UI (com.vaadin.flow.component.UI)5 Element (org.jsoup.nodes.Element)5 RouteConfiguration (com.vaadin.flow.router.RouteConfiguration)3 SessionExpiredException (com.vaadin.flow.server.SessionExpiredException)3 VaadinService (com.vaadin.flow.server.VaadinService)3 InvalidUIDLSecurityKeyException (com.vaadin.flow.server.communication.ServerRpcHandler.InvalidUIDLSecurityKeyException)3 MockDeploymentConfiguration (com.vaadin.tests.util.MockDeploymentConfiguration)3 JsonException (elemental.json.JsonException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3