Search in sources :

Example 6 with Connection

use of org.eclipse.jetty.io.Connection in project jetty.project by eclipse.

the class HalfCloseTest method testCompleteClose.

@Test
public void testCompleteClose() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, 1, 1);
    connector.setPort(0);
    connector.setIdleTimeout(5000);
    final AtomicInteger opened = new AtomicInteger(0);
    final CountDownLatch closed = new CountDownLatch(1);
    connector.addBean(new Connection.Listener() {

        @Override
        public void onOpened(Connection connection) {
            opened.incrementAndGet();
        }

        @Override
        public void onClosed(Connection connection) {
            closed.countDown();
        }
    });
    server.addConnector(connector);
    TestHandler handler = new TestHandler();
    server.setHandler(handler);
    server.start();
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        client.getOutputStream().write("GET / HTTP/1.0\r\n\r\n".getBytes());
        IO.toString(client.getInputStream());
        assertEquals(1, handler.getHandled());
        assertEquals(1, opened.get());
    }
    assertEquals(true, closed.await(1, TimeUnit.SECONDS));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Connection(org.eclipse.jetty.io.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) Test(org.junit.Test)

Example 7 with Connection

use of org.eclipse.jetty.io.Connection in project jetty.project by eclipse.

the class HalfCloseTest method testAsyncClose.

@Test
public void testAsyncClose() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, 1, 1);
    connector.setPort(0);
    connector.setIdleTimeout(5000);
    final AtomicInteger opened = new AtomicInteger(0);
    final CountDownLatch closed = new CountDownLatch(1);
    connector.addBean(new Connection.Listener() {

        @Override
        public void onOpened(Connection connection) {
            opened.incrementAndGet();
        }

        @Override
        public void onClosed(Connection connection) {
            closed.countDown();
        }
    });
    server.addConnector(connector);
    AsyncHandler handler = new AsyncHandler();
    server.setHandler(handler);
    server.start();
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        client.getOutputStream().write("GET / HTTP/1.0\r\n\r\n".getBytes());
        IO.toString(client.getInputStream());
        assertEquals(1, handler.getHandled());
        assertEquals(1, opened.get());
    }
    assertEquals(true, closed.await(1, TimeUnit.SECONDS));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Connection(org.eclipse.jetty.io.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) Test(org.junit.Test)

Example 8 with Connection

use of org.eclipse.jetty.io.Connection in project jetty.project by eclipse.

the class AsyncIOServletTest method testAsyncReadEarlyEOF.

@Test
public void testAsyncReadEarlyEOF() throws Exception {
    // SSLEngine receives the close alert from the client, and when
    // the server passes the response to encrypt and write, SSLEngine
    // only generates the close alert back, without encrypting the
    // response, so we need to skip the transports over TLS.
    Assume.assumeThat(transport, Matchers.not(Matchers.isOneOf(Transport.HTTPS, Transport.H2)));
    String content = "jetty";
    int responseCode = HttpStatus.NO_CONTENT_204;
    CountDownLatch readLatch = new CountDownLatch(content.length());
    CountDownLatch errorLatch = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = request.startAsync();
            ServletInputStream input = request.getInputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    while (input.isReady() && !input.isFinished()) {
                        int read = input.read();
                        // System.err.printf("%x%n", read);
                        readLatch.countDown();
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                }

                @Override
                public void onError(Throwable x) {
                    response.setStatus(responseCode);
                    asyncContext.complete();
                    errorLatch.countDown();
                }
            });
        }
    });
    CountDownLatch responseLatch = new CountDownLatch(1);
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    contentProvider.offer(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
    org.eclipse.jetty.client.api.Request request = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(contentProvider).onResponseSuccess(response -> responseLatch.countDown());
    Destination destination = client.getDestination(getScheme(), "localhost", connector.getLocalPort());
    FuturePromise<org.eclipse.jetty.client.api.Connection> promise = new FuturePromise<>();
    destination.newConnection(promise);
    org.eclipse.jetty.client.api.Connection connection = promise.get(5, TimeUnit.SECONDS);
    CountDownLatch clientLatch = new CountDownLatch(1);
    connection.send(request, result -> {
        assertThat(result.getResponse().getStatus(), Matchers.equalTo(responseCode));
        clientLatch.countDown();
    });
    assertTrue(readLatch.await(5, TimeUnit.SECONDS));
    switch(transport) {
        case HTTP:
        case HTTPS:
            ((HttpConnectionOverHTTP) connection).getEndPoint().shutdownOutput();
            break;
        case H2C:
        case H2:
            // In case of HTTP/2, we not only send the request, but also the preface and
            // SETTINGS frames. SETTINGS frame need to be replied, so we want to wait to
            // write the reply before shutting output down, so that the test does not fail.
            Thread.sleep(1000);
            Session session = ((HttpConnectionOverHTTP2) connection).getSession();
            ((HTTP2Session) session).getEndPoint().shutdownOutput();
            break;
        default:
            Assert.fail();
    }
    // Wait for the response to arrive before finishing the request.
    assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
    contentProvider.close();
    assertTrue(errorLatch.await(5, TimeUnit.SECONDS));
    assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : Destination(org.eclipse.jetty.client.api.Destination) AsyncContext(javax.servlet.AsyncContext) HttpConnectionOverHTTP2(org.eclipse.jetty.http2.client.http.HttpConnectionOverHTTP2) Matchers.containsString(org.hamcrest.Matchers.containsString) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) Connection(org.eclipse.jetty.io.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 9 with Connection

use of org.eclipse.jetty.io.Connection in project jetty.project by eclipse.

the class ConnectorStatistics method update.

private synchronized void update() {
    long now = System.nanoTime();
    long then = _nanoStamp.get();
    long duration = now - then;
    if (duration > SECOND_NANOS / 2) {
        if (_nanoStamp.compareAndSet(then, now)) {
            long msgsIn = _closedIn.sumThenReset();
            long msgsOut = _closedOut.sumThenReset();
            for (Map.Entry<Connection, Sample> entry : _samples.entrySet()) {
                Connection connection = entry.getKey();
                Sample sample = entry.getValue();
                Sample next = new Sample(connection);
                if (_samples.replace(connection, sample, next)) {
                    msgsIn += next._messagesIn - sample._messagesIn;
                    msgsOut += next._messagesOut - sample._messagesOut;
                }
            }
            _messagesInPerSecond = (int) (msgsIn * SECOND_NANOS / duration);
            _messagesOutPerSecond = (int) (msgsOut * SECOND_NANOS / duration);
        }
    }
}
Also used : Connection(org.eclipse.jetty.io.Connection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Example 10 with Connection

use of org.eclipse.jetty.io.Connection in project jetty.project by eclipse.

the class ForwardProxyServerTest method testRequestTarget.

@Test
public void testRequestTarget() throws Exception {
    startServer(new AbstractConnectionFactory("http/1.1") {

        @Override
        public Connection newConnection(Connector connector, EndPoint endPoint) {
            return new AbstractConnection(endPoint, connector.getExecutor()) {

                @Override
                public void onOpen() {
                    super.onOpen();
                    fillInterested();
                }

                @Override
                public void onFillable() {
                    try {
                        // When using TLS, multiple reads are required.
                        ByteBuffer buffer = BufferUtil.allocate(1024);
                        int filled = 0;
                        while (filled == 0) filled = getEndPoint().fill(buffer);
                        Utf8StringBuilder builder = new Utf8StringBuilder();
                        builder.append(buffer);
                        String request = builder.toString();
                        // ProxyServlet will receive an absolute URI from
                        // the client, and convert it to a relative URI.
                        // The ConnectHandler won't modify what the client
                        // sent, which must be a relative URI.
                        Assert.assertThat(request.length(), Matchers.greaterThan(0));
                        if (serverSslContextFactory == null)
                            Assert.assertFalse(request.contains("http://"));
                        else
                            Assert.assertFalse(request.contains("https://"));
                        String response = "" + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "\r\n";
                        getEndPoint().write(Callback.NOOP, ByteBuffer.wrap(response.getBytes(StandardCharsets.UTF_8)));
                    } catch (Throwable x) {
                        x.printStackTrace();
                        close();
                    }
                }
            };
        }
    });
    startProxy();
    HttpClient httpClient = new HttpClient(newSslContextFactory());
    httpClient.getProxyConfiguration().getProxies().add(newHttpProxy());
    httpClient.start();
    try {
        ContentResponse response = httpClient.newRequest("localhost", serverConnector.getLocalPort()).scheme(serverSslContextFactory == null ? "http" : "https").method(HttpMethod.GET).path("/test").send();
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    } finally {
        httpClient.stop();
    }
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) AbstractConnectionFactory(org.eclipse.jetty.server.AbstractConnectionFactory) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) AbstractConnection(org.eclipse.jetty.io.AbstractConnection) Utf8StringBuilder(org.eclipse.jetty.util.Utf8StringBuilder) HttpClient(org.eclipse.jetty.client.HttpClient) AbstractConnection(org.eclipse.jetty.io.AbstractConnection) Connection(org.eclipse.jetty.io.Connection) EndPoint(org.eclipse.jetty.io.EndPoint) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Aggregations

Connection (org.eclipse.jetty.io.Connection)18 Test (org.junit.Test)9 CountDownLatch (java.util.concurrent.CountDownLatch)8 IOException (java.io.IOException)7 Socket (java.net.Socket)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 ServletException (javax.servlet.ServletException)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 AbstractConnection (org.eclipse.jetty.io.AbstractConnection)4 EndPoint (org.eclipse.jetty.io.EndPoint)3 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)3 Slow (org.eclipse.jetty.toolchain.test.annotation.Slow)3 Timer (com.codahale.metrics.Timer)2 InputStream (java.io.InputStream)2 InterruptedIOException (java.io.InterruptedIOException)2 OutputStream (java.io.OutputStream)2 UncheckedIOException (java.io.UncheckedIOException)2 AsyncContext (javax.servlet.AsyncContext)2 ReadListener (javax.servlet.ReadListener)2