com.vaadin.flow.server.VaadinSession.unlock()

Here are the examples of the java api com.vaadin.flow.server.VaadinSession.unlock() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

9 Examples 7

17 Source : StreamReceiverHandler.java
with MIT License
from mcollovati

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;
}

17 Source : StreamReceiverHandler.java
with MIT License
from mcollovati

private void cleanStreamVariable(VaadinSession session, StreamReceiver streamReceiver) {
    session.lock();
    try {
        session.getResourceRegistry().unregisterResource(streamReceiver);
    } finally {
        session.unlock();
    }
}

17 Source : StreamReceiverHandler.java
with MIT License
from mcollovati

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();
        }
    }
}

16 Source : StreamReceiverHandler.java
with MIT License
from mcollovati

/**
 * 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);
    }
}

15 Source : SockJSPushHandler.java
with MIT License
from mcollovati

private VaadinSession handleConnectionLost(PushEvent event) {
    // We don't want to use callWithUi here, as it replacedumes there's a client
    // request active and does requestStart and requestEnd among other
    // things.
    VaadinRequest vaadinRequest = new VertxVaadinRequest(service, event.routingContext);
    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
        logger.trace("Session expired before push disconnect event was received", e);
        return null;
    }
    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 = findUiUsingSocket(event.socket(), session.getUIs());
            if (ui == null) {
                logger.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 {
                logger.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();
        SockJSPushConnection pushConnection = getConnectionForUI(ui);
        String id = event.socket().getUUID();
        if (pushConnection == null) {
            logger.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.
                     */
                logger.trace("Connection closed for resource {}", id);
            } else {
                /*
                     * Unexpected cancel, e.g. if the user closes the browser
                     * tab.
                     */
                logger.trace("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) {
            logger.warn("Error while unlocking session", e);
        // can't call ErrorHandler, we (hopefully) don't have a lock
        }
    }
    return session;
}

12 Source : SockJSPushHandler.java
with MIT License
from mcollovati

private void callWithUi(final PushEvent event, final PushEventCallback callback) {
    PushSocket socket = event.socket;
    RoutingContext routingContext = event.routingContext;
    VertxVaadinRequest vaadinRequest = new VertxVaadinRequest(service, routingContext);
    VaadinSession session = null;
    service.requestStart(vaadinRequest, null);
    try {
        try {
            session = service.findVaadinSession(vaadinRequest);
            replacedert VaadinSession.getCurrent() == session;
        } catch (SessionExpiredException e) {
            sendNotificationAndDisconnect(socket, VaadinService.createSessionExpiredJSON());
            return;
        }
        UI ui = null;
        session.lock();
        try {
            ui = service.findUI(vaadinRequest);
            replacedert UI.getCurrent() == ui;
            if (ui == null) {
                sendNotificationAndDisconnect(socket, VaadinService.createUINotFoundJSON());
            } else {
                callback.run(event, ui);
            }
        } catch (final IOException e) {
            callErrorHandler(session, e);
        } catch (final Exception e) {
            SystemMessages msg = service.getSystemMessages(ServletHelper.findLocale(null, vaadinRequest), vaadinRequest);
            /* TODO: verify */
            PushSocket errorSocket = getOpenedPushConnection(socket, ui);
            sendNotificationAndDisconnect(errorSocket, VaadinService.createCriticalNotificationJSON(msg.getInternalErrorCaption(), msg.getInternalErrorMessage(), null, msg.getInternalErrorURL()));
            callErrorHandler(session, e);
        } finally {
            try {
                session.unlock();
            } catch (Exception e) {
                logger.warn("Error while unlocking session", e);
            // can't call ErrorHandler, we (hopefully) don't have a lock
            }
        }
    } finally {
        try {
            service.requestEnd(vaadinRequest, null, session);
        } catch (Exception e) {
            logger.warn("Error while ending request", e);
        // can't call ErrorHandler, we don't have a lock
        }
    }
}

10 Source : StreamReceiverHandler.java
with MIT License
from mcollovati

private final boolean streamToReceiver(VaadinSession session, final InputStream in, StreamReceiver streamReceiver, String filename, String type, long contentLength) throws UploadException {
    StreamVariable streamVariable = streamReceiver.getStreamVariable();
    if (streamVariable == null) {
        throw new IllegalStateException("StreamVariable for the post not found");
    }
    OutputStream out = null;
    long totalBytes = 0;
    StreamingStartEventImpl startedEvent = new StreamingStartEventImpl(filename, type, contentLength);
    try {
        boolean listenProgress;
        session.lock();
        try {
            streamVariable.streamingStarted(startedEvent);
            out = streamVariable.getOutputStream();
            listenProgress = streamVariable.listenProgress();
        } finally {
            session.unlock();
        }
        // Gets the output target stream
        if (out == null) {
            throw new NoOutputStreamException();
        }
        if (null == in) {
            // No file, for instance non-existent filename in html upload
            throw new NoInputStreamException();
        }
        final byte[] buffer = new byte[MAX_UPLOAD_BUFFER_SIZE];
        long lastStreamingEvent = 0;
        int bytesReadToBuffer;
        do {
            bytesReadToBuffer = in.read(buffer);
            if (bytesReadToBuffer > 0) {
                out.write(buffer, 0, bytesReadToBuffer);
                totalBytes += bytesReadToBuffer;
            }
            if (listenProgress) {
                StreamingProgressEventImpl progressEvent = new StreamingProgressEventImpl(filename, type, contentLength, totalBytes);
                lastStreamingEvent = updateProgress(session, streamVariable, progressEvent, lastStreamingEvent, bytesReadToBuffer);
            }
            if (streamVariable.isInterrupted()) {
                throw new UploadInterruptedException();
            }
        } while (bytesReadToBuffer > 0);
        // upload successful
        out.close();
        StreamVariable.StreamingEndEvent event = new StreamingEndEventImpl(filename, type, totalBytes);
        session.lock();
        try {
            streamVariable.streamingFinished(event);
        } finally {
            session.unlock();
        }
    } catch (UploadInterruptedException e) {
        // Download interrupted by application code
        tryToCloseStream(out);
        StreamVariable.StreamingErrorEvent event = new StreamingErrorEventImpl(filename, type, contentLength, totalBytes, e);
        session.lock();
        try {
            streamVariable.streamingFailed(event);
        } finally {
            session.unlock();
        }
    // Note, we are not throwing interrupted exception forward as it is
    // not a terminal level error like all other exception.
    } catch (final Exception e) {
        tryToCloseStream(out);
        session.lock();
        try {
            StreamVariable.StreamingErrorEvent event = new StreamingErrorEventImpl(filename, type, contentLength, totalBytes, e);
            streamVariable.streamingFailed(event);
            // throw exception for terminal to be handled (to be preplaceded to
            // terminalErrorHandler)
            throw new UploadException(e);
        } finally {
            session.unlock();
        }
    }
    return startedEvent.isDisposed();
}

7 Source : VertxStreamRequestHandler.java
with MIT License
from mcollovati

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        return false;
    }
    // remove leading '/'
    replacedert pathInfo.startsWith(Character.toString(PATH_SEPARATOR));
    pathInfo = pathInfo.substring(1);
    if (!pathInfo.startsWith(DYN_RES_PREFIX)) {
        return false;
    }
    Optional<AbstractStreamResource> abstractStreamResource;
    session.lock();
    try {
        abstractStreamResource = VertxStreamRequestHandler.getPathUri(pathInfo).flatMap(session.getResourceRegistry()::getResource);
        if (!abstractStreamResource.isPresent()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource is not found for path=" + pathInfo);
            return true;
        }
    } finally {
        session.unlock();
    }
    if (abstractStreamResource.isPresent()) {
        AbstractStreamResource resource = abstractStreamResource.get();
        if (resource instanceof StreamResource) {
            resourceHandler.handleRequest(session, request, response, (StreamResource) resource);
        } else if (resource instanceof StreamReceiver) {
            StreamReceiver streamReceiver = (StreamReceiver) resource;
            String[] parts = parsePath(pathInfo);
            receiverHandler.handleRequest(session, request, response, streamReceiver, parts[0], parts[1]);
        } else {
            getLogger().warn("Received unknown stream resource.");
        }
    }
    return true;
}

6 Source : StreamResourceHandler.java
with MIT License
from mcollovati

/**
 * 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);
    }
}