Search in sources :

Example 26 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class HttpClientTest method testResponseListenerForMultipleEventsIsInvokedOncePerEvent.

@Test
public void testResponseListenerForMultipleEventsIsInvokedOncePerEvent() throws Exception {
    start(new EmptyServerHandler());
    final AtomicInteger counter = new AtomicInteger();
    final CountDownLatch latch = new CountDownLatch(1);
    Response.Listener listener = new Response.Listener() {

        @Override
        public void onBegin(Response response) {
            counter.incrementAndGet();
        }

        @Override
        public boolean onHeader(Response response, HttpField field) {
            // Number of header may vary, so don't count
            return true;
        }

        @Override
        public void onHeaders(Response response) {
            counter.incrementAndGet();
        }

        @Override
        public void onContent(Response response, ByteBuffer content) {
            // Should not be invoked
            counter.incrementAndGet();
        }

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            // Should not be invoked
            counter.incrementAndGet();
        }

        @Override
        public void onSuccess(Response response) {
            counter.incrementAndGet();
        }

        @Override
        public void onFailure(Response response, Throwable failure) {
            // Should not be invoked
            counter.incrementAndGet();
        }

        @Override
        public void onComplete(Result result) {
            Assert.assertEquals(200, result.getResponse().getStatus());
            counter.incrementAndGet();
            latch.countDown();
        }
    };
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseBegin(listener).onResponseHeader(listener).onResponseHeaders(listener).onResponseContent(listener).onResponseContentAsync(listener).onResponseSuccess(listener).onResponseFailure(listener).send(listener);
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    int expectedEventsTriggeredByOnResponseXXXListeners = 3;
    int expectedEventsTriggeredByCompletionListener = 4;
    int expected = expectedEventsTriggeredByOnResponseXXXListeners + expectedEventsTriggeredByCompletionListener;
    Assert.assertEquals(expected, counter.get());
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpField(org.eclipse.jetty.http.HttpField) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) Result(org.eclipse.jetty.client.api.Result) Test(org.junit.Test)

Example 27 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class ForwardedRequestCustomizer method customize.

@Override
public void customize(Connector connector, HttpConfiguration config, Request request) {
    HttpFields httpFields = request.getHttpFields();
    RFC7239 rfc7239 = null;
    String forwardedHost = null;
    String forwardedServer = null;
    String forwardedFor = null;
    String forwardedProto = null;
    String forwardedHttps = null;
    // Do a single pass through the header fields as it is a more efficient single iteration.
    for (HttpField field : httpFields) {
        String name = field.getName();
        if (getForwardedCipherSuiteHeader() != null && getForwardedCipherSuiteHeader().equalsIgnoreCase(name)) {
            request.setAttribute("javax.servlet.request.cipher_suite", field.getValue());
            if (isSslIsSecure()) {
                request.setSecure(true);
                request.setScheme(config.getSecureScheme());
            }
        }
        if (getForwardedSslSessionIdHeader() != null && getForwardedSslSessionIdHeader().equalsIgnoreCase(name)) {
            request.setAttribute("javax.servlet.request.ssl_session_id", field.getValue());
            if (isSslIsSecure()) {
                request.setSecure(true);
                request.setScheme(config.getSecureScheme());
            }
        }
        if (forwardedHost == null && _forwardedHostHeader != null && _forwardedHostHeader.equalsIgnoreCase(name))
            forwardedHost = getLeftMost(field.getValue());
        if (forwardedServer == null && _forwardedServerHeader != null && _forwardedServerHeader.equalsIgnoreCase(name))
            forwardedServer = getLeftMost(field.getValue());
        if (forwardedFor == null && _forwardedForHeader != null && _forwardedForHeader.equalsIgnoreCase(name))
            forwardedFor = getLeftMost(field.getValue());
        if (forwardedProto == null && _forwardedProtoHeader != null && _forwardedProtoHeader.equalsIgnoreCase(name))
            forwardedProto = getLeftMost(field.getValue());
        if (forwardedHttps == null && _forwardedHttpsHeader != null && _forwardedHttpsHeader.equalsIgnoreCase(name))
            forwardedHttps = getLeftMost(field.getValue());
        if (_forwardedHeader != null && _forwardedHeader.equalsIgnoreCase(name)) {
            if (rfc7239 == null)
                rfc7239 = new RFC7239();
            rfc7239.addValue(field.getValue());
        }
    }
    // Handle host header if if not available any RFC7230.by or X-ForwardedServer header      
    if (_forcedHost != null) {
        // Update host header
        httpFields.put(_forcedHost);
        request.setAuthority(_forcedHost.getHost(), _forcedHost.getPort());
    } else if (rfc7239 != null && rfc7239._host != null) {
        HostPortHttpField auth = rfc7239._host;
        httpFields.put(auth);
        request.setAuthority(auth.getHost(), auth.getPort());
    } else if (forwardedHost != null) {
        HostPortHttpField auth = new HostPortHttpField(forwardedHost);
        httpFields.put(auth);
        request.setAuthority(auth.getHost(), auth.getPort());
    } else if (_proxyAsAuthority) {
        if (rfc7239 != null && rfc7239._by != null) {
            HostPortHttpField auth = rfc7239._by;
            httpFields.put(auth);
            request.setAuthority(auth.getHost(), auth.getPort());
        } else if (forwardedServer != null) {
            request.setAuthority(forwardedServer, request.getServerPort());
        }
    }
    // handle remote end identifier
    if (rfc7239 != null && rfc7239._for != null) {
        request.setRemoteAddr(InetSocketAddress.createUnresolved(rfc7239._for.getHost(), rfc7239._for.getPort()));
    } else if (forwardedFor != null) {
        request.setRemoteAddr(InetSocketAddress.createUnresolved(forwardedFor, request.getRemotePort()));
    }
    // handle protocol identifier
    if (rfc7239 != null && rfc7239._proto != null) {
        request.setScheme(rfc7239._proto);
        if (rfc7239._proto.equals(config.getSecureScheme()))
            request.setSecure(true);
    } else if (forwardedProto != null) {
        request.setScheme(forwardedProto);
        if (forwardedProto.equals(config.getSecureScheme()))
            request.setSecure(true);
    } else if (forwardedHttps != null && ("on".equalsIgnoreCase(forwardedHttps) || "true".equalsIgnoreCase(forwardedHttps))) {
        request.setScheme(HttpScheme.HTTPS.asString());
        if (HttpScheme.HTTPS.asString().equals(config.getSecureScheme()))
            request.setSecure(true);
    }
}
Also used : HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) HttpField(org.eclipse.jetty.http.HttpField) HttpFields(org.eclipse.jetty.http.HttpFields) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField)

Example 28 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class ResponseTest method testResetWithNewSession.

@Test
public void testResetWithNewSession() throws Exception {
    Response response = getResponse();
    Request request = response.getHttpChannel().getRequest();
    SessionHandler session_handler = new SessionHandler();
    session_handler.setServer(_server);
    session_handler.setUsingCookies(true);
    session_handler.start();
    request.setSessionHandler(session_handler);
    HttpSession session = request.getSession(true);
    assertThat(session, not(nullValue()));
    assertTrue(session.isNew());
    HttpField set_cookie = response.getHttpFields().getField(HttpHeader.SET_COOKIE);
    assertThat(set_cookie, not(nullValue()));
    assertThat(set_cookie.getValue(), startsWith("JSESSIONID"));
    assertThat(set_cookie.getValue(), containsString(session.getId()));
    response.setHeader("Some", "Header");
    response.addCookie(new Cookie("Some", "Cookie"));
    response.getOutputStream().print("X");
    assertThat(response.getHttpFields().size(), is(4));
    response.reset();
    set_cookie = response.getHttpFields().getField(HttpHeader.SET_COOKIE);
    assertThat(set_cookie, not(nullValue()));
    assertThat(set_cookie.getValue(), startsWith("JSESSIONID"));
    assertThat(set_cookie.getValue(), containsString(session.getId()));
    assertThat(response.getHttpFields().size(), is(2));
    response.getWriter();
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) HttpSession(javax.servlet.http.HttpSession) HttpField(org.eclipse.jetty.http.HttpField) HttpServletRequest(javax.servlet.http.HttpServletRequest) Test(org.junit.Test)

Example 29 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class AbstractProxyServlet method onServerResponseHeaders.

protected void onServerResponseHeaders(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
    for (HttpField field : serverResponse.getHeaders()) {
        String headerName = field.getName();
        String lowerHeaderName = headerName.toLowerCase(Locale.ENGLISH);
        if (HOP_HEADERS.contains(lowerHeaderName))
            continue;
        String newHeaderValue = filterServerResponseHeader(clientRequest, serverResponse, headerName, field.getValue());
        if (newHeaderValue == null || newHeaderValue.trim().length() == 0)
            continue;
        proxyResponse.addHeader(headerName, newHeaderValue);
    }
    if (_log.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder(System.lineSeparator());
        builder.append(clientRequest.getProtocol()).append(" ").append(proxyResponse.getStatus()).append(" ").append(serverResponse.getReason()).append(System.lineSeparator());
        for (String headerName : proxyResponse.getHeaderNames()) {
            builder.append(headerName).append(": ");
            for (Iterator<String> headerValues = proxyResponse.getHeaders(headerName).iterator(); headerValues.hasNext(); ) {
                String headerValue = headerValues.next();
                if (headerValue != null)
                    builder.append(headerValue);
                if (headerValues.hasNext())
                    builder.append(",");
            }
            builder.append(System.lineSeparator());
        }
        _log.debug("{} proxying to downstream:{}{}{}{}{}", getRequestId(clientRequest), System.lineSeparator(), serverResponse, System.lineSeparator(), serverResponse.getHeaders().toString().trim(), System.lineSeparator(), builder);
    }
}
Also used : HttpField(org.eclipse.jetty.http.HttpField)

Example 30 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class ContinuationParseTest method testParseOneByteAtATime.

@Test
public void testParseOneByteAtATime() throws Exception {
    ByteBufferPool byteBufferPool = new MappedByteBufferPool();
    HeadersGenerator generator = new HeadersGenerator(new HeaderGenerator(), new HpackEncoder());
    final List<HeadersFrame> frames = new ArrayList<>();
    Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

        @Override
        public void onHeaders(HeadersFrame frame) {
            frames.add(frame);
        }

        @Override
        public void onConnectionFailure(int error, String reason) {
            frames.add(new HeadersFrame(null, null, false));
        }
    }, 4096, 8192);
    // Iterate a few times to be sure the parser is properly reset.
    for (int i = 0; i < 2; ++i) {
        int streamId = 13;
        HttpFields fields = new HttpFields();
        fields.put("Accept", "text/html");
        fields.put("User-Agent", "Jetty");
        MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:8080"), "/path", HttpVersion.HTTP_2, fields);
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        generator.generateHeaders(lease, streamId, metaData, null, true);
        List<ByteBuffer> byteBuffers = lease.getByteBuffers();
        Assert.assertEquals(2, byteBuffers.size());
        ByteBuffer headersBody = byteBuffers.remove(1);
        int start = headersBody.position();
        int length = headersBody.remaining();
        int oneThird = length / 3;
        int lastThird = length - 2 * oneThird;
        // Adjust the length of the HEADERS frame.
        ByteBuffer headersHeader = byteBuffers.get(0);
        headersHeader.put(0, (byte) ((oneThird >>> 16) & 0xFF));
        headersHeader.put(1, (byte) ((oneThird >>> 8) & 0xFF));
        headersHeader.put(2, (byte) (oneThird & 0xFF));
        // Remove the END_HEADERS flag from the HEADERS header.
        headersHeader.put(4, (byte) (headersHeader.get(4) & ~Flags.END_HEADERS));
        // New HEADERS body.
        headersBody.position(start);
        headersBody.limit(start + oneThird);
        byteBuffers.add(headersBody.slice());
        // Split the rest of the HEADERS body into CONTINUATION frames.
        // First CONTINUATION header.
        byte[] continuationHeader1 = new byte[9];
        continuationHeader1[0] = (byte) ((oneThird >>> 16) & 0xFF);
        continuationHeader1[1] = (byte) ((oneThird >>> 8) & 0xFF);
        continuationHeader1[2] = (byte) (oneThird & 0xFF);
        continuationHeader1[3] = (byte) FrameType.CONTINUATION.getType();
        continuationHeader1[4] = Flags.NONE;
        continuationHeader1[5] = 0x00;
        continuationHeader1[6] = 0x00;
        continuationHeader1[7] = 0x00;
        continuationHeader1[8] = (byte) streamId;
        byteBuffers.add(ByteBuffer.wrap(continuationHeader1));
        // First CONTINUATION body.
        headersBody.position(start + oneThird);
        headersBody.limit(start + 2 * oneThird);
        byteBuffers.add(headersBody.slice());
        // Second CONTINUATION header.
        byte[] continuationHeader2 = new byte[9];
        continuationHeader2[0] = (byte) ((lastThird >>> 16) & 0xFF);
        continuationHeader2[1] = (byte) ((lastThird >>> 8) & 0xFF);
        continuationHeader2[2] = (byte) (lastThird & 0xFF);
        continuationHeader2[3] = (byte) FrameType.CONTINUATION.getType();
        continuationHeader2[4] = Flags.END_HEADERS;
        continuationHeader2[5] = 0x00;
        continuationHeader2[6] = 0x00;
        continuationHeader2[7] = 0x00;
        continuationHeader2[8] = (byte) streamId;
        byteBuffers.add(ByteBuffer.wrap(continuationHeader2));
        headersBody.position(start + 2 * oneThird);
        headersBody.limit(start + length);
        byteBuffers.add(headersBody.slice());
        frames.clear();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            while (buffer.hasRemaining()) {
                parser.parse(ByteBuffer.wrap(new byte[] { buffer.get() }));
            }
        }
        Assert.assertEquals(1, frames.size());
        HeadersFrame frame = frames.get(0);
        Assert.assertEquals(streamId, frame.getStreamId());
        Assert.assertTrue(frame.isEndStream());
        MetaData.Request request = (MetaData.Request) frame.getMetaData();
        Assert.assertEquals(metaData.getMethod(), request.getMethod());
        Assert.assertEquals(metaData.getURI(), request.getURI());
        for (int j = 0; j < fields.size(); ++j) {
            HttpField field = fields.getField(j);
            Assert.assertTrue(request.getFields().contains(field));
        }
        PriorityFrame priority = frame.getPriority();
        Assert.assertNull(priority);
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ArrayList(java.util.ArrayList) HeadersGenerator(org.eclipse.jetty.http2.generator.HeadersGenerator) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) HeaderGenerator(org.eclipse.jetty.http2.generator.HeaderGenerator) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) HpackEncoder(org.eclipse.jetty.http2.hpack.HpackEncoder) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) HttpField(org.eclipse.jetty.http.HttpField) Test(org.junit.Test)

Aggregations

HttpField (org.eclipse.jetty.http.HttpField)57 Test (org.junit.Test)29 HttpFields (org.eclipse.jetty.http.HttpFields)19 ByteBuffer (java.nio.ByteBuffer)17 MetaData (org.eclipse.jetty.http.MetaData)16 HostPortHttpField (org.eclipse.jetty.http.HostPortHttpField)12 ArrayList (java.util.ArrayList)8 PreEncodedHttpField (org.eclipse.jetty.http.PreEncodedHttpField)7 Entry (org.eclipse.jetty.http2.hpack.HpackContext.Entry)7 ByteBufferPool (org.eclipse.jetty.io.ByteBufferPool)7 MappedByteBufferPool (org.eclipse.jetty.io.MappedByteBufferPool)7 HttpHeader (org.eclipse.jetty.http.HttpHeader)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)5 HeaderGenerator (org.eclipse.jetty.http2.generator.HeaderGenerator)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 HpackEncoder (org.eclipse.jetty.http2.hpack.HpackEncoder)4 Parser (org.eclipse.jetty.http2.parser.Parser)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3