io.undertow.websockets.spi.WebSocketHttpExchange Java Examples

The following examples show how to use io.undertow.websockets.spi.WebSocketHttpExchange. 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: UndertowWebSocketFilter.java    From pippo with Apache License 2.0 6 votes vote down vote up
private void processWebSocketRequest(Request request, Response response) {
        HttpServletRequest servletRequest = request.getHttpServletRequest();
        HttpServletResponse servletResponse = response.getHttpServletResponse();

        WebSocketHttpExchange exchange = new ServletWebSocketHttpExchange(servletRequest, servletResponse, peerConnections);
//        exchange.putAttachment(HandshakeUtil.PATH_PARAMS, Collections.<String, String>emptyMap());

        Handshake handshake = getHandshake(exchange);

        exchange.upgradeChannel((connection, serverExchange) -> {
            WebSocketChannel channel = handshake.createChannel(exchange, connection, exchange.getBufferPool());
            peerConnections.add(channel);
            createWebSocketAdapter(request).onConnect(exchange, channel);
        });

        handshake.handshake(exchange);
    }
 
Example #2
Source File: WebSocketHandler.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    if (this.hasAuthentication) {
        String header = null;
        if (exchange.getRequestHeader(Header.COOKIE.toString()) != null) {
            header = exchange.getRequestHeader(Header.COOKIE.toString());
        }
        
        if (RequestUtils.hasValidAuthentication(header)) {
            channel.getReceiveSetter().set((ChannelListener<? super WebSocketChannel>) Application.getInstance(this.controllerClass));
            channel.resumeReceives();
            channel.addCloseTask(Application.getInstance(WebSocketCloseListener.class));
            Application.getInstance(WebSocketService.class).addChannel(channel);
        } else {
            MangooUtils.closeQuietly(channel);
        }
    } else {
        channel.getReceiveSetter().set((ChannelListener<? super WebSocketChannel>) Application.getInstance(this.controllerClass));
        channel.resumeReceives();
        channel.addCloseTask(Application.getInstance(WebSocketCloseListener.class));
        Application.getInstance(WebSocketService.class).addChannel(channel);
    }
}
 
Example #3
Source File: EventsPath.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    try {
        Cookie sid = getRequestCookies(exchange).get("PYX-Session");

        User user;
        if (sid == null || (user = Sessions.get().getUser(sid.getValue())) == null) {
            sendConnectionError(exchange, channel, new JsonWrapper(Consts.ErrorCode.NOT_REGISTERED));
        } else if (!user.isValid()) {
            sendConnectionError(exchange, channel, new JsonWrapper(Consts.ErrorCode.SESSION_EXPIRED));
        } else {
            if (user.getEventsSender() == null) user.establishedEventsConnection(new EventsSender(user, channel));
            else user.getEventsSender().addChannel(channel);

            channel.getCloseSetter().set((ChannelListener<AbstractFramedChannel>) newChannel -> {
                if (user.getEventsSender() != null)
                    user.getEventsSender().removeChannel((WebSocketChannel) newChannel);
            });
        }
    } catch (Throwable ex) {
        logger.error("Failed handling incoming connection.", ex);
        throw ex;
    }
}
 
Example #4
Source File: EventBusToWebSocket.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {

    String uri = exchange.getRequestURI();
    final String subscriptionId = uri.substring(path.length() + 1);
    EventReservationsHandler.Reservation reservation = eventReservationsHandler.claimReservation(subscriptionId);
    if (reservation == null) {
        send(channel, "error", "Invalid subscription: not reserved");
        safeClose(channel);
        return;
    }
    LOG.debug("Principal is: {}", reservation.getPrincipal());
    send(channel, "message", "connected");
    bus.subscribe(subscriptionId, (type, data) -> {
        if (channel.isOpen()) {
            send(channel, type, data);
        } else {
            bus.unsubscribe(subscriptionId);
        }
    });
}
 
Example #5
Source File: Hybi07Handshake.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected void handshakeInternal(final WebSocketHttpExchange exchange) {

        String origin = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_ORIGIN_STRING);
        if (origin != null) {
            exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ORIGIN_STRING, origin);
        }
        selectSubprotocol(exchange);
        selectExtensions(exchange);
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_LOCATION_STRING, getWebSocketLocation(exchange));

        final String key = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING);
        try {
            final String solution = solve(key);
            exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ACCEPT_STRING, solution);
            performUpgrade(exchange);
        } catch (NoSuchAlgorithmException e) {
            IoUtils.safeClose(exchange);
            exchange.endExchange();
            return;
        }

    }
 
Example #6
Source File: Hybi13Handshake.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void handshakeInternal(final WebSocketHttpExchange exchange) {
    String origin = exchange.getRequestHeader(Headers.ORIGIN_STRING);
    if (origin != null) {
        exchange.setResponseHeader(Headers.ORIGIN_STRING, origin);
    }
    selectSubprotocol(exchange);
    selectExtensions(exchange);
    exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_LOCATION_STRING, getWebSocketLocation(exchange));

    final String key = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING);
    try {
        final String solution = solve(key);
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_ACCEPT_STRING, solution);
        performUpgrade(exchange);
    } catch (NoSuchAlgorithmException e) {
        IoUtils.safeClose(exchange);
        exchange.endExchange();
        return;
    }
}
 
Example #7
Source File: Handshake.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the {@code ExtensionFunction} list associated with the negotiated extensions defined in the exchange's response.
 *
 * @param exchange the exchange used to retrieve negotiated extensions
 * @return         a list of {@code ExtensionFunction} with the implementation of the extensions
 */
protected final List<ExtensionFunction> initExtensions(final WebSocketHttpExchange exchange) {
    String extHeader = exchange.getResponseHeaders().get(Headers.SEC_WEB_SOCKET_EXTENSIONS_STRING) != null ?
            exchange.getResponseHeaders().get(Headers.SEC_WEB_SOCKET_EXTENSIONS_STRING).get(0) : null;

    List<ExtensionFunction> negotiated = new ArrayList<>();
    if (extHeader != null) {
        List<WebSocketExtension> extensions = WebSocketExtension.parse(extHeader);
        if (extensions != null && !extensions.isEmpty()) {
            for (WebSocketExtension ext : extensions) {
                for (ExtensionHandshake extHandshake : availableExtensions) {
                    if (extHandshake.getName().equals(ext.getName())) {
                        negotiated.add(extHandshake.create());
                    }
                }
            }
        }
    }
    return negotiated;
}
 
Example #8
Source File: Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void upgradeChannel(final WebSocketHttpExchange exchange, final byte[] data) {
    if (data.length > 0) {
        writePayload(exchange, ByteBuffer.wrap(data));
    } else {
        exchange.endExchange();
    }
}
 
Example #9
Source File: UndertowWebSocketAdapter.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    connection = new UndertowWebSocketConnection(exchange, channel);
    connections.add(connection);

    context = new WebSocketContext(connectionsReadOnly, connection, pathParameters);

    handler.onOpen(context);

    channel.addCloseTask(ch -> connections.remove(connection));
    channel.getReceiveSetter().set(this);
    channel.resumeReceives();
}
 
Example #10
Source File: UndertowWebSocketFilter.java    From pippo with Apache License 2.0 5 votes vote down vote up
private Handshake getHandshake(WebSocketHttpExchange exchange) {
    for (Handshake handshake : handshakes) {
        if (handshake.matches(exchange)) {
            return handshake;
        }
    }

    throw new PippoRuntimeException("No matching Undertow Handshake found: {}", exchange.getRequestHeaders());
}
 
Example #11
Source File: Hybi07Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean matches(final WebSocketHttpExchange exchange) {
    if (exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_KEY_STRING) != null &&
            exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_VERSION_STRING) != null) {
        return exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_VERSION_STRING)
                .equals(getVersion().toHttpHeaderValue());
    }
    return false;
}
 
Example #12
Source File: Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected final void selectExtensions(final WebSocketHttpExchange exchange) {
    List<WebSocketExtension> requestedExtensions = WebSocketExtension.parse(exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_EXTENSIONS_STRING));
    List<WebSocketExtension> extensions = selectedExtension(requestedExtensions);
    if (extensions != null && !extensions.isEmpty()) {
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_EXTENSIONS_STRING, WebSocketExtension.toExtensionHeader(extensions));
    }

}
 
Example #13
Source File: Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Selects the first matching supported sub protocol and add it the the headers of the exchange.
 *
 */
protected final void selectSubprotocol(final WebSocketHttpExchange exchange) {
    String requestedSubprotocols = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING);
    if (requestedSubprotocols == null) {
        return;
    }

    String[] requestedSubprotocolArray = PATTERN.split(requestedSubprotocols);
    String subProtocol = supportedSubprotols(requestedSubprotocolArray);
    if (subProtocol != null && !subProtocol.isEmpty()) {
        exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING, subProtocol);
    }

}
 
Example #14
Source File: Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static void writePayload(final WebSocketHttpExchange exchange, final ByteBuffer payload) {
    exchange.sendData(payload).addNotifier(new IoFuture.Notifier<Void, Object>() {
        @Override
        public void notify(final IoFuture<? extends Void> ioFuture, final Object attachment) {
            if (ioFuture.getStatus() == IoFuture.Status.DONE) {
                exchange.endExchange();
            } else {
                exchange.close();
            }
        }
    }, null);
}
 
Example #15
Source File: UndertowRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
	UndertowWebSocketSession session = createSession(channel);
	UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session);

	channel.getReceiveSetter().set(adapter);
	channel.resumeReceives();

	this.handler.handle(session)
			.checkpoint(exchange.getRequestURI() + " [UndertowRequestUpgradeStrategy]")
			.subscribe(session);
}
 
Example #16
Source File: Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * convenience method to perform the upgrade
 */
protected final void performUpgrade(final WebSocketHttpExchange exchange, final byte[] data) {
    exchange.setResponseHeader(Headers.CONTENT_LENGTH_STRING, String.valueOf(data.length));
    exchange.setResponseHeader(Headers.UPGRADE_STRING, "WebSocket");
    exchange.setResponseHeader(Headers.CONNECTION_STRING, "Upgrade");
    upgradeChannel(exchange, data);
}
 
Example #17
Source File: UndertowRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange httpExchange, WebSocketChannel channel) {
	UndertowWebSocketSession session = createSession(channel);
	UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session);

	channel.getReceiveSetter().set(adapter);
	channel.resumeReceives();

	this.handler.handle(session).subscribe(session);
}
 
Example #18
Source File: Handshake.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the full url of the websocket location of the given {@link WebSocketHttpExchange}
 */
protected static String getWebSocketLocation(WebSocketHttpExchange exchange) {
    String scheme;
    if ("https".equals(exchange.getRequestScheme())) {
        scheme = "wss";
    } else {
        scheme = "ws";
    }
    return scheme + "://" + exchange.getRequestHeader(Headers.HOST_STRING) + exchange.getRequestURI();
}
 
Example #19
Source File: WSServer.java    From greycat with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange webSocketHttpExchange, WebSocketChannel webSocketChannel) {
    final Graph graph = builder.build();
    graph.setProperty("ws.source", webSocketChannel.getSourceAddress().getAddress());
    graph.connect(new Callback<Boolean>() {
        @Override
        public void on(Boolean result) {
            webSocketChannel.getReceiveSetter().set(new PeerInternalListener(graph));
            webSocketChannel.resumeReceives();
            peers.add(webSocketChannel);
        }
    });
}
 
Example #20
Source File: WSServer.java    From greycat with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange webSocketHttpExchange, WebSocketChannel webSocketChannel) {
    webSocketChannel.getReceiveSetter().set(new InternalListener());
    webSocketChannel.resumeReceives();
    webSocketChannel.setAttribute("id", channelCounter.get());
    peers.put(channelCounter.getAndIncrement(), webSocketChannel);
    if (channelCounter.get() == Integer.MAX_VALUE) {
        channelCounter.set(0);
    }
}
 
Example #21
Source File: Hybi07Handshake.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public WebSocketChannel createChannel(WebSocketHttpExchange exchange, final StreamConnection channel, final ByteBufferPool pool) {
    List<ExtensionFunction> extensionFunctions = initExtensions(exchange);
    return new WebSocket07Channel(channel, pool, getWebSocketLocation(exchange), exchange.getResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING), false, !extensionFunctions.isEmpty(), CompositeExtensionFunction.compose(extensionFunctions), exchange.getPeerConnections(), exchange.getOptions());
}
 
Example #22
Source File: WSSharedServer.java    From greycat with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange webSocketHttpExchange, WebSocketChannel webSocketChannel) {
    webSocketChannel.getReceiveSetter().set(new PeerInternalListener());
    webSocketChannel.resumeReceives();
    peers.add(webSocketChannel);
}
 
Example #23
Source File: WSServerWithWorkers.java    From greycat with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnect(WebSocketHttpExchange webSocketHttpExchange, WebSocketChannel webSocketChannel) {
    webSocketChannel.getReceiveSetter().set(new PeerInternalListener(webSocketChannel));
    webSocketChannel.resumeReceives();
    peers.add(webSocketChannel);
}
 
Example #24
Source File: UndertowWebSocketConnection.java    From pippo with Apache License 2.0 4 votes vote down vote up
public WebSocketHttpExchange getExchange() {
    return exchange;
}
 
Example #25
Source File: UndertowWebSocketConnection.java    From pippo with Apache License 2.0 4 votes vote down vote up
public UndertowWebSocketConnection(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    this.exchange = exchange;
    this.channel = channel;
}
 
Example #26
Source File: EventsPath.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
private static void sendConnectionError(WebSocketHttpExchange exchange, WebSocketChannel channel, JsonWrapper error) {
    WebSockets.sendText(error.toString(), channel, null);
    exchange.endExchange();
}
 
Example #27
Source File: EventsPath.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
private static Map<String, Cookie> getRequestCookies(WebSocketHttpExchange exchange) {
    return Cookies.parseRequestCookies(200, false, exchange.getRequestHeaders().get(Headers.COOKIE_STRING));
}
 
Example #28
Source File: Hybi08Handshake.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public WebSocketChannel createChannel(final WebSocketHttpExchange exchange, final StreamConnection channel, final ByteBufferPool pool) {
    List<ExtensionFunction> extensionFunctions = initExtensions(exchange);
    return new WebSocket08Channel(channel, pool, getWebSocketLocation(exchange), exchange.getResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING), false, !extensionFunctions.isEmpty(), CompositeExtensionFunction.compose(extensionFunctions), exchange.getPeerConnections(), exchange.getOptions());

}
 
Example #29
Source File: Hybi13Handshake.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public WebSocketChannel createChannel(WebSocketHttpExchange exchange, final StreamConnection channel, final ByteBufferPool pool) {
    List<ExtensionFunction> extensionFunctions = initExtensions(exchange);
    return new WebSocket13Channel(channel, pool, getWebSocketLocation(exchange), exchange.getResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING), false, !extensionFunctions.isEmpty(), CompositeExtensionFunction.compose(extensionFunctions), exchange.getPeerConnections(), exchange.getOptions());
}
 
Example #30
Source File: Handshake.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform the upgrade using no payload
 */
protected final void performUpgrade(final WebSocketHttpExchange exchange) {
    performUpgrade(exchange, EMPTY);
}