Java Code Examples for com.vaadin.flow.server.VaadinSession#lock()

The following examples show how to use com.vaadin.flow.server.VaadinSession#lock() . 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: StreamResourceHandler.java    From vertx-vaadin with MIT License 6 votes vote down vote up
/**
 * 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 = ((VertxVaadinRequest) request).getService().getServletContext();
        response.setContentType(streamResource.getContentTypeResolver()
            .apply(streamResource, context));
        response.setCacheTime(streamResource.getCacheTime());
        writer = streamResource.getWriter();
        if (writer == null) {
            throw new IOException(
                "Stream resource produces null input stream");
        }
    } finally {
        session.unlock();
    }
    try (OutputStream outputStream = response.getOutputStream()) {
        writer.accept(outputStream, session);
    }
}
 
Example 2
Source File: StreamReceiverHandler.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private long updateProgress(VaadinSession session,
                            StreamVariable streamVariable,
                            StreamingProgressEventImpl progressEvent, long lastStreamingEvent,
                            int bytesReadToBuffer) {
    long now = System.currentTimeMillis();
    // to avoid excessive session locking and event storms,
    // events are sent in intervals, or at the end of the file.
    if (lastStreamingEvent + getProgressEventInterval() <= now
        || bytesReadToBuffer <= 0) {
        session.lock();
        try {
            streamVariable.onProgress(progressEvent);
        } finally {
            session.unlock();
        }
    }
    return now;
}
 
Example 3
Source File: SessionRequestHandler.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 {
    // Use a copy to avoid ConcurrentModificationException
    session.lock();
    List<RequestHandler> requestHandlers;
    try {
        requestHandlers = new ArrayList<>(session.getRequestHandlers());
    } finally {
        session.unlock();
    }
    for (RequestHandler handler : requestHandlers) {
        if (handler.handleRequest(session, request, response)) {
            return true;
        }
    }
    // If not handled
    return false;
}
 
Example 4
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 5
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private long updateProgress(VaadinSession session,
        StreamVariable streamVariable,
        StreamingProgressEventImpl progressEvent, long lastStreamingEvent,
        int bytesReadToBuffer) {
    long now = System.currentTimeMillis();
    // to avoid excessive session locking and event storms,
    // events are sent in intervals, or at the end of the file.
    if (lastStreamingEvent + getProgressEventInterval() <= now
            || bytesReadToBuffer <= 0) {
        session.lock();
        try {
            streamVariable.onProgress(progressEvent);
        } finally {
            session.unlock();
        }
    }
    return now;
}
 
Example 6
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 7
Source File: StreamReceiverHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
/**
 * Handle reception of incoming stream from the client.
 *
 * @param session        The session for the request
 * @param request        The request to handle
 * @param response       The response object to which a response can be written.
 * @param streamReceiver the receiver containing the destination stream variable
 * @param uiId           id of the targeted ui
 * @param securityKey    security from the request that should match registered stream
 *                       receiver id
 * @throws IOException if an IO error occurred
 */
public void handleRequest(VaadinSession session, VaadinRequest request,
                          VaadinResponse response, StreamReceiver streamReceiver, String uiId,
                          String securityKey) throws IOException {
    StateNode source;

    session.lock();
    try {
        String secKey = streamReceiver.getId();
        if (secKey == null || !secKey.equals(securityKey)) {
            getLogger().warn(
                "Received incoming stream with faulty security key.");
            return;
        }

        UI ui = session.getUIById(Integer.parseInt(uiId));
        UI.setCurrent(ui);

        source = streamReceiver.getNode();

    } finally {
        session.unlock();
    }

    try {
        Set<FileUpload> fileUploads = ((VertxVaadinRequest) request).getRoutingContext().fileUploads();
        if (!fileUploads.isEmpty()) {
            doHandleMultipartFileUpload(session, request, response, fileUploads, streamReceiver, source);
        } else {
            // if boundary string does not exist, the posted file is from
            // XHR2.post(File)
            doHandleXhrFilePost(session, request, response, streamReceiver,
                source, getContentLength(request));
        }
    } finally {
        UI.setCurrent(null);
    }
}
 
Example 8
Source File: StreamReceiverHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void 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
        boolean forgetVariable = streamToReceiver(session, inputStream,
            streamReceiver, filename, mimeType, contentLength);
        if (forgetVariable) {
            cleanStreamVariable(session, streamReceiver);
        }
    } catch (Exception e) {
        session.lock();
        try {
            session.getErrorHandler().error(new ErrorEvent(e));
        } finally {
            session.unlock();
        }
    }
}
 
Example 9
Source File: StreamReceiverHandler.java    From vertx-vaadin with MIT License 5 votes vote down vote up
private void cleanStreamVariable(VaadinSession session,
                                 StreamReceiver streamReceiver) {
    session.lock();
    try {
        session.getResourceRegistry().unregisterResource(streamReceiver);
    } finally {
        session.unlock();
    }
}
 
Example 10
Source File: StreamReceiverHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Handle reception of incoming stream from the client.
 *
 * @param session
 *            The session for the request
 * @param request
 *            The request to handle
 * @param response
 *            The response object to which a response can be written.
 * @param streamReceiver
 *            the receiver containing the destination stream variable
 * @param uiId
 *            id of the targeted ui
 * @param securityKey
 *            security from the request that should match registered stream
 *            receiver id
 * @throws IOException
 *             if an IO error occurred
 */
public void handleRequest(VaadinSession session, VaadinRequest request,
        VaadinResponse response, StreamReceiver streamReceiver, String uiId,
        String securityKey) throws IOException {
    StateNode source;

    session.lock();
    try {
        String secKey = streamReceiver.getId();
        if (secKey == null || !secKey.equals(securityKey)) {
            getLogger().warn(
                    "Received incoming stream with faulty security key.");
            return;
        }

        UI ui = session.getUIById(Integer.parseInt(uiId));
        UI.setCurrent(ui);

        source = streamReceiver.getNode();

    } finally {
        session.unlock();
    }

    try {
        if (isMultipartUpload(request)) {
            doHandleMultipartFileUpload(session, request, response,
                    streamReceiver, source);
        } else {
            // if boundary string does not exist, the posted file is from
            // XHR2.post(File)
            doHandleXhrFilePost(session, request, response, streamReceiver,
                    source, getContentLength(request));
        }
    } finally {
        UI.setCurrent(null);
    }
}
 
Example 11
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 12
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 13
Source File: UI.java    From flow with Apache License 2.0 5 votes vote down vote up
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);
        }
    }

}
 
Example 14
Source File: UidlWriterTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private UI initializeUIForDependenciesTest(UI ui) throws Exception {
    mocks = new MockServletServiceSessionSetup();

    VaadinSession session = mocks.getSession();
    session.lock();
    ui.getInternals().setSession(session);

    RouteConfiguration routeConfiguration = RouteConfiguration
            .forRegistry(ui.getRouter().getRegistry());
    routeConfiguration.update(() -> {
        routeConfiguration.getHandledRegistry().clean();
        routeConfiguration.setAnnotatedRoute(BaseClass.class);
    });

    for (String type : new String[] { "html", "js", "css" }) {
        mocks.getServlet().addServletContextResource("inline." + type,
                "inline." + type);
    }

    HttpServletRequest servletRequestMock = mock(HttpServletRequest.class);

    VaadinServletRequest vaadinRequestMock = mock(
            VaadinServletRequest.class);

    when(vaadinRequestMock.getHttpServletRequest())
            .thenReturn(servletRequestMock);

    ui.doInit(vaadinRequestMock, 1);
    ui.getRouter().initializeUI(ui, vaadinRequestMock);

    return ui;
}
 
Example 15
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 16
Source File: WebComponentBootstrapHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void writeBootstrapPage_noPWA()
        throws IOException, ServiceException {
    TestWebComponentBootstrapHandler handler = new TestWebComponentBootstrapHandler();

    PwaRegistry registry = Mockito.mock(PwaRegistry.class);

    PwaConfiguration conf = Mockito.mock(PwaConfiguration.class);

    Mockito.when(registry.getPwaConfiguration()).thenReturn(conf);

    Mockito.when(conf.isEnabled()).thenReturn(true);

    Mockito.when(conf.getManifestPath()).thenReturn("bar");

    PwaIcon icon = Mockito.mock(PwaIcon.class);
    Mockito.when(icon.asElement()).thenReturn(new Element("h1"));

    Mockito.when(registry.getHeaderIcons())
            .thenReturn(Collections.singletonList(icon));

    VaadinServletService service = new MockVaadinServletService() {
        @Override
        protected PwaRegistry getPwaRegistry() {
            return registry;
        };
    };
    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.assertThat(result,
            CoreMatchers.not(CoreMatchers.containsString("bar")));
    Assert.assertThat(result,
            CoreMatchers.not(CoreMatchers.containsString("h1")));
    Assert.assertThat(result,
            CoreMatchers.not(CoreMatchers.containsString("baz")));
}