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

The following examples show how to use com.vaadin.flow.server.VaadinSession#unlock() . 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: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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();
    }
}