Search in sources :

Example 1 with HttpConnection

use of org.eclipse.jetty.server.HttpConnection 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 2 with HttpConnection

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

the class ConnectHandler method onConnectSuccess.

protected void onConnectSuccess(ConnectContext connectContext, UpstreamConnection upstreamConnection) {
    ConcurrentMap<String, Object> context = connectContext.getContext();
    HttpServletRequest request = connectContext.getRequest();
    prepareContext(request, context);
    HttpConnection httpConnection = connectContext.getHttpConnection();
    EndPoint downstreamEndPoint = httpConnection.getEndPoint();
    DownstreamConnection downstreamConnection = newDownstreamConnection(downstreamEndPoint, context);
    downstreamConnection.setInputBufferSize(getBufferSize());
    upstreamConnection.setConnection(downstreamConnection);
    downstreamConnection.setConnection(upstreamConnection);
    if (LOG.isDebugEnabled())
        LOG.debug("Connection setup completed: {}<->{}", downstreamConnection, upstreamConnection);
    HttpServletResponse response = connectContext.getResponse();
    sendConnectResponse(request, response, HttpServletResponse.SC_OK);
    upgradeConnection(request, response, downstreamConnection);
    connectContext.getAsyncContext().complete();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpConnection(org.eclipse.jetty.server.HttpConnection) HttpServletResponse(javax.servlet.http.HttpServletResponse) EndPoint(org.eclipse.jetty.io.EndPoint) SelectChannelEndPoint(org.eclipse.jetty.io.SelectChannelEndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint)

Example 3 with HttpConnection

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

the class SslBytesServerTest method init.

@Before
public void init() throws Exception {
    threadPool = Executors.newCachedThreadPool();
    server = new Server();
    File keyStore = MavenTestingUtils.getTestResourceFile("keystore.jks");
    sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keyStore.getAbsolutePath());
    sslContextFactory.setKeyStorePassword("storepwd");
    HttpConnectionFactory httpFactory = new HttpConnectionFactory() {

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

                @Override
                protected HttpParser newHttpParser(HttpCompliance compliance) {
                    return new HttpParser(newRequestHandler(), getHttpConfiguration().getRequestHeaderSize(), compliance) {

                        @Override
                        public boolean parseNext(ByteBuffer buffer) {
                            httpParses.incrementAndGet();
                            return super.parseNext(buffer);
                        }
                    };
                }

                @Override
                protected boolean onReadTimeout() {
                    final Runnable idleHook = SslBytesServerTest.this.idleHook;
                    if (idleHook != null)
                        idleHook.run();
                    return super.onReadTimeout();
                }
            }, connector, endPoint);
        }
    };
    httpFactory.getHttpConfiguration().addCustomizer(new SecureRequestCustomizer());
    SslConnectionFactory sslFactory = new SslConnectionFactory(sslContextFactory, httpFactory.getProtocol()) {

        @Override
        protected SslConnection newSslConnection(Connector connector, EndPoint endPoint, SSLEngine engine) {
            return new SslConnection(connector.getByteBufferPool(), connector.getExecutor(), endPoint, engine) {

                @Override
                protected DecryptedEndPoint newDecryptedEndPoint() {
                    return new DecryptedEndPoint() {

                        @Override
                        public int fill(ByteBuffer buffer) throws IOException {
                            sslFills.incrementAndGet();
                            return super.fill(buffer);
                        }

                        @Override
                        public boolean flush(ByteBuffer... appOuts) throws IOException {
                            sslFlushes.incrementAndGet();
                            return super.flush(appOuts);
                        }
                    };
                }
            };
        }
    };
    ServerConnector connector = new ServerConnector(server, null, null, null, 1, 1, sslFactory, httpFactory) {

        @Override
        protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException {
            ChannelEndPoint endp = super.newEndPoint(channel, selectSet, key);
            serverEndPoint.set(endp);
            return endp;
        }
    };
    connector.setIdleTimeout(idleTimeout);
    connector.setPort(0);
    server.addConnector(connector);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
            try {
                request.setHandled(true);
                String contentLength = request.getHeader("Content-Length");
                if (contentLength != null) {
                    int length = Integer.parseInt(contentLength);
                    ServletInputStream input = httpRequest.getInputStream();
                    ServletOutputStream output = httpResponse.getOutputStream();
                    byte[] buffer = new byte[32 * 1024];
                    while (length > 0) {
                        int read = input.read(buffer);
                        if (read < 0)
                            throw new EOFException();
                        length -= read;
                        if (target.startsWith("/echo"))
                            output.write(buffer, 0, read);
                    }
                }
            } catch (IOException x) {
                if (!(target.endsWith("suppress_exception")))
                    throw x;
            }
        }
    });
    server.start();
    serverPort = connector.getLocalPort();
    sslContext = sslContextFactory.getSslContext();
    proxy = new SimpleProxy(threadPool, "localhost", serverPort);
    proxy.start();
    logger.info("proxy:{} <==> server:{}", proxy.getPort(), serverPort);
}
Also used : ManagedSelector(org.eclipse.jetty.io.ManagedSelector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) SocketChannel(java.nio.channels.SocketChannel) Server(org.eclipse.jetty.server.Server) HttpConnection(org.eclipse.jetty.server.HttpConnection) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint) ServletOutputStream(javax.servlet.ServletOutputStream) SSLEngine(javax.net.ssl.SSLEngine) EndPoint(org.eclipse.jetty.io.EndPoint) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ServletInputStream(javax.servlet.ServletInputStream) EOFException(java.io.EOFException) HttpParser(org.eclipse.jetty.http.HttpParser) SelectionKey(java.nio.channels.SelectionKey) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpCompliance(org.eclipse.jetty.http.HttpCompliance) SslConnection(org.eclipse.jetty.io.ssl.SslConnection) File(java.io.File) Before(org.junit.Before)

Example 4 with HttpConnection

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

the class WebSocketServerFactory method acceptWebSocket.

@Override
public boolean acceptWebSocket(WebSocketCreator creator, HttpServletRequest request, HttpServletResponse response) throws IOException {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(contextClassloader);
        // Create Servlet Specific Upgrade Request/Response objects
        ServletUpgradeRequest sockreq = new ServletUpgradeRequest(request);
        ServletUpgradeResponse sockresp = new ServletUpgradeResponse(response);
        Object websocketPojo = creator.createWebSocket(sockreq, sockresp);
        // Handle response forbidden (and similar paths)
        if (sockresp.isCommitted()) {
            return false;
        }
        if (websocketPojo == null) {
            // no creation, sorry
            sockresp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Endpoint Creation Failed");
            return false;
        }
        // Allow Decorators to do their thing
        websocketPojo = getObjectFactory().decorate(websocketPojo);
        // Get the original HTTPConnection
        HttpConnection connection = (HttpConnection) request.getAttribute("org.eclipse.jetty.server.HttpConnection");
        // Send the upgrade
        EventDriver driver = eventDriverFactory.wrap(websocketPojo);
        return upgrade(connection, sockreq, sockresp, driver);
    } catch (URISyntaxException e) {
        throw new IOException("Unable to accept websocket due to mangled URI", e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : EventDriver(org.eclipse.jetty.websocket.common.events.EventDriver) HttpConnection(org.eclipse.jetty.server.HttpConnection) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) ServletUpgradeRequest(org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest) ServletUpgradeResponse(org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse)

Example 5 with HttpConnection

use of org.eclipse.jetty.server.HttpConnection in project vespa by vespa-engine.

the class ServletFilterRequestTest method newServletRequest.

private ServletRequest newServletRequest() throws Exception {
    MockHttpServletRequest parent = new MockHttpServletRequest("GET", uri.toString());
    parent.setProtocol(Version.HTTP_1_1.toString());
    parent.setRemoteHost(host);
    parent.setRemotePort(port);
    parent.setParameter(paramName, paramValue);
    parent.setParameter(listParamName, listParamValue);
    parent.addHeader(headerName, headerValue);
    parent.setAttribute(attributeName, attributeValue);
    HttpConnection connection = Mockito.mock(HttpConnection.class);
    when(connection.getCreatedTimeStamp()).thenReturn(System.currentTimeMillis());
    parent.setAttribute("org.eclipse.jetty.server.HttpConnection", connection);
    return new ServletRequest(parent, uri);
}
Also used : ServletRequest(com.yahoo.jdisc.http.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpConnection(org.eclipse.jetty.server.HttpConnection) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest)

Aggregations

HttpConnection (org.eclipse.jetty.server.HttpConnection)9 EndPoint (org.eclipse.jetty.io.EndPoint)5 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)2 SocketChannel (java.nio.channels.SocketChannel)2 ServletException (javax.servlet.ServletException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 SelectChannelEndPoint (org.eclipse.jetty.io.SelectChannelEndPoint)2 SocketChannelEndPoint (org.eclipse.jetty.io.SocketChannelEndPoint)2 Connector (org.eclipse.jetty.server.Connector)2 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)2 ServerConnector (org.eclipse.jetty.server.ServerConnector)2 ServletRequest (com.yahoo.jdisc.http.servlet.ServletRequest)1 BufferedReader (java.io.BufferedReader)1 EOFException (java.io.EOFException)1 File (java.io.File)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1