Search in sources :

Example 1 with CloseReason

use of jakarta.websocket.CloseReason in project atmosphere by Atmosphere.

the class JSR356Endpoint method onOpen.

@Override
public void onOpen(Session session, final EndpointConfig endpointConfig) {
    if (framework.isDestroyed())
        return;
    if (!session.isOpen()) {
        logger.trace("Session Closed {}", session);
        return;
    }
    if (maxBinaryBufferSize != -1)
        session.setMaxBinaryMessageBufferSize(maxBinaryBufferSize);
    if (webSocketWriteTimeout != -1)
        session.setMaxIdleTimeout(webSocketWriteTimeout);
    if (maxTextBufferSize != -1)
        session.setMaxTextMessageBufferSize(maxTextBufferSize);
    webSocket = new JSR356WebSocket(session, framework.getAtmosphereConfig());
    Map<String, String> headers = new HashMap<>();
    // TODO: We don't support multi map header, which cause => https://github.com/Atmosphere/atmosphere/issues/1945
    for (Map.Entry<String, List<String>> e : handshakeHeaders.entrySet()) {
        headers.put(e.getKey(), !e.getValue().isEmpty() ? e.getValue().get(0) : "");
    }
    // Force WebSocket. Hack for https://github.com/Atmosphere/atmosphere/issues/1944
    headers.put("Connection", "Upgrade");
    String servletPath = framework.getAtmosphereConfig().getInitParameter(ApplicationConfig.JSR356_MAPPING_PATH);
    if (servletPath == null) {
        servletPath = IOUtils.guestServletPath(framework.getAtmosphereConfig());
    }
    boolean recomputeForBackwardCompat = false;
    URI uri = session.getRequestURI();
    String rawPath = uri.getPath();
    String contextPath = framework.getAtmosphereConfig().getServletContext().getContextPath();
    int pathInfoStartAt = rawPath.indexOf(servletPath) + servletPath.length();
    String pathInfo = null;
    if (rawPath.length() >= pathInfoStartAt) {
        pathInfo = rawPath.substring(pathInfoStartAt);
    } else {
        recomputeForBackwardCompat = true;
    }
    if (recomputeForBackwardCompat) {
        // DON"T SCREAM this code is for broken/backward compatible
        String[] paths = uri.getPath() != null ? uri.getPath().split("/") : new String[] {};
        int pathInfoStartIndex = 3;
        if ("".equals(contextPath) || "".equals(servletPath)) {
            pathInfoStartIndex = 2;
        }
        // /contextPath / servletPath / pathInfo or / servletPath / pathInfo
        StringBuilder b = new StringBuilder("/");
        for (int i = 0; i < paths.length; i++) {
            if (i >= pathInfoStartIndex) {
                b.append(paths[i]).append("/");
            }
        }
        if (b.length() > 1) {
            b.deleteCharAt(b.length() - 1);
        }
        pathInfo = b.toString();
    }
    if (pathInfo.equals("/")) {
        pathInfo = null;
    }
    try {
        String requestURL = uri.toASCIIString();
        if (requestURL.contains("?")) {
            requestURL = requestURL.substring(0, requestURL.indexOf("?"));
        }
        // https://java.net/jira/browse/WEBSOCKET_SPEC-228
        if ((!requestURL.startsWith("http://")) || (!requestURL.startsWith("https://"))) {
            if (requestURL.startsWith("/")) {
                List<String> l = handshakeHeaders.get("origin");
                if (l == null) {
                    // https://issues.jboss.org/browse/UNDERTOW-252
                    l = handshakeHeaders.get("Origin");
                }
                String origin = null;
                if (l != null && !l.isEmpty()) {
                    origin = l.get(0);
                }
                // become something like 'null/path/to/resource'.
                if (origin == null || origin.equalsIgnoreCase("null")) {
                    // Broken WebSocket Spec
                    logger.trace("Unable to retrieve the `origin` header for websocket {}", session);
                    origin = "http" + (session.isSecure() ? "s" : "") + "://0.0.0.0:80";
                }
                requestURL = origin + requestURL;
            } else if (requestURL.startsWith("ws://")) {
                requestURL = requestURL.replace("ws://", "http://");
            } else if (requestURL.startsWith("wss://")) {
                requestURL = requestURL.replace("wss://", "https://");
            }
        }
        List<String> cookieHeaders = handshakeHeaders.get("cookie");
        if (cookieHeaders == null) {
            cookieHeaders = handshakeHeaders.get("Cookie");
        }
        Set<Cookie> cookies = null;
        if (cookieHeaders != null) {
            cookies = new HashSet<>();
            for (String cookieHeader : cookieHeaders) cookies.addAll(CookieUtil.ServerCookieDecoder.STRICT.decode(cookieHeader));
        }
        request = new AtmosphereRequestImpl.Builder().requestURI(uri.getPath()).requestURL(requestURL).headers(headers).cookies(cookies).session(handshakeSession).servletPath(servletPath).contextPath(framework.getServletContext().getContextPath()).pathInfo(pathInfo).destroyable(false).userPrincipal(session.getUserPrincipal()).remoteInetSocketAddress((Callable<InetSocketAddress>) () -> (InetSocketAddress) endpointConfig.getUserProperties().get(JAVAX_WEBSOCKET_ENDPOINT_REMOTE_ADDRESS)).localInetSocketAddress((Callable<InetSocketAddress>) () -> (InetSocketAddress) endpointConfig.getUserProperties().get(JAVAX_WEBSOCKET_ENDPOINT_LOCAL_ADDRESS)).build().queryString(session.getQueryString());
        if (!webSocketProcessor.handshake(request)) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Handshake not accepted."));
            } catch (IOException e) {
                logger.trace("", e);
            }
            return;
        }
        // TODO: Fix this crazy code.
        framework.addInitParameter(ALLOW_QUERYSTRING_AS_REQUEST, "false");
        webSocketProcessor.open(webSocket, request, AtmosphereResponseImpl.newInstance(framework.getAtmosphereConfig(), request, webSocket));
        framework.addInitParameter(ALLOW_QUERYSTRING_AS_REQUEST, "true");
        if (session.isOpen()) {
            // https://bz.apache.org/bugzilla/show_bug.cgi?format=multiple&id=57788
            session.addMessageHandler(new MessageHandler.Whole<String>() {

                @Override
                public void onMessage(String s) {
                    webSocketProcessor.invokeWebSocketProtocol(webSocket, s);
                }
            });
            session.addMessageHandler(new MessageHandler.Whole<ByteBuffer>() {

                @Override
                public void onMessage(ByteBuffer bb) {
                    byte[] b = bb.hasArray() ? bb.array() : new byte[((Buffer) bb).limit()];
                    bb.get(b);
                    webSocketProcessor.invokeWebSocketProtocol(webSocket, b, 0, b.length);
                }
            });
        } else {
            logger.trace("Session closed during onOpen {}", session);
            onClose(session, new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "Session closed already"));
        }
    } catch (Throwable e) {
        if (session.isOpen()) {
            logger.error("", e);
        } else {
            logger.trace("Session closed during onOpen", e);
        }
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, e.getMessage()));
        } catch (IOException e1) {
            logger.trace("", e);
        }
    }
}
Also used : MessageHandler(jakarta.websocket.MessageHandler) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) Callable(java.util.concurrent.Callable) CloseReason(jakarta.websocket.CloseReason) List(java.util.List) Cookie(jakarta.servlet.http.Cookie) ByteBuffer(java.nio.ByteBuffer) Buffer(java.nio.Buffer) IOException(java.io.IOException) JSR356WebSocket(org.atmosphere.container.version.JSR356WebSocket) ByteBuffer(java.nio.ByteBuffer) Endpoint(jakarta.websocket.Endpoint) AtmosphereRequestImpl(org.atmosphere.cpr.AtmosphereRequestImpl) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with CloseReason

use of jakarta.websocket.CloseReason in project spring-framework by spring-projects.

the class StandardWebSocketSession method close.

@Override
public Mono<Void> close(CloseStatus status) {
    try {
        CloseReason.CloseCode code = CloseCodes.getCloseCode(status.getCode());
        getDelegate().close(new CloseReason(code, status.getReason()));
    } catch (IOException ex) {
        return Mono.error(ex);
    }
    return Mono.empty();
}
Also used : CloseReason(jakarta.websocket.CloseReason) IOException(java.io.IOException)

Example 3 with CloseReason

use of jakarta.websocket.CloseReason in project spring-framework by spring-projects.

the class StandardWebSocketHandlerAdapterTests method onClose.

@Test
public void onClose() throws Throwable {
    this.adapter.onClose(this.session, new CloseReason(CloseCodes.NORMAL_CLOSURE, "reason"));
    verify(this.webSocketHandler).afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL.withReason("reason"));
}
Also used : CloseReason(jakarta.websocket.CloseReason) Test(org.junit.jupiter.api.Test)

Example 4 with CloseReason

use of jakarta.websocket.CloseReason in project tomcat by apache.

the class WsHttpUpgradeHandler method upgradeDispatch.

@Override
public SocketState upgradeDispatch(SocketEvent status) {
    switch(status) {
        case OPEN_READ:
            try {
                return wsFrame.notifyDataAvailable();
            } catch (WsIOException ws) {
                close(ws.getCloseReason());
            } catch (IOException ioe) {
                onError(ioe);
                CloseReason cr = new CloseReason(CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
                close(cr);
            }
            return SocketState.CLOSED;
        case OPEN_WRITE:
            wsRemoteEndpointServer.onWritePossible(false);
            break;
        case STOP:
            CloseReason cr = new CloseReason(CloseCodes.GOING_AWAY, sm.getString("wsHttpUpgradeHandler.serverStop"));
            try {
                wsSession.close(cr);
            } catch (IOException ioe) {
                onError(ioe);
                cr = new CloseReason(CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
                close(cr);
                return SocketState.CLOSED;
            }
            break;
        case ERROR:
            String msg = sm.getString("wsHttpUpgradeHandler.closeOnError");
            wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, msg), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg));
        // $FALL-THROUGH$
        case DISCONNECT:
        case TIMEOUT:
        case CONNECT_FAIL:
            return SocketState.CLOSED;
    }
    if (wsFrame.isOpen()) {
        return SocketState.UPGRADED;
    } else {
        return SocketState.CLOSED;
    }
}
Also used : CloseReason(jakarta.websocket.CloseReason) WsIOException(org.apache.tomcat.websocket.WsIOException) WsIOException(org.apache.tomcat.websocket.WsIOException) IOException(java.io.IOException)

Example 5 with CloseReason

use of jakarta.websocket.CloseReason in project tomcat by apache.

the class WsFrameBase method handleThrowableOnSend.

private void handleThrowableOnSend(Throwable t) throws WsIOException {
    ExceptionUtils.handleThrowable(t);
    wsSession.getLocal().onError(wsSession, t);
    CloseReason cr = new CloseReason(CloseCodes.CLOSED_ABNORMALLY, sm.getString("wsFrame.ioeTriggeredClose"));
    throw new WsIOException(cr);
}
Also used : CloseReason(jakarta.websocket.CloseReason)

Aggregations

CloseReason (jakarta.websocket.CloseReason)15 IOException (java.io.IOException)6 MessageHandler (jakarta.websocket.MessageHandler)2 ByteBuffer (java.nio.ByteBuffer)2 CoderResult (java.nio.charset.CoderResult)2 Cookie (jakarta.servlet.http.Cookie)1 Endpoint (jakarta.websocket.Endpoint)1 PongMessage (jakarta.websocket.PongMessage)1 InetSocketAddress (java.net.InetSocketAddress)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URI (java.net.URI)1 Buffer (java.nio.Buffer)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Callable (java.util.concurrent.Callable)1 WsIOException (org.apache.tomcat.websocket.WsIOException)1 JSR356WebSocket (org.atmosphere.container.version.JSR356WebSocket)1 AtmosphereRequestImpl (org.atmosphere.cpr.AtmosphereRequestImpl)1