Search in sources :

Example 16 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class DefaultServer method wrapOpenListener.

private static ChannelListener<StreamConnection> wrapOpenListener(final ChannelListener<StreamConnection> listener) {
    if (!single) {
        return listener;
    }
    return new ChannelListener<StreamConnection>() {

        @Override
        public void handleEvent(StreamConnection channel) {
            channel.getSinkChannel().setConduit(new SingleByteStreamSinkConduit(channel.getSinkChannel().getConduit(), 10000));
            channel.getSourceChannel().setConduit(new SingleByteStreamSourceConduit(channel.getSourceChannel().getConduit(), 10000));
            listener.handleEvent(channel);
        }
    };
}
Also used : SingleByteStreamSinkConduit(io.undertow.util.SingleByteStreamSinkConduit) ChannelListener(org.xnio.ChannelListener) StreamConnection(org.xnio.StreamConnection) SingleByteStreamSourceConduit(io.undertow.util.SingleByteStreamSourceConduit)

Example 17 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class JsrWebSocketFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (req.getHeader(Headers.UPGRADE_STRING) != null) {
        final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
        String path;
        if (req.getPathInfo() == null) {
            path = req.getServletPath();
        } else {
            path = req.getServletPath() + req.getPathInfo();
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        PathTemplateMatcher.PathMatchResult<WebSocketHandshakeHolder> matchResult = pathTemplateMatcher.match(path);
        if (matchResult != null) {
            Handshake handshaker = null;
            for (Handshake method : matchResult.getValue().handshakes) {
                if (method.matches(facade)) {
                    handshaker = method;
                    break;
                }
            }
            if (handshaker != null) {
                if (container.isClosed()) {
                    resp.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                    return;
                }
                facade.putAttachment(HandshakeUtil.PATH_PARAMS, matchResult.getParameters());
                facade.putAttachment(HandshakeUtil.PRINCIPAL, req.getUserPrincipal());
                final Handshake selected = handshaker;
                facade.upgradeChannel(new HttpUpgradeListener() {

                    @Override
                    public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                        WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
                        peerConnections.add(channel);
                        callback.onConnect(facade, channel);
                    }
                });
                handshaker.handshake(facade);
                return;
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : WebSocketHandshakeHolder(io.undertow.websockets.jsr.ServerWebSocketContainer.WebSocketHandshakeHolder) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) HttpServletResponse(javax.servlet.http.HttpServletResponse) StreamConnection(org.xnio.StreamConnection) ServletWebSocketHttpExchange(io.undertow.servlet.websockets.ServletWebSocketHttpExchange) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServerExchange(io.undertow.server.HttpServerExchange) PathTemplateMatcher(io.undertow.util.PathTemplateMatcher) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) Handshake(io.undertow.websockets.core.protocol.Handshake)

Example 18 with StreamConnection

use of org.xnio.StreamConnection in project undertow by undertow-io.

the class ServerWebSocketContainer method doUpgrade.

public void doUpgrade(HttpServletRequest request, HttpServletResponse response, final ServerEndpointConfig sec, Map<String, String> pathParams) throws ServletException, IOException {
    ServerEndpointConfig.Configurator configurator = sec.getConfigurator();
    try {
        EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, sec.getDecoders(), sec.getEncoders());
        PathTemplate pt = PathTemplate.create(sec.getPath());
        InstanceFactory<?> instanceFactory = null;
        try {
            instanceFactory = classIntrospecter.createInstanceFactory(sec.getEndpointClass());
        } catch (Exception e) {
            //so it is possible that this is still valid if a custom configurator is in use
            if (configurator == null || configurator.getClass() == ServerEndpointConfig.Configurator.class) {
                throw JsrWebSocketMessages.MESSAGES.couldNotDeploy(e);
            } else {
                instanceFactory = new InstanceFactory<Object>() {

                    @Override
                    public InstanceHandle<Object> createInstance() throws InstantiationException {
                        throw JsrWebSocketMessages.MESSAGES.endpointDoesNotHaveAppropriateConstructor(sec.getEndpointClass());
                    }
                };
            }
        }
        if (configurator == null) {
            configurator = DefaultContainerConfigurator.INSTANCE;
        }
        ServerEndpointConfig config = ServerEndpointConfig.Builder.create(sec.getEndpointClass(), sec.getPath()).decoders(sec.getDecoders()).encoders(sec.getEncoders()).subprotocols(sec.getSubprotocols()).extensions(sec.getExtensions()).configurator(configurator).build();
        AnnotatedEndpointFactory annotatedEndpointFactory = null;
        if (!Endpoint.class.isAssignableFrom(sec.getEndpointClass())) {
            annotatedEndpointFactory = AnnotatedEndpointFactory.create(sec.getEndpointClass(), encodingFactory, pt.getParameterNames());
        }
        ConfiguredServerEndpoint confguredServerEndpoint;
        if (annotatedEndpointFactory == null) {
            confguredServerEndpoint = new ConfiguredServerEndpoint(config, instanceFactory, null, encodingFactory);
        } else {
            confguredServerEndpoint = new ConfiguredServerEndpoint(config, instanceFactory, null, encodingFactory, annotatedEndpointFactory, installedExtensions);
        }
        WebSocketHandshakeHolder hand;
        WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) request.getServletContext().getAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
        if (info == null || info.getExtensions() == null) {
            hand = ServerWebSocketContainer.handshakes(confguredServerEndpoint);
        } else {
            hand = ServerWebSocketContainer.handshakes(confguredServerEndpoint, info.getExtensions());
        }
        final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(request, response, new HashSet<WebSocketChannel>());
        Handshake handshaker = null;
        for (Handshake method : hand.handshakes) {
            if (method.matches(facade)) {
                handshaker = method;
                break;
            }
        }
        if (handshaker != null) {
            if (isClosed()) {
                response.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                return;
            }
            facade.putAttachment(HandshakeUtil.PATH_PARAMS, pathParams);
            final Handshake selected = handshaker;
            facade.upgradeChannel(new HttpUpgradeListener() {

                @Override
                public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                    WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
                    new EndpointSessionHandler(ServerWebSocketContainer.this).onConnect(facade, channel);
                }
            });
            handshaker.handshake(facade);
            return;
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) PathTemplate(io.undertow.util.PathTemplate) StreamConnection(org.xnio.StreamConnection) ServletWebSocketHttpExchange(io.undertow.servlet.websockets.ServletWebSocketHttpExchange) ServletException(javax.servlet.ServletException) DeploymentException(javax.websocket.DeploymentException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UpgradeFailedException(org.xnio.http.UpgradeFailedException) HttpServerExchange(io.undertow.server.HttpServerExchange) ServletException(javax.servlet.ServletException) AnnotatedEndpointFactory(io.undertow.websockets.jsr.annotated.AnnotatedEndpointFactory) Endpoint(javax.websocket.Endpoint) ServerEndpoint(javax.websocket.server.ServerEndpoint) ClientEndpoint(javax.websocket.ClientEndpoint) ConstructorInstanceFactory(io.undertow.servlet.util.ConstructorInstanceFactory) InstanceFactory(io.undertow.servlet.api.InstanceFactory) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) ExtensionHandshake(io.undertow.websockets.extensions.ExtensionHandshake) JsrHybi13Handshake(io.undertow.websockets.jsr.handshake.JsrHybi13Handshake) JsrHybi08Handshake(io.undertow.websockets.jsr.handshake.JsrHybi08Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake) JsrHybi07Handshake(io.undertow.websockets.jsr.handshake.JsrHybi07Handshake)

Example 19 with StreamConnection

use of org.xnio.StreamConnection in project wildfly by wildfly.

the class HTTPUpgradeService method switchToMessagingProtocol.

private static HttpUpgradeListener switchToMessagingProtocol(final ActiveMQServer activemqServer, final String acceptorName, final String protocolName) {
    return new HttpUpgradeListener() {

        @Override
        public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
            ChannelListener<StreamConnection> listener = new ChannelListener<StreamConnection>() {

                @Override
                public void handleEvent(StreamConnection connection) {
                    MessagingLogger.ROOT_LOGGER.debugf("Switching to %s protocol for %s http-acceptor", protocolName, acceptorName);
                    ActiveMQServer server = selectServer(exchange, activemqServer);
                    RemotingService remotingService = server.getRemotingService();
                    if (!server.isActive() || !remotingService.isStarted()) {
                        // ActiveMQ does not accept connection
                        IoUtils.safeClose(connection);
                        return;
                    }
                    NettyAcceptor acceptor = (NettyAcceptor) remotingService.getAcceptor(acceptorName);
                    SocketChannel channel = new WrappingXnioSocketChannel(connection);
                    try {
                        acceptor.transfer(channel);
                        connection.getSourceChannel().resumeReads();
                    } catch (IllegalStateException e) {
                        IoUtils.safeClose(connection);
                    }
                }
            };
            ChannelListeners.invokeChannelListener(streamConnection, listener);
        }
    };
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) WrappingXnioSocketChannel(org.xnio.netty.transport.WrappingXnioSocketChannel) ActiveMQServer(org.apache.activemq.artemis.core.server.ActiveMQServer) SocketChannel(io.netty.channel.socket.SocketChannel) WrappingXnioSocketChannel(org.xnio.netty.transport.WrappingXnioSocketChannel) ChannelListener(org.xnio.ChannelListener) RemotingService(org.apache.activemq.artemis.core.remoting.server.RemotingService) NettyAcceptor(org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptor) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) StreamConnection(org.xnio.StreamConnection)

Example 20 with StreamConnection

use of org.xnio.StreamConnection in project indy by Commonjava.

the class HttpProxy method start.

@Override
public void start() throws IndyLifecycleException {
    if (!config.isEnabled()) {
        logger.info("HTTProx proxy is disabled.");
        return;
    }
    String bind;
    if (bootOptions.getBind() == null) {
        bind = "0.0.0.0";
    } else {
        bind = bootOptions.getBind();
    }
    logger.info("Starting HTTProx proxy on: {}:{}", bind, config.getPort());
    XnioWorker worker;
    try {
        worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
        final InetSocketAddress addr;
        if (config.getPort() < 1) {
            ThreadLocal<InetSocketAddress> using = new ThreadLocal<>();
            ThreadLocal<IOException> errorHolder = new ThreadLocal<>();
            server = PortFinder.findPortFor(16, (foundPort) -> {
                InetSocketAddress a = new InetSocketAddress(bind, config.getPort());
                AcceptingChannel<StreamConnection> result = worker.createStreamConnectionServer(a, acceptHandler, OptionMap.EMPTY);
                result.resumeAccepts();
                using.set(a);
                return result;
            });
            addr = using.get();
            config.setPort(addr.getPort());
        } else {
            addr = new InetSocketAddress(bind, config.getPort());
            server = worker.createStreamConnectionServer(addr, acceptHandler, OptionMap.EMPTY);
            server.resumeAccepts();
        }
        logger.info("HTTProxy listening on: {}", addr);
    } catch (IllegalArgumentException | IOException e) {
        throw new IndyLifecycleException("Failed to start HTTProx general content proxy: %s", e, e.getMessage());
    }
}
Also used : Logger(org.slf4j.Logger) Xnio(org.xnio.Xnio) ShutdownAction(org.commonjava.indy.action.ShutdownAction) XnioWorker(org.xnio.XnioWorker) PortFinder(org.commonjava.indy.boot.PortFinder) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) IndyLifecycleException(org.commonjava.indy.action.IndyLifecycleException) BootOptions(org.commonjava.indy.boot.BootOptions) AcceptingChannel(org.xnio.channels.AcceptingChannel) InetSocketAddress(java.net.InetSocketAddress) OptionMap(org.xnio.OptionMap) Inject(javax.inject.Inject) StreamConnection(org.xnio.StreamConnection) HttproxConfig(org.commonjava.indy.httprox.conf.HttproxConfig) StartupAction(org.commonjava.indy.action.StartupAction) ProxyAcceptHandler(org.commonjava.indy.httprox.handler.ProxyAcceptHandler) ApplicationScoped(javax.enterprise.context.ApplicationScoped) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) IndyLifecycleException(org.commonjava.indy.action.IndyLifecycleException) AcceptingChannel(org.xnio.channels.AcceptingChannel)

Aggregations

StreamConnection (org.xnio.StreamConnection)20 IOException (java.io.IOException)9 HttpServerExchange (io.undertow.server.HttpServerExchange)8 HttpUpgradeListener (io.undertow.server.HttpUpgradeListener)8 InetSocketAddress (java.net.InetSocketAddress)7 ChannelListener (org.xnio.ChannelListener)6 OptionMap (org.xnio.OptionMap)5 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)4 Handshake (io.undertow.websockets.core.protocol.Handshake)4 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)3 HttpOpenListener (io.undertow.server.protocol.http.HttpOpenListener)3 ConduitStreamSinkChannel (org.xnio.conduits.ConduitStreamSinkChannel)3 Http2Channel (io.undertow.protocols.http2.Http2Channel)2 HttpHandler (io.undertow.server.HttpHandler)2 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)2 DeploymentManager (io.undertow.servlet.api.DeploymentManager)2 FilterInfo (io.undertow.servlet.api.FilterInfo)2 ServletContainer (io.undertow.servlet.api.ServletContainer)2 ServletWebSocketHttpExchange (io.undertow.servlet.websockets.ServletWebSocketHttpExchange)2 Hybi07Handshake (io.undertow.websockets.core.protocol.version07.Hybi07Handshake)2