Search in sources :

Example 26 with Channel

use of java.nio.channels.Channel in project undertow by undertow-io.

the class Http2Channel method sendGoAway.

public void sendGoAway(int status, final ChannelExceptionHandler<AbstractHttp2StreamSinkChannel> exceptionHandler) {
    if (thisGoneAway) {
        return;
    }
    thisGoneAway = true;
    if (UndertowLogger.REQUEST_IO_LOGGER.isTraceEnabled()) {
        UndertowLogger.REQUEST_IO_LOGGER.tracef(new ClosedChannelException(), "Sending goaway on channel %s", this);
    }
    Http2GoAwayStreamSinkChannel goAway = new Http2GoAwayStreamSinkChannel(this, status, getLastGoodStreamId());
    try {
        goAway.shutdownWrites();
        if (!goAway.flush()) {
            goAway.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<Channel>() {

                @Override
                public void handleEvent(Channel channel) {
                    IoUtils.safeClose(Http2Channel.this);
                }
            }, exceptionHandler));
            goAway.resumeWrites();
        } else {
            IoUtils.safeClose(this);
        }
    } catch (IOException e) {
        exceptionHandler.handleException(goAway, e);
    } catch (Throwable t) {
        exceptionHandler.handleException(goAway, new IOException(t));
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelListener(org.xnio.ChannelListener) AbstractFramedStreamSourceChannel(io.undertow.server.protocol.framed.AbstractFramedStreamSourceChannel) AbstractFramedChannel(io.undertow.server.protocol.framed.AbstractFramedChannel) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) Channel(java.nio.channels.Channel) IOException(java.io.IOException)

Example 27 with Channel

use of java.nio.channels.Channel in project undertow by undertow-io.

the class PipeliningBufferingStreamSinkConduit method performFlush.

void performFlush(final HttpServerExchange exchange, final HttpServerConnection connection) {
    try {
        final HttpServerConnection.ConduitState oldState = connection.resetChannel();
        if (!flushPipelinedData()) {
            final StreamConnection channel = connection.getChannel();
            channel.getSinkChannel().setWriteListener(new ChannelListener<Channel>() {

                @Override
                public void handleEvent(Channel c) {
                    try {
                        if (flushPipelinedData()) {
                            channel.getSinkChannel().setWriteListener(null);
                            channel.getSinkChannel().suspendWrites();
                            connection.restoreChannel(oldState);
                            connection.getReadListener().exchangeComplete(exchange);
                        }
                    } catch (IOException e) {
                        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                        IoUtils.safeClose(channel);
                    } catch (Throwable t) {
                        UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
                        IoUtils.safeClose(channel);
                    }
                }
            });
            connection.getChannel().getSinkChannel().resumeWrites();
            return;
        } else {
            connection.restoreChannel(oldState);
            connection.getReadListener().exchangeComplete(exchange);
        }
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
        IoUtils.safeClose(connection.getChannel());
    } catch (Throwable t) {
        UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
        IoUtils.safeClose(connection.getChannel());
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) ConduitWritableByteChannel(org.xnio.conduits.ConduitWritableByteChannel) FileChannel(java.nio.channels.FileChannel) Channel(java.nio.channels.Channel) IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection)

Example 28 with Channel

use of java.nio.channels.Channel in project undertow by undertow-io.

the class HttpContinue method internalSendContinueResponse.

private static void internalSendContinueResponse(final HttpServerExchange exchange, final IoCallback callback) {
    if (exchange.getAttachment(ALREADY_SENT) != null) {
        callback.onComplete(exchange, null);
        return;
    }
    HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange);
    exchange.putAttachment(ALREADY_SENT, true);
    newExchange.setStatusCode(StatusCodes.CONTINUE);
    newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
    final StreamSinkChannel responseChannel = newExchange.getResponseChannel();
    try {
        responseChannel.shutdownWrites();
        if (!responseChannel.flush()) {
            responseChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {

                @Override
                public void handleEvent(StreamSinkChannel channel) {
                    channel.suspendWrites();
                    exchange.dispatch(new HttpHandler() {

                        @Override
                        public void handleRequest(HttpServerExchange exchange) throws Exception {
                            callback.onComplete(exchange, null);
                        }
                    });
                }
            }, new ChannelExceptionHandler<Channel>() {

                @Override
                public void handleException(Channel channel, final IOException e) {
                    exchange.dispatch(new HttpHandler() {

                        @Override
                        public void handleRequest(HttpServerExchange exchange) throws Exception {
                            callback.onException(exchange, null, e);
                        }
                    });
                }
            }));
            responseChannel.resumeWrites();
            exchange.dispatch();
        } else {
            callback.onComplete(exchange, null);
        }
    } catch (IOException e) {
        callback.onException(exchange, null, e);
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) ChannelListener(org.xnio.ChannelListener) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) Channel(java.nio.channels.Channel) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) ChannelExceptionHandler(org.xnio.ChannelExceptionHandler) IOException(java.io.IOException) IOException(java.io.IOException)

Example 29 with Channel

use of java.nio.channels.Channel in project undertow by undertow-io.

the class ReadTimeoutTestCase method testReadTimeout.

@Test
public void testReadTimeout() throws InterruptedException, IOException {
    final CountDownLatch errorLatch = new CountDownLatch(1);
    DefaultServer.setRootHandler((final HttpServerExchange exchange) -> {
        final StreamSinkChannel response = exchange.getResponseChannel();
        final StreamSourceChannel request = exchange.getRequestChannel();
        request.getReadSetter().set(ChannelListeners.drainListener(Long.MAX_VALUE, (final Channel channel) -> {
            new StringWriteChannelListener("COMPLETED") {

                @Override
                protected void writeDone(final StreamSinkChannel channel) {
                    exchange.endExchange();
                }
            }.setup(response);
        }, (final StreamSourceChannel channel, final IOException e) -> {
            e.printStackTrace();
            exchange.endExchange();
            exception = e;
            errorLatch.countDown();
        }));
        request.wakeupReads();
    });
    final TestHttpClient client = new TestHttpClient();
    try {
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL());
        post.setEntity(new AbstractHttpEntity() {

            @Override
            public InputStream getContent() throws IllegalStateException {
                return null;
            }

            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                for (int i = 0; i < 5; ++i) {
                    outstream.write('*');
                    outstream.flush();
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            @Override
            public boolean isStreaming() {
                return true;
            }

            @Override
            public boolean isRepeatable() {
                return false;
            }

            @Override
            public long getContentLength() {
                return 5;
            }
        });
        post.addHeader(Headers.CONNECTION_STRING, "close");
        boolean socketFailure = false;
        try {
            client.execute(post);
        } catch (SocketException e) {
            Assert.assertTrue(e.getMessage(), e.getMessage().contains("Broken pipe") || e.getMessage().contains("connection abort"));
            socketFailure = true;
        }
        Assert.assertTrue("Test sent request without any exception", socketFailure);
        if (errorLatch.await(5, TimeUnit.SECONDS)) {
            Assert.assertTrue(getExceptionDescription(exception), exception instanceof ReadTimeoutException || (DefaultServer.isProxy() && exception instanceof IOException));
            if (exception.getSuppressed() != null && exception.getSuppressed().length > 0) {
                for (Throwable supressed : exception.getSuppressed()) {
                    Assert.assertEquals(getExceptionDescription(supressed), ReadTimeoutException.class, exception.getClass());
                }
            }
        } else if (!DefaultServer.isProxy()) {
            // ignore if proxy, because when we're on proxy, we might not be able to see the exception
            Assert.fail("Did not get ReadTimeoutException");
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : StreamSourceChannel(org.xnio.channels.StreamSourceChannel) HttpPost(org.apache.http.client.methods.HttpPost) SocketException(java.net.SocketException) InputStream(java.io.InputStream) ReadTimeoutException(org.xnio.channels.ReadTimeoutException) StreamSourceChannel(org.xnio.channels.StreamSourceChannel) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) Channel(java.nio.channels.Channel) OutputStream(java.io.OutputStream) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) TestHttpClient(io.undertow.testutils.TestHttpClient) StringWriteChannelListener(io.undertow.util.StringWriteChannelListener) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) Test(org.junit.Test)

Example 30 with Channel

use of java.nio.channels.Channel in project undertow by undertow-io.

the class WriteTimeoutTestCase method testWriteTimeout.

@Test
public void testWriteTimeout() throws IOException, InterruptedException {
    DefaultServer.setRootHandler(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final StreamSinkChannel response = exchange.getResponseChannel();
            try {
                response.setOption(Options.WRITE_TIMEOUT, 10);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 1mb
            final int capacity = 1 * 1024 * 1024;
            final ByteBuffer originalBuffer = ByteBuffer.allocateDirect(capacity);
            for (int i = 0; i < capacity; ++i) {
                originalBuffer.put((byte) '*');
            }
            originalBuffer.flip();
            response.getWriteSetter().set(new ChannelListener<Channel>() {

                private ByteBuffer buffer = originalBuffer.duplicate();

                int count = 0;

                @Override
                public void handleEvent(final Channel channel) {
                    do {
                        try {
                            int res = response.write(buffer);
                            if (res == 0) {
                                return;
                            }
                        } catch (IOException e) {
                            exception = e;
                            errorLatch.countDown();
                        }
                        if (!buffer.hasRemaining()) {
                            count++;
                            buffer = originalBuffer.duplicate();
                        }
                    } while (count < 1000);
                    exchange.endExchange();
                }
            });
            response.wakeupWrites();
        }
    });
    final TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
        try {
            HttpResponse result = client.execute(get);
            InputStream content = result.getEntity().getContent();
            byte[] buffer = new byte[512];
            int r = 0;
            while ((r = content.read(buffer)) > 0) {
                Thread.sleep(200);
                if (exception != null) {
                    Assert.assertEquals(WriteTimeoutException.class, exception.getClass());
                    return;
                }
            }
            Assert.fail("Write did not time out");
        } catch (IOException e) {
            if (errorLatch.await(5, TimeUnit.SECONDS)) {
                Assert.assertEquals(WriteTimeoutException.class, exception.getClass());
            } else {
                Assert.fail("Write did not time out");
            }
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : ChannelListener(org.xnio.ChannelListener) InputStream(java.io.InputStream) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) Channel(java.nio.channels.Channel) HttpGet(org.apache.http.client.methods.HttpGet) StreamSinkChannel(org.xnio.channels.StreamSinkChannel) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) WriteTimeoutException(org.xnio.channels.WriteTimeoutException) IOException(java.io.IOException) TestHttpClient(io.undertow.testutils.TestHttpClient) WriteTimeoutException(org.xnio.channels.WriteTimeoutException) Test(org.junit.Test)

Aggregations

Channel (java.nio.channels.Channel)33 IOException (java.io.IOException)22 FileChannel (java.nio.channels.FileChannel)10 ReadableByteChannel (java.nio.channels.ReadableByteChannel)8 SocketChannel (java.nio.channels.SocketChannel)7 WritableByteChannel (java.nio.channels.WritableByteChannel)7 InputStream (java.io.InputStream)6 ServerSocketChannel (java.nio.channels.ServerSocketChannel)5 FileNotFoundException (java.io.FileNotFoundException)4 InetSocketAddress (java.net.InetSocketAddress)4 ArrayList (java.util.ArrayList)4 IgniteRunnable (org.apache.ignite.lang.IgniteRunnable)4 StreamSinkChannel (org.xnio.channels.StreamSinkChannel)4 DataFile (edu.harvard.iq.dataverse.DataFile)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 List (java.util.List)3 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3