Search in sources :

Example 1 with Connector

use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.

the class JettyHttpServer method cleanUpConnectors.

private void cleanUpConnectors() {
    for (Map.Entry<String, Connector> stringConnectorEntry : _connectors.entrySet()) {
        Connector connector = stringConnectorEntry.getValue();
        try {
            connector.stop();
        } catch (Exception ex) {
            LOG.warn(ex);
        }
        _server.removeConnector(connector);
    }
    _connectors.clear();
}
Also used : NetworkConnector(org.eclipse.jetty.server.NetworkConnector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) HashMap(java.util.HashMap) Map(java.util.Map) IOException(java.io.IOException)

Example 2 with Connector

use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.

the class HTTP2CServerTest method testHTTP_2_0_DirectWithoutH2C.

@Test
public void testHTTP_2_0_DirectWithoutH2C() throws Exception {
    AtomicLong fills = new AtomicLong();
    // Remove "h2c", leaving only "http/1.1".
    connector.clearConnectionFactories();
    HttpConnectionFactory connectionFactory = new HttpConnectionFactory() {

        @Override
        public Connection newConnection(Connector connector, EndPoint endPoint) {
            HttpConnection connection = new HttpConnection(getHttpConfiguration(), connector, endPoint, getHttpCompliance(), isRecordHttpComplianceViolations()) {

                @Override
                public void onFillable() {
                    fills.incrementAndGet();
                    super.onFillable();
                }
            };
            return configure(connection, connector, endPoint);
        }
    };
    connector.addConnectionFactory(connectionFactory);
    connector.setDefaultProtocol(connectionFactory.getProtocol());
    // Now send a HTTP/2 direct request, which
    // will have the PRI * HTTP/2.0 preface.
    byteBufferPool = new MappedByteBufferPool();
    generator = new Generator(byteBufferPool);
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
        // We sent a HTTP/2 preface, but the server has no "h2c" connection
        // factory so it does not know how to handle this request.
        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        String responseLine = reader.readLine();
        Assert.assertThat(responseLine, Matchers.containsString(" 426 "));
        while (true) {
            if (reader.read() < 0)
                break;
        }
    }
    // Make sure we did not spin.
    Thread.sleep(1000);
    Assert.assertThat(fills.get(), Matchers.lessThan(5L));
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) InputStreamReader(java.io.InputStreamReader) HttpConnection(org.eclipse.jetty.server.HttpConnection) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) EndPoint(org.eclipse.jetty.io.EndPoint) Matchers.containsString(org.hamcrest.Matchers.containsString) ByteBuffer(java.nio.ByteBuffer) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) AtomicLong(java.util.concurrent.atomic.AtomicLong) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 3 with Connector

use of org.eclipse.jetty.server.Connector 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)

Example 4 with Connector

use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.

the class StatisticsServlet method sendTextResponse.

private void sendTextResponse(HttpServletResponse response) throws IOException {
    StringBuilder sb = new StringBuilder();
    sb.append(_statsHandler.toStatsHTML());
    sb.append("<h2>Connections:</h2>\n");
    for (Connector connector : _connectors) {
        sb.append("<h3>").append(connector.getClass().getName()).append("@").append(connector.hashCode()).append("</h3>");
        sb.append("Protocols:");
        for (String protocol : connector.getProtocols()) sb.append(protocol).append("&nbsp;");
        sb.append("    <br />\n");
        ConnectionStatistics connectionStats = null;
        if (connector instanceof Container)
            connectionStats = ((Container) connector).getBean(ConnectionStatistics.class);
        if (connectionStats != null) {
            sb.append("Total connections: ").append(connectionStats.getConnectionsTotal()).append("<br />\n");
            sb.append("Current connections open: ").append(connectionStats.getConnections()).append("<br />\n");
            sb.append("Max concurrent connections open: ").append(connectionStats.getConnectionsMax()).append("<br />\n");
            sb.append("Mean connection duration: ").append(connectionStats.getConnectionDurationMean()).append("<br />\n");
            sb.append("Max connection duration: ").append(connectionStats.getConnectionDurationMax()).append("<br />\n");
            sb.append("Connection duration standard deviation: ").append(connectionStats.getConnectionDurationStdDev()).append("<br />\n");
            sb.append("Total bytes received: ").append(connectionStats.getReceivedBytes()).append("<br />\n");
            sb.append("Total bytes sent: ").append(connectionStats.getSentBytes()).append("<br />\n");
            sb.append("Total messages received: ").append(connectionStats.getReceivedMessages()).append("<br />\n");
            sb.append("Total messages sent: ").append(connectionStats.getSentMessages()).append("<br />\n");
        } else {
            ConnectorStatistics connectorStats = null;
            if (connector instanceof AbstractConnector)
                connectorStats = ((AbstractConnector) connector).getBean(ConnectorStatistics.class);
            if (connectorStats != null) {
                sb.append("Statistics gathering started ").append(connectorStats.getStartedMillis()).append("ms ago").append("<br />\n");
                sb.append("Total connections: ").append(connectorStats.getConnections()).append("<br />\n");
                sb.append("Current connections open: ").append(connectorStats.getConnectionsOpen()).append("<br />\n");
                sb.append("Max concurrent connections open: ").append(connectorStats.getConnectionsOpenMax()).append("<br />\n");
                sb.append("Mean connection duration: ").append(connectorStats.getConnectionDurationMean()).append("<br />\n");
                sb.append("Max connection duration: ").append(connectorStats.getConnectionDurationMax()).append("<br />\n");
                sb.append("Connection duration standard deviation: ").append(connectorStats.getConnectionDurationStdDev()).append("<br />\n");
                sb.append("Total messages in: ").append(connectorStats.getMessagesIn()).append("<br />\n");
                sb.append("Total messages out: ").append(connectorStats.getMessagesOut()).append("<br />\n");
            } else {
                sb.append("Statistics gathering off.\n");
            }
        }
    }
    sb.append("<h2>Memory:</h2>\n");
    sb.append("Heap memory usage: ").append(_memoryBean.getHeapMemoryUsage().getUsed()).append(" bytes").append("<br />\n");
    sb.append("Non-heap memory usage: ").append(_memoryBean.getNonHeapMemoryUsage().getUsed()).append(" bytes").append("<br />\n");
    response.setContentType("text/html");
    PrintWriter pout = response.getWriter();
    pout.write(sb.toString());
}
Also used : AbstractConnector(org.eclipse.jetty.server.AbstractConnector) Connector(org.eclipse.jetty.server.Connector) Container(org.eclipse.jetty.util.component.Container) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) ConnectorStatistics(org.eclipse.jetty.server.ConnectorStatistics) AbstractConnector(org.eclipse.jetty.server.AbstractConnector) PrintWriter(java.io.PrintWriter)

Example 5 with Connector

use of org.eclipse.jetty.server.Connector in project jetty.project by eclipse.

the class PrefaceTest method testOnPrefaceNotifiedForStandardUpgrade.

@Test
public void testOnPrefaceNotifiedForStandardUpgrade() throws Exception {
    Integer maxConcurrentStreams = 128;
    AtomicReference<CountDownLatch> serverPrefaceLatch = new AtomicReference<>(new CountDownLatch(1));
    AtomicReference<CountDownLatch> serverSettingsLatch = new AtomicReference<>(new CountDownLatch(1));
    HttpConfiguration config = new HttpConfiguration();
    prepareServer(new HttpConnectionFactory(config), new HTTP2CServerConnectionFactory(config) {

        @Override
        protected ServerSessionListener newSessionListener(Connector connector, EndPoint endPoint) {
            return new ServerSessionListener.Adapter() {

                @Override
                public Map<Integer, Integer> onPreface(Session session) {
                    Map<Integer, Integer> serverSettings = new HashMap<>();
                    serverSettings.put(SettingsFrame.MAX_CONCURRENT_STREAMS, maxConcurrentStreams);
                    serverPrefaceLatch.get().countDown();
                    return serverSettings;
                }

                @Override
                public void onSettings(Session session, SettingsFrame frame) {
                    serverSettingsLatch.get().countDown();
                }

                @Override
                public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
                    MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                    stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
                    return null;
                }
            };
        }
    });
    server.start();
    ByteBufferPool byteBufferPool = new MappedByteBufferPool();
    try (SocketChannel socket = SocketChannel.open()) {
        socket.connect(new InetSocketAddress("localhost", connector.getLocalPort()));
        String upgradeRequest = "" + "GET /one HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: \r\n" + "\r\n";
        ByteBuffer upgradeBuffer = ByteBuffer.wrap(upgradeRequest.getBytes(StandardCharsets.ISO_8859_1));
        socket.write(upgradeBuffer);
        // Make sure onPreface() is called on server.
        Assert.assertTrue(serverPrefaceLatch.get().await(5, TimeUnit.SECONDS));
        Assert.assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS));
        // The 101 response is the reply to the client preface SETTINGS frame.
        ByteBuffer buffer = byteBufferPool.acquire(1024, true);
        http1: while (true) {
            BufferUtil.clearToFill(buffer);
            int read = socket.read(buffer);
            BufferUtil.flipToFlush(buffer, 0);
            if (read < 0)
                Assert.fail();
            int crlfs = 0;
            while (buffer.hasRemaining()) {
                byte b = buffer.get();
                if (b == '\r' || b == '\n')
                    ++crlfs;
                else
                    crlfs = 0;
                if (crlfs == 4)
                    break http1;
            }
        }
        // Reset the latches on server.
        serverPrefaceLatch.set(new CountDownLatch(1));
        serverSettingsLatch.set(new CountDownLatch(1));
        // After the 101, the client must send the connection preface.
        Generator generator = new Generator(byteBufferPool);
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        generator.control(lease, new PrefaceFrame());
        Map<Integer, Integer> clientSettings = new HashMap<>();
        clientSettings.put(SettingsFrame.ENABLE_PUSH, 1);
        generator.control(lease, new SettingsFrame(clientSettings, false));
        List<ByteBuffer> buffers = lease.getByteBuffers();
        socket.write(buffers.toArray(new ByteBuffer[buffers.size()]));
        // However, we should not call onPreface() again.
        Assert.assertFalse(serverPrefaceLatch.get().await(1, TimeUnit.SECONDS));
        // Although we should notify of the SETTINGS frame.
        Assert.assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS));
        CountDownLatch clientSettingsLatch = new CountDownLatch(1);
        AtomicBoolean responded = new AtomicBoolean();
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onSettings(SettingsFrame frame) {
                if (frame.isReply())
                    return;
                Assert.assertEquals(maxConcurrentStreams, frame.getSettings().get(SettingsFrame.MAX_CONCURRENT_STREAMS));
                clientSettingsLatch.countDown();
            }

            @Override
            public void onHeaders(HeadersFrame frame) {
                if (frame.isEndStream())
                    responded.set(true);
            }
        }, 4096, 8192);
        // HTTP/2 parsing.
        while (true) {
            parser.parse(buffer);
            if (responded.get())
                break;
            BufferUtil.clearToFill(buffer);
            int read = socket.read(buffer);
            BufferUtil.flipToFlush(buffer, 0);
            if (read < 0)
                Assert.fail();
        }
        Assert.assertTrue(clientSettingsLatch.await(5, TimeUnit.SECONDS));
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) Connector(org.eclipse.jetty.server.Connector) SocketChannel(java.nio.channels.SocketChannel) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) EndPoint(org.eclipse.jetty.io.EndPoint) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) HTTP2CServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) Parser(org.eclipse.jetty.http2.parser.Parser) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Map(java.util.Map) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Aggregations

Connector (org.eclipse.jetty.server.Connector)123 Server (org.eclipse.jetty.server.Server)64 ServerConnector (org.eclipse.jetty.server.ServerConnector)49 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)30 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)25 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)21 IOException (java.io.IOException)20 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)20 ArrayList (java.util.ArrayList)18 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)15 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)14 Test (org.testng.annotations.Test)14 SelectChannelConnector (org.eclipse.jetty.server.nio.SelectChannelConnector)13 SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)11 File (java.io.File)10 Handler (org.eclipse.jetty.server.Handler)10 NetworkConnector (org.eclipse.jetty.server.NetworkConnector)10 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)10 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)10 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)9