Search in sources :

Example 6 with ChannelListener

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

the class AnnotatedAutobahnServer method run.

public void run() {
    Xnio xnio = Xnio.getInstance();
    try {
        XnioWorker worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_WRITE_THREADS, 4).set(Options.WORKER_READ_THREADS, 4).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 10).set(Options.WORKER_TASK_MAX_THREADS, 12).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
        OptionMap serverOptions = OptionMap.builder().set(Options.WORKER_ACCEPT_THREADS, 4).set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).getMap();
        DefaultByteBufferPool pool = new DefaultByteBufferPool(true, 8024);
        HttpOpenListener openListener = new HttpOpenListener(pool);
        ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
        AcceptingChannel<StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, serverOptions);
        server.resumeAccepts();
        final ServletContainer container = ServletContainer.Factory.newInstance();
        DeploymentInfo builder = new DeploymentInfo().setClassLoader(AnnotatedAutobahnServer.class.getClassLoader()).setContextPath("/").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, new WebSocketDeploymentInfo().setBuffers(pool).setWorker(worker).addEndpoint(AutobahnAnnotatedEndpoint.class).setDispatchToWorkerThread(true).addExtension(new PerMessageDeflateHandshake())).addFilter(new FilterInfo("filter", JsrWebSocketFilter.class)).addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST);
        DeploymentManager manager = container.addDeployment(builder);
        manager.deploy();
        openListener.setRootHandler(manager.start());
    } catch (Exception e) {
        log.error("failed to start server", e);
    }
}
Also used : ChannelListener(org.xnio.ChannelListener) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) DeploymentManager(io.undertow.servlet.api.DeploymentManager) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) StreamConnection(org.xnio.StreamConnection) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) Xnio(org.xnio.Xnio) OptionMap(org.xnio.OptionMap) ServletContainer(io.undertow.servlet.api.ServletContainer) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) FilterInfo(io.undertow.servlet.api.FilterInfo)

Example 7 with ChannelListener

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

the class ProgramaticAutobahnServer method run.

public void run() {
    Xnio xnio = Xnio.getInstance();
    try {
        XnioWorker worker = xnio.createWorker(OptionMap.builder().set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 10).set(Options.WORKER_TASK_MAX_THREADS, 12).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
        OptionMap serverOptions = OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).getMap();
        DefaultByteBufferPool pool = new DefaultByteBufferPool(true, 8192);
        HttpOpenListener openListener = new HttpOpenListener(pool);
        ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
        AcceptingChannel<StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, serverOptions);
        server.resumeAccepts();
        final ServletContainer container = ServletContainer.Factory.newInstance();
        DeploymentInfo builder = new DeploymentInfo().setClassLoader(ProgramaticAutobahnServer.class.getClassLoader()).setContextPath("/").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").addFilter(new FilterInfo("filter", JsrWebSocketFilter.class)).addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, new WebSocketDeploymentInfo().setBuffers(pool).setWorker(worker).setDispatchToWorkerThread(true).addEndpoint(new ServerEndpointConfigImpl(ProgramaticAutobahnEndpoint.class, "/")).addExtension(new PerMessageDeflateHandshake()));
        DeploymentManager manager = container.addDeployment(builder);
        manager.deploy();
        openListener.setRootHandler(manager.start());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ChannelListener(org.xnio.ChannelListener) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) DeploymentManager(io.undertow.servlet.api.DeploymentManager) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) ServerEndpointConfigImpl(io.undertow.websockets.jsr.ServerEndpointConfigImpl) StreamConnection(org.xnio.StreamConnection) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) Xnio(org.xnio.Xnio) JsrWebSocketFilter(io.undertow.websockets.jsr.JsrWebSocketFilter) OptionMap(org.xnio.OptionMap) ServletContainer(io.undertow.servlet.api.ServletContainer) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) FilterInfo(io.undertow.servlet.api.FilterInfo)

Example 8 with ChannelListener

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

the class Http2ClientConnection method sendRequest.

@Override
public void sendRequest(ClientRequest request, ClientCallback<ClientExchange> clientCallback) {
    request.getRequestHeaders().put(METHOD, request.getMethod().toString());
    boolean connectRequest = request.getMethod().equals(Methods.CONNECT);
    if (!connectRequest) {
        request.getRequestHeaders().put(PATH, request.getPath());
        request.getRequestHeaders().put(SCHEME, secure ? "https" : "http");
    }
    final String host = request.getRequestHeaders().getFirst(Headers.HOST);
    if (host != null) {
        request.getRequestHeaders().put(AUTHORITY, host);
    } else {
        request.getRequestHeaders().put(AUTHORITY, defaultHost);
    }
    request.getRequestHeaders().remove(Headers.HOST);
    boolean hasContent = true;
    String fixedLengthString = request.getRequestHeaders().getFirst(CONTENT_LENGTH);
    String transferEncodingString = request.getRequestHeaders().getLast(TRANSFER_ENCODING);
    if (fixedLengthString != null) {
        try {
            long length = Long.parseLong(fixedLengthString);
            hasContent = length != 0;
        } catch (NumberFormatException e) {
            handleError(new IOException(e));
            return;
        }
    } else if (transferEncodingString == null && !connectRequest) {
        hasContent = false;
    }
    request.getRequestHeaders().remove(Headers.CONNECTION);
    request.getRequestHeaders().remove(Headers.KEEP_ALIVE);
    request.getRequestHeaders().remove(Headers.TRANSFER_ENCODING);
    //setup the X-Forwarded-* headers
    String peer = request.getAttachment(ProxiedRequestAttachments.REMOTE_HOST);
    if (peer != null) {
        request.getRequestHeaders().put(Headers.X_FORWARDED_FOR, peer);
    }
    Boolean proto = request.getAttachment(ProxiedRequestAttachments.IS_SSL);
    if (proto == null || !proto) {
        request.getRequestHeaders().put(Headers.X_FORWARDED_PROTO, "http");
    } else {
        request.getRequestHeaders().put(Headers.X_FORWARDED_PROTO, "https");
    }
    String hn = request.getAttachment(ProxiedRequestAttachments.SERVER_NAME);
    if (hn != null) {
        request.getRequestHeaders().put(Headers.X_FORWARDED_HOST, NetworkUtils.formatPossibleIpv6Address(hn));
    }
    Integer port = request.getAttachment(ProxiedRequestAttachments.SERVER_PORT);
    if (port != null) {
        request.getRequestHeaders().put(Headers.X_FORWARDED_PORT, port);
    }
    Http2HeadersStreamSinkChannel sinkChannel;
    try {
        sinkChannel = http2Channel.createStream(request.getRequestHeaders());
    } catch (IOException e) {
        clientCallback.failed(e);
        return;
    }
    Http2ClientExchange exchange = new Http2ClientExchange(this, sinkChannel, request);
    currentExchanges.put(sinkChannel.getStreamId(), exchange);
    if (clientCallback != null) {
        clientCallback.completed(exchange);
    }
    if (!hasContent) {
        //otherwise it is up to the user
        try {
            sinkChannel.shutdownWrites();
            if (!sinkChannel.flush()) {
                sinkChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(null, new ChannelExceptionHandler<StreamSinkChannel>() {

                    @Override
                    public void handleException(StreamSinkChannel channel, IOException exception) {
                        handleError(exception);
                    }
                }));
                sinkChannel.resumeWrites();
            }
        } catch (IOException e) {
            handleError(e);
        }
    } else if (!sinkChannel.isWriteResumed()) {
        try {
            //TODO: this needs some more thought
            if (!sinkChannel.flush()) {
                sinkChannel.getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {

                    @Override
                    public void handleEvent(StreamSinkChannel channel) {
                        try {
                            if (channel.flush()) {
                                channel.suspendWrites();
                            }
                        } catch (IOException e) {
                            handleError(e);
                        }
                    }
                });
                sinkChannel.resumeWrites();
            }
        } catch (IOException e) {
            handleError(e);
        }
    }
}
Also used : Http2HeadersStreamSinkChannel(io.undertow.protocols.http2.Http2HeadersStreamSinkChannel) ChannelListener(org.xnio.ChannelListener) ChannelExceptionHandler(org.xnio.ChannelExceptionHandler) Http2HeadersStreamSinkChannel(io.undertow.protocols.http2.Http2HeadersStreamSinkChannel) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException)

Example 9 with ChannelListener

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

the class AsyncReceiverImpl method receiveFullString.

@Override
public void receiveFullString(final FullStringCallback callback, final ErrorCallback errorCallback, final Charset charset) {
    if (done) {
        throw UndertowMessages.MESSAGES.requestBodyAlreadyRead();
    }
    final ErrorCallback error = errorCallback == null ? END_EXCHANGE : errorCallback;
    if (callback == null) {
        throw UndertowMessages.MESSAGES.argumentCannotBeNull("callback");
    }
    if (exchange.isRequestComplete()) {
        callback.handle(exchange, "");
        return;
    }
    String contentLengthString = exchange.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    long contentLength;
    final ByteArrayOutputStream sb;
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
        if (contentLength > Integer.MAX_VALUE) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
        sb = new ByteArrayOutputStream((int) contentLength);
    } else {
        contentLength = -1;
        sb = new ByteArrayOutputStream();
    }
    if (maxBufferSize > 0) {
        if (contentLength > maxBufferSize) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
    }
    PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
    final ByteBuffer buffer = pooled.getBuffer();
    try {
        int res;
        do {
            try {
                buffer.clear();
                res = channel.read(buffer);
                if (res == -1) {
                    done = true;
                    callback.handle(exchange, sb.toString(charset.name()));
                    return;
                } else if (res == 0) {
                    channel.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {

                        @Override
                        public void handleEvent(StreamSourceChannel channel) {
                            if (done) {
                                return;
                            }
                            PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
                            final ByteBuffer buffer = pooled.getBuffer();
                            try {
                                int res;
                                do {
                                    try {
                                        buffer.clear();
                                        res = channel.read(buffer);
                                        if (res == -1) {
                                            done = true;
                                            Connectors.executeRootHandler(new HttpHandler() {

                                                @Override
                                                public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                    callback.handle(exchange, sb.toString(charset.name()));
                                                }
                                            }, exchange);
                                            return;
                                        } else if (res == 0) {
                                            return;
                                        } else {
                                            buffer.flip();
                                            while (buffer.hasRemaining()) {
                                                sb.write(buffer.get());
                                            }
                                            if (maxBufferSize > 0 && sb.size() > maxBufferSize) {
                                                Connectors.executeRootHandler(new HttpHandler() {

                                                    @Override
                                                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                        error.error(exchange, new RequestToLargeException());
                                                    }
                                                }, exchange);
                                                return;
                                            }
                                        }
                                    } catch (final IOException e) {
                                        Connectors.executeRootHandler(new HttpHandler() {

                                            @Override
                                            public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                error.error(exchange, e);
                                            }
                                        }, exchange);
                                        return;
                                    }
                                } while (true);
                            } finally {
                                pooled.close();
                            }
                        }
                    });
                    channel.resumeReads();
                    return;
                } else {
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        sb.write(buffer.get());
                    }
                    if (maxBufferSize > 0 && sb.size() > maxBufferSize) {
                        error.error(exchange, new RequestToLargeException());
                        return;
                    }
                }
            } catch (IOException e) {
                error.error(exchange, e);
                return;
            }
        } while (true);
    } finally {
        pooled.close();
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) HttpHandler(io.undertow.server.HttpHandler) ChannelListener(org.xnio.ChannelListener) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) PooledByteBuffer(io.undertow.connector.PooledByteBuffer)

Example 10 with ChannelListener

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

the class AsyncReceiverImpl method receiveFullBytes.

@Override
public void receiveFullBytes(final FullBytesCallback callback, final ErrorCallback errorCallback) {
    if (done) {
        throw UndertowMessages.MESSAGES.requestBodyAlreadyRead();
    }
    final ErrorCallback error = errorCallback == null ? END_EXCHANGE : errorCallback;
    if (callback == null) {
        throw UndertowMessages.MESSAGES.argumentCannotBeNull("callback");
    }
    if (exchange.isRequestComplete()) {
        callback.handle(exchange, EMPTY_BYTE_ARRAY);
        return;
    }
    String contentLengthString = exchange.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    long contentLength;
    final ByteArrayOutputStream sb;
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
        if (contentLength > Integer.MAX_VALUE) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
        sb = new ByteArrayOutputStream((int) contentLength);
    } else {
        contentLength = -1;
        sb = new ByteArrayOutputStream();
    }
    if (maxBufferSize > 0) {
        if (contentLength > maxBufferSize) {
            error.error(exchange, new RequestToLargeException());
            return;
        }
    }
    PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
    final ByteBuffer buffer = pooled.getBuffer();
    try {
        int res;
        do {
            try {
                buffer.clear();
                res = channel.read(buffer);
                if (res == -1) {
                    done = true;
                    callback.handle(exchange, sb.toByteArray());
                    return;
                } else if (res == 0) {
                    channel.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {

                        @Override
                        public void handleEvent(StreamSourceChannel channel) {
                            if (done) {
                                return;
                            }
                            PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
                            final ByteBuffer buffer = pooled.getBuffer();
                            try {
                                int res;
                                do {
                                    try {
                                        buffer.clear();
                                        res = channel.read(buffer);
                                        if (res == -1) {
                                            done = true;
                                            Connectors.executeRootHandler(new HttpHandler() {

                                                @Override
                                                public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                    callback.handle(exchange, sb.toByteArray());
                                                }
                                            }, exchange);
                                            return;
                                        } else if (res == 0) {
                                            return;
                                        } else {
                                            buffer.flip();
                                            while (buffer.hasRemaining()) {
                                                sb.write(buffer.get());
                                            }
                                            if (maxBufferSize > 0 && sb.size() > maxBufferSize) {
                                                Connectors.executeRootHandler(new HttpHandler() {

                                                    @Override
                                                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                        error.error(exchange, new RequestToLargeException());
                                                    }
                                                }, exchange);
                                                return;
                                            }
                                        }
                                    } catch (final Exception e) {
                                        Connectors.executeRootHandler(new HttpHandler() {

                                            @Override
                                            public void handleRequest(HttpServerExchange exchange) throws Exception {
                                                error.error(exchange, new IOException(e));
                                            }
                                        }, exchange);
                                        return;
                                    }
                                } while (true);
                            } finally {
                                pooled.close();
                            }
                        }
                    });
                    channel.resumeReads();
                    return;
                } else {
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        sb.write(buffer.get());
                    }
                    if (maxBufferSize > 0 && sb.size() > maxBufferSize) {
                        error.error(exchange, new RequestToLargeException());
                        return;
                    }
                }
            } catch (IOException e) {
                error.error(exchange, e);
                return;
            }
        } while (true);
    } finally {
        pooled.close();
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) HttpHandler(io.undertow.server.HttpHandler) ChannelListener(org.xnio.ChannelListener) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IOException(java.io.IOException) HttpServerExchange(io.undertow.server.HttpServerExchange) PooledByteBuffer(io.undertow.connector.PooledByteBuffer)

Aggregations

ChannelListener (org.xnio.ChannelListener)23 IOException (java.io.IOException)16 InetSocketAddress (java.net.InetSocketAddress)8 OptionMap (org.xnio.OptionMap)7 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)6 HttpOpenListener (io.undertow.server.protocol.http.HttpOpenListener)6 ByteBuffer (java.nio.ByteBuffer)6 StreamConnection (org.xnio.StreamConnection)6 StreamSinkChannel (org.xnio.channels.StreamSinkChannel)6 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)5 HttpHandler (io.undertow.server.HttpHandler)4 HttpServerExchange (io.undertow.server.HttpServerExchange)4 ChannelExceptionHandler (org.xnio.ChannelExceptionHandler)4 StreamSourceChannel (org.xnio.channels.StreamSourceChannel)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Channel (java.nio.channels.Channel)3 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)2 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)2 DeploymentManager (io.undertow.servlet.api.DeploymentManager)2 FilterInfo (io.undertow.servlet.api.FilterInfo)2