From cf9df70935c128ddc394da0d797611c2d0a5adc6 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Mon, 4 May 2020 23:16:59 +0200 Subject: [PATCH 1/3] Fixes #4808 - Review HttpClient Request header APIs. Introduced: * Request Request.headers(Consumer). This allows applications to modify the headers, and chain calls. It also delegates the precise semantic of put/add/remove/clear to HttpFields, so there is no API duplication. * HttpRequest.header(HttpField) to efficiently add fields while normalizing the request (only used in implementation). * HttpResponse.header(HttpField) to efficiently add fields while parsing the response (only used in implementation). This pairs with HttpResponse.trailer(HttpField). * HttpResponse.headers(Consumer) to modify the fields after they have been populated (only used in tests). Removed: * Request.[set,add,put,remove], replaced by headers(Consumer). Deprecated: * Request.header(String, String) * Request.header(HttpHeader, String) Both replaced by headers(Consumer) with clearer semantic for add/put/remove. All the rest is code cleanup to remove the usage of the deprecated header() methods. Signed-off-by: Simone Bordet --- .../jetty/embedded/ManyHandlersTest.java | 5 +- .../embedded/SecuredHelloHandlerTest.java | 2 +- .../client/AuthenticationProtocolHandler.java | 2 +- .../org/eclipse/jetty/client/HttpClient.java | 8 ++-- .../eclipse/jetty/client/HttpConnection.java | 24 +++++----- .../org/eclipse/jetty/client/HttpProxy.java | 9 ++-- .../eclipse/jetty/client/HttpReceiver.java | 4 +- .../org/eclipse/jetty/client/HttpRequest.java | 46 +++++++----------- .../eclipse/jetty/client/HttpResponse.java | 14 ++++-- .../org/eclipse/jetty/client/api/Request.java | 32 ++++--------- .../client/http/HttpConnectionOverHTTP.java | 11 ++--- .../client/http/HttpReceiverOverHTTP.java | 4 ++ .../client/util/BasicAuthentication.java | 2 +- .../client/util/DigestAuthentication.java | 2 +- .../client/util/FormContentProvider.java | 28 +---------- .../client/util/SPNEGOAuthentication.java | 2 +- .../client/ClientConnectionCloseTest.java | 13 ++--- .../jetty/client/ConnectionPoolTest.java | 29 ++++-------- .../client/HttpClientCorrelationDataTest.java | 2 +- .../client/HttpClientProxyProtocolTest.java | 3 +- .../jetty/client/HttpClientProxyTest.java | 4 +- .../jetty/client/HttpClientTLSTest.java | 5 +- .../eclipse/jetty/client/HttpClientTest.java | 47 +++++++++---------- .../client/HttpConnectionLifecycleTest.java | 4 +- .../eclipse/jetty/client/HttpCookieTest.java | 32 ++++++------- .../client/NetworkTrafficListenerTest.java | 2 +- .../org/eclipse/jetty/client/api/Usage.java | 2 +- .../http/HttpDestinationOverHTTPTest.java | 4 +- .../client/util/TypedContentProviderTest.java | 11 ++--- .../embedded/client/http/HTTPClientDocs.java | 9 ++-- .../client/http/HttpConnectionOverFCGI.java | 3 +- .../server/proxy/FastCGIProxyServlet.java | 13 ++--- .../session/TestHazelcastSessions.java | 21 ++++----- .../client/http/HttpConnectionOverHTTP2.java | 7 ++- .../client/http/HttpReceiverOverHTTP2.java | 4 ++ .../session/TestMemcachedSessions.java | 17 ++++--- .../jetty/proxy/AbstractProxyServlet.java | 18 +++---- .../jetty/proxy/AsyncMiddleManServlet.java | 2 +- .../proxy/AsyncMiddleManServletTest.java | 12 ++--- .../proxy/ForwardProxyTLSServerTest.java | 9 ++-- .../eclipse/jetty/proxy/ProxyServletTest.java | 17 +++---- .../org/eclipse/jetty/servlet/FormTest.java | 2 +- .../servlet/GzipHandlerBreakEvenSizeTest.java | 3 +- .../core/client/HttpUpgraderOverHTTP.java | 21 +++++---- .../core/client/HttpUpgraderOverHTTP2.java | 6 +-- .../core/WebSocketNegotiationTest.java | 2 +- .../javax/tests/server/ConfiguratorTest.java | 6 +-- .../jetty/http/client/AsyncIOServletTest.java | 7 +-- .../http/client/ConnectionStatisticsTest.java | 3 +- .../http/client/HttpClientContinueTest.java | 26 +++++----- .../jetty/http/client/HttpClientLoadTest.java | 11 +++-- .../jetty/http/client/HttpClientTest.java | 2 +- .../HttpClientTransportDynamicTest.java | 39 ++++++++------- .../jetty/test/FailedSelectorTest.java | 5 +- .../ClusteredSessionMigrationTest.java | 15 +++--- .../nosql/mongodb/AttributeNameTest.java | 12 ++--- .../AbstractClusteredOrphanedSessionTest.java | 13 +++-- .../AbstractWebAppObjectInSessionTest.java | 10 ++-- .../ClientCrossContextSessionTest.java | 13 +++-- .../session/DeleteUnloadableSessionTest.java | 22 ++++----- .../server/session/DuplicateCookieTest.java | 18 +++---- 61 files changed, 338 insertions(+), 383 deletions(-) diff --git a/examples/embedded/src/test/java/org/eclipse/jetty/embedded/ManyHandlersTest.java b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/ManyHandlersTest.java index 9f4ebcf0993..6b0b2d7fa24 100644 --- a/examples/embedded/src/test/java/org/eclipse/jetty/embedded/ManyHandlersTest.java +++ b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/ManyHandlersTest.java @@ -23,6 +23,7 @@ import java.util.Map; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Server; @@ -59,7 +60,7 @@ public class ManyHandlersTest extends AbstractEmbeddedTest ContentResponse response = client.newRequest(uri) .method(HttpMethod.GET) - .header(HttpHeader.ACCEPT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.ACCEPT_ENCODING, HttpHeaderValue.GZIP)) .send(); assertThat("HTTP Response Status", response.getStatus(), is(HttpStatus.OK_200)); @@ -84,7 +85,7 @@ public class ManyHandlersTest extends AbstractEmbeddedTest URI uri = server.getURI().resolve("/hello"); ContentResponse response = client.newRequest(uri) .method(HttpMethod.GET) - .header(HttpHeader.ACCEPT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.ACCEPT_ENCODING, HttpHeaderValue.GZIP)) .send(); assertThat("HTTP Response Status", response.getStatus(), is(HttpStatus.OK_200)); diff --git a/examples/embedded/src/test/java/org/eclipse/jetty/embedded/SecuredHelloHandlerTest.java b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/SecuredHelloHandlerTest.java index 5b569fbaae6..92bec6ec4dd 100644 --- a/examples/embedded/src/test/java/org/eclipse/jetty/embedded/SecuredHelloHandlerTest.java +++ b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/SecuredHelloHandlerTest.java @@ -72,7 +72,7 @@ public class SecuredHelloHandlerTest extends AbstractEmbeddedTest String authEncoded = Base64.getEncoder().encodeToString("user:password".getBytes(UTF_8)); ContentResponse response = client.newRequest(uri) .method(HttpMethod.GET) - .header(HttpHeader.AUTHORIZATION, "Basic " + authEncoded) + .headers(headers -> headers.put(HttpHeader.AUTHORIZATION, "Basic " + authEncoded)) .send(); assertThat("HTTP Response Status", response.getStatus(), is(HttpStatus.OK_200)); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java b/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java index 35067e47a26..494ba110379 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java @@ -256,7 +256,7 @@ public abstract class AuthenticationProtocolHandler implements ProtocolHandler { HttpField field = oldRequest.getHeaders().getField(header); if (field != null && !newRequest.getHeaders().contains(header)) - newRequest.put(field); + newRequest.headers(headers -> headers.put(field)); } private void forwardSuccessComplete(HttpRequest request, Response response) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java index f5270c93dc0..a662c16bbb1 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java @@ -444,7 +444,7 @@ public class HttpClient extends ContainerLifeCycle protected Request copyRequest(HttpRequest oldRequest, URI newURI) { - Request newRequest = newHttpRequest(oldRequest.getConversation(), newURI); + HttpRequest newRequest = newHttpRequest(oldRequest.getConversation(), newURI); newRequest.method(oldRequest.getMethod()) .version(oldRequest.getVersion()) .body(oldRequest.getBody()) @@ -471,10 +471,8 @@ public class HttpClient extends ContainerLifeCycle HttpHeader.PROXY_AUTHORIZATION == header) continue; - String name = field.getName(); - String value = field.getValue(); - if (!newRequest.getHeaders().contains(name, value)) - newRequest.header(name, value); + if (!newRequest.getHeaders().contains(field)) + newRequest.header(field); } return newRequest; } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java index 187a4f133e1..3546ce7192f 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java @@ -122,9 +122,9 @@ public abstract class HttpConnection implements IConnection } } - protected void normalizeRequest(Request request) + protected void normalizeRequest(HttpRequest request) { - boolean normalized = ((HttpRequest)request).normalized(); + boolean normalized = request.normalized(); if (LOG.isDebugEnabled()) LOG.debug("Normalizing {} {}", !normalized, request); if (normalized) @@ -153,7 +153,7 @@ public abstract class HttpConnection implements IConnection if (version.getVersion() <= 11) { if (!headers.contains(HttpHeader.HOST)) - request.put(getHttpDestination().getHostField()); + request.header(getHttpDestination().getHostField()); } // Add content headers @@ -167,22 +167,19 @@ public abstract class HttpConnection implements IConnection if (!headers.contains(HttpHeader.CONTENT_TYPE)) { String contentType = content.getContentType(); + if (contentType == null) + contentType = getHttpClient().getDefaultRequestContentType(); if (contentType != null) { - request.put(new HttpField(HttpHeader.CONTENT_TYPE, contentType)); - } - else - { - contentType = getHttpClient().getDefaultRequestContentType(); - if (contentType != null) - request.put(new HttpField(HttpHeader.CONTENT_TYPE, contentType)); + HttpField field = new HttpField(HttpHeader.CONTENT_TYPE, contentType); + request.header(field); } } long contentLength = content.getLength(); if (contentLength >= 0) { if (!headers.contains(HttpHeader.CONTENT_LENGTH)) - request.put(new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH, contentLength)); + request.header(new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH, contentLength)); } } @@ -195,7 +192,10 @@ public abstract class HttpConnection implements IConnection cookies = convertCookies(HttpCookieStore.matchPath(uri, cookieStore.get(uri)), null); cookies = convertCookies(request.getCookies(), cookies); if (cookies != null) - request.header(HttpHeader.COOKIE, cookies.toString()); + { + HttpField cookieField = new HttpField(HttpHeader.COOKIE, cookies.toString()); + request.header(cookieField); + } } // Authentication diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java index 64a2812a024..82b1918428d 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpProxy.java @@ -200,9 +200,9 @@ public class HttpProxy extends ProxyConfiguration.Proxy Origin.Address proxyAddress = destination.getConnectAddress(); HttpClient httpClient = destination.getHttpClient(); Request connect = new TunnelRequest(httpClient, proxyAddress) - .method(HttpMethod.CONNECT) - .path(target) - .header(HttpHeader.HOST, target); + .method(HttpMethod.CONNECT) + .path(target) + .headers(headers -> headers.put(HttpHeader.HOST, target)); ProxyConfiguration.Proxy proxy = destination.getProxy(); if (proxy.isSecure()) connect.scheme(HttpScheme.HTTPS.asString()); @@ -262,8 +262,7 @@ public class HttpProxy extends ProxyConfiguration.Proxy } else { - HttpResponseException failure = new HttpResponseException("Unexpected " + response + - " for " + response.getRequest(), response); + HttpResponseException failure = new HttpResponseException("Unexpected " + response + " for " + response.getRequest(), response); tunnelFailed(endPoint, failure); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java index c39d75b1717..937e4e3679c 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java @@ -72,7 +72,7 @@ import org.slf4j.LoggerFactory; */ public abstract class HttpReceiver { - protected static final Logger LOG = LoggerFactory.getLogger(HttpReceiver.class); + private static final Logger LOG = LoggerFactory.getLogger(HttpReceiver.class); private final AtomicReference responseState = new AtomicReference<>(ResponseState.IDLE); private final HttpChannel channel; @@ -242,7 +242,7 @@ public abstract class HttpReceiver boolean process = notifier.notifyHeader(exchange.getConversation().getResponseListeners(), response, field); if (process) { - response.getHeaderFieldsMutable().add(field); + response.header(field); HttpHeader fieldHeader = field.getHeader(); if (fieldHeader != null) { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java index 8d4e7a6eca8..30c9eb9b113 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java @@ -41,6 +41,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; +import java.util.function.Consumer; import java.util.function.LongConsumer; import java.util.function.Supplier; @@ -305,34 +306,6 @@ public class HttpRequest implements Request return this; } - @Override - public Request set(HttpFields fields) - { - headers.clear().add(fields); - return this; - } - - @Override - public Request remove(HttpHeader header) - { - headers.remove(header); - return this; - } - - @Override - public Request put(HttpField field) - { - headers.put(field); - return this; - } - - @Override - public Request add(HttpField field) - { - headers.add(field); - return this; - } - @Override public Request header(String name, String value) { @@ -402,6 +375,19 @@ public class HttpRequest implements Request return headers; } + @Override + public Request headers(Consumer consumer) + { + consumer.accept(headers); + return this; + } + + public HttpRequest header(HttpField header) + { + headers.add(header); + return this; + } + @Override @SuppressWarnings("unchecked") public List getRequestListeners(Class type) @@ -707,7 +693,7 @@ public class HttpRequest implements Request public Request content(ContentProvider content, String contentType) { if (contentType != null) - header(HttpHeader.CONTENT_TYPE, contentType); + headers.put(HttpHeader.CONTENT_TYPE, contentType); return body(ContentProvider.toRequestContent(content)); } @@ -886,7 +872,7 @@ public class HttpRequest implements Request * headers, etc.

* * @return whether this request was already normalized - * @see HttpConnection#normalizeRequest(Request) + * @see HttpConnection#normalizeRequest(HttpRequest) */ boolean normalized() { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java index 3d941c92827..28c0dcf0df6 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java @@ -20,6 +20,7 @@ package org.eclipse.jetty.client; import java.util.ArrayList; import java.util.List; +import java.util.function.Consumer; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; @@ -91,9 +92,16 @@ public class HttpResponse implements Response return headers.asImmutable(); } - public HttpFields.Mutable getHeaderFieldsMutable() + public HttpResponse header(HttpField header) { - return headers; + headers.add(header); + return this; + } + + public HttpResponse headers(Consumer consumer) + { + consumer.accept(headers); + return this; } @Override @@ -110,7 +118,7 @@ public class HttpResponse implements Response public HttpFields getTrailers() { - return trailers; + return trailers.asImmutable(); } public HttpResponse trailer(HttpField trailer) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java index 7b2d14edb27..c1831b869ac 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/api/Request.java @@ -31,10 +31,10 @@ import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.Consumer; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.util.InputStreamResponseListener; -import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpMethod; @@ -166,38 +166,22 @@ public interface Request */ HttpFields getHeaders(); - /** Set the headers, clearing any existing headers - * @param fields The fields to set - * @return this request object - */ - Request set(HttpFields fields); - /** - * @param header the header to remove + * Modifies the headers of this request. + * + * @param consumer the code that modifies the headers of this request * @return this request object */ - Request remove(HttpHeader header); - - /** - * @param field the field to add - * @return this request object - * @see #header(HttpHeader, String) - */ - Request add(HttpField field); - - /** - * @param field the field to put - * @return this request object - * @see #header(HttpHeader, String) - */ - Request put(HttpField field); + Request headers(Consumer consumer); /** * @param name the name of the header * @param value the value of the header * @return this request object * @see #header(HttpHeader, String) + * @deprecated use {@link #headers(Consumer)} instead */ + @Deprecated Request header(String name, String value); /** @@ -208,7 +192,9 @@ public interface Request * @param header the header name * @param value the value of the header * @return this request object + * @deprecated use {@link #headers(Consumer)} instead */ + @Deprecated Request header(HttpHeader header, String value); /** diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpConnectionOverHTTP.java b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpConnectionOverHTTP.java index 1375d799458..f6bd5d11353 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpConnectionOverHTTP.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpConnectionOverHTTP.java @@ -261,7 +261,7 @@ public class HttpConnectionOverHTTP extends AbstractConnection implements IConne @Override public SendFailure send(HttpExchange exchange) { - Request request = exchange.getRequest(); + HttpRequest request = exchange.getRequest(); normalizeRequest(request); // Save the old idle timeout to restore it. @@ -276,7 +276,7 @@ public class HttpConnectionOverHTTP extends AbstractConnection implements IConne } @Override - protected void normalizeRequest(Request request) + protected void normalizeRequest(HttpRequest request) { super.normalizeRequest(request); @@ -287,8 +287,7 @@ public class HttpConnectionOverHTTP extends AbstractConnection implements IConne .idleTimeout(2 * connectTimeout, TimeUnit.MILLISECONDS); } - HttpRequest httpRequest = (HttpRequest)request; - HttpConversation conversation = httpRequest.getConversation(); + HttpConversation conversation = request.getConversation(); HttpUpgrader upgrader = (HttpUpgrader)conversation.getAttribute(HttpUpgrader.class.getName()); if (upgrader == null) { @@ -296,7 +295,7 @@ public class HttpConnectionOverHTTP extends AbstractConnection implements IConne { upgrader = ((HttpUpgrader.Factory)request).newHttpUpgrader(HttpVersion.HTTP_1_1); conversation.setAttribute(HttpUpgrader.class.getName(), upgrader); - upgrader.prepare(httpRequest); + upgrader.prepare(request); } else { @@ -305,7 +304,7 @@ public class HttpConnectionOverHTTP extends AbstractConnection implements IConne { upgrader = new ProtocolHttpUpgrader(getHttpDestination(), protocol); conversation.setAttribute(HttpUpgrader.class.getName(), upgrader); - upgrader.prepare(httpRequest); + upgrader.prepare(request); } } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java index 4bd4307fed1..5047b482338 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTP.java @@ -38,9 +38,13 @@ import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.RetainableByteBuffer; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HttpReceiverOverHTTP extends HttpReceiver implements HttpParser.ResponseHandler { + private static final Logger LOG = LoggerFactory.getLogger(HttpReceiverOverHTTP.class); + private final HttpParser parser; private RetainableByteBuffer networkBuffer; private boolean shutdown; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/BasicAuthentication.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/BasicAuthentication.java index ed3665074f0..faa889a63f1 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/BasicAuthentication.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/BasicAuthentication.java @@ -105,7 +105,7 @@ public class BasicAuthentication extends AbstractAuthentication public void apply(Request request) { if (!request.getHeaders().contains(header, value)) - request.header(header, value); + request.headers(headers -> headers.add(header, value)); } @Override diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java index 466ea8168b6..dac81b63102 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/DigestAuthentication.java @@ -204,7 +204,7 @@ public class DigestAuthentication extends AbstractAuthentication } value.append(", response=\"").append(hashA3).append("\""); - request.header(header, value.toString()); + request.headers(headers -> headers.add(header, value.toString())); } private String nextNonceCount() diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/FormContentProvider.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/FormContentProvider.java index 2bff3857e3a..356dfe75f6b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/FormContentProvider.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/FormContentProvider.java @@ -18,11 +18,8 @@ package org.eclipse.jetty.client.util; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.nio.charset.UnsupportedCharsetException; import org.eclipse.jetty.client.api.ContentProvider; import org.eclipse.jetty.util.Fields; @@ -53,29 +50,6 @@ public class FormContentProvider extends StringContentProvider public static String convert(Fields fields, Charset charset) { - // Assume 32 chars between name and value. - StringBuilder builder = new StringBuilder(fields.getSize() * 32); - for (Fields.Field field : fields) - { - for (String value : field.getValues()) - { - if (builder.length() > 0) - builder.append("&"); - builder.append(encode(field.getName(), charset)).append("=").append(encode(value, charset)); - } - } - return builder.toString(); - } - - private static String encode(String value, Charset charset) - { - try - { - return URLEncoder.encode(value, charset.name()); - } - catch (UnsupportedEncodingException x) - { - throw new UnsupportedCharsetException(charset.name()); - } + return FormRequestContent.convert(fields, charset); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java index 5f3d7742604..a3398393372 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/SPNEGOAuthentication.java @@ -307,7 +307,7 @@ public class SPNEGOAuthentication extends AbstractAuthentication @Override public void apply(Request request) { - request.header(header, value); + request.headers(headers -> headers.add(header, value)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java index 70cb83e408f..bd6c64dde53 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java @@ -86,7 +86,7 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest var request = client.newRequest(host, port) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .body(new StringRequestContent("0")) .onRequestSuccess(r -> { @@ -126,7 +126,7 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest long idleTimeout = 1000; var request = client.newRequest(host, port) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .onRequestSuccess(r -> { @@ -188,7 +188,7 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest CountDownLatch resultLatch = new CountDownLatch(1); var request = client.newRequest(host, port) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .body(content) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .onRequestSuccess(r -> @@ -242,7 +242,7 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest var request = client.newRequest(host, port) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .onRequestSuccess(r -> { HttpDestination destination = (HttpDestination)client.resolveDestination(r); @@ -250,10 +250,7 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); assertFalse(connection.getEndPoint().isOutputShutdown()); }) - .onResponseHeaders(r -> - { - ((HttpResponse)r).getHeaderFieldsMutable().remove(HttpHeader.CONNECTION); - }); + .onResponseHeaders(r -> ((HttpResponse)r).headers(headers -> headers.remove(HttpHeader.CONNECTION))); ContentResponse response = request.send(); assertEquals(HttpStatus.OK_200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java index 08139dbf1d6..581d61a7c03 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.client; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -36,6 +35,7 @@ import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.client.util.BytesRequestContent; import org.eclipse.jetty.client.util.FutureResponseListener; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Handler; @@ -45,7 +45,6 @@ import org.eclipse.jetty.util.IO; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -58,20 +57,10 @@ public class ConnectionPoolTest private ServerConnector connector; private HttpClient client; - public static Stream pools() + public static Stream pools() { - List pools = new ArrayList<>(); - pools.add(new Object[]{ - DuplexConnectionPool.class, - (ConnectionPool.Factory) - destination -> new DuplexConnectionPool(destination, 8, destination) - }); - pools.add(new Object[]{ - RoundRobinConnectionPool.class, - (ConnectionPool.Factory) - destination -> new RoundRobinConnectionPool(destination, 8, destination) - }); - return pools.stream().map(Arguments::of); + return Stream.of(destination -> new DuplexConnectionPool(destination, 8, destination), + destination -> new RoundRobinConnectionPool(destination, 8, destination)); } private void start(final ConnectionPool.Factory factory, Handler handler) throws Exception @@ -112,7 +101,7 @@ public class ConnectionPoolTest @ParameterizedTest(name = "[{index}] {0}") @MethodSource("pools") - public void test(Class connectionPoolClass, ConnectionPool.Factory factory) throws Exception + public void test(ConnectionPool.Factory factory) throws Exception { start(factory, new EmptyServerHandler() { @@ -202,17 +191,17 @@ public class ConnectionPoolTest .method(method); if (clientClose) - request.header(HttpHeader.CONNECTION, "close"); + request.headers(fields -> fields.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)); else if (serverClose) - request.header("X-Close", "true"); + request.headers(fields -> fields.put("X-Close", "true")); switch (method) { case GET: - request.header("X-Download", String.valueOf(contentLength)); + request.headers(fields -> fields.put("X-Download", String.valueOf(contentLength))); break; case POST: - request.header(HttpHeader.CONTENT_LENGTH, String.valueOf(contentLength)); + request.headers(fields -> fields.put(HttpHeader.CONTENT_LENGTH, String.valueOf(contentLength))); request.body(new BytesRequestContent(new byte[contentLength])); break; default: diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCorrelationDataTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCorrelationDataTest.java index 3fa4680c475..71331cd8b12 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCorrelationDataTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCorrelationDataTest.java @@ -54,7 +54,7 @@ public class HttpClientCorrelationDataTest extends AbstractHttpClientServerTest @Override public void onQueued(Request request) { - request.header(correlationName, correlation.get()); + request.headers(headers -> headers.put(correlationName, correlation.get())); } }); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyProtocolTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyProtocolTest.java index bdf75fbbdb9..5d20037f480 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyProtocolTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyProtocolTest.java @@ -29,6 +29,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Destination; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.EndPoint; @@ -248,7 +249,7 @@ public class HttpClientProxyProtocolTest // The proxy maps the client address, then sends the request. ContentResponse response = client.newRequest("localhost", serverPort) .tag(tag) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java index e223f8ba2e0..35959299f0a 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java @@ -379,7 +379,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest // Make a request, expect 407 + 204. ContentResponse response1 = client.newRequest(serverHost, serverPort) .scheme(scenario.getScheme()) - .header(HttpHeader.AUTHORIZATION, "Basic foobar") + .headers(headers -> headers.put(HttpHeader.AUTHORIZATION, "Basic foobar")) .timeout(5, TimeUnit.SECONDS) .send(); @@ -390,7 +390,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest requests.set(0); ContentResponse response2 = client.newRequest(serverHost, serverPort) .scheme(scenario.getScheme()) - .header(HttpHeader.AUTHORIZATION, "Basic foobar") + .headers(headers -> headers.put(HttpHeader.AUTHORIZATION, "Basic foobar")) .timeout(5, TimeUnit.SECONDS) .send(); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java index 2678e18778b..491df8bdbea 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java @@ -44,6 +44,7 @@ import javax.net.ssl.SSLSocket; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpScheme; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.io.ByteBufferPool; @@ -380,7 +381,7 @@ public class HttpClientTLSTest // First request primes the TLS session. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .timeout(5, TimeUnit.SECONDS) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -416,7 +417,7 @@ public class HttpClientTLSTest // Second request should have the same session ID. response = client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .timeout(5, TimeUnit.SECONDS) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java index 79a377408b1..0c516e4e24b 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java @@ -907,7 +907,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest // If no exceptions the test passes. client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .send(); } @@ -938,8 +938,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) - .header(HttpHeader.USER_AGENT, null) - .header(HttpHeader.USER_AGENT, userAgent) + .headers(headers -> headers.put(HttpHeader.USER_AGENT, userAgent)) .timeout(5, TimeUnit.SECONDS) .send(); @@ -985,7 +984,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest // User agent explicitly removed. response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) - .header(HttpHeader.USER_AGENT, null) + .headers(headers -> headers.remove(HttpHeader.USER_AGENT)) .timeout(5, TimeUnit.SECONDS) .send(); @@ -1213,7 +1212,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest ContentResponse response = client.newRequest("http://127.0.0.1:" + connector.getLocalPort() + "/path") .scheme(scenario.getScheme()) - .header(HttpHeader.HOST, host) + .headers(headers -> headers.put(HttpHeader.HOST, host)) .send(); assertEquals(200, response.getStatus()); @@ -1239,7 +1238,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .version(HttpVersion.HTTP_1_0) - .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())) .timeout(5, TimeUnit.SECONDS) .send(); @@ -1266,7 +1265,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest Request request = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .version(HttpVersion.HTTP_1_0) - .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())) .timeout(timeout, TimeUnit.MILLISECONDS); FuturePromise promise = new FuturePromise<>(); Destination destination = client.resolveDestination(request); @@ -1295,7 +1294,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .version(HttpVersion.HTTP_1_0) - .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())) .timeout(5, TimeUnit.SECONDS) .send(); @@ -1647,8 +1646,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(321, TimeUnit.SECONDS) .idleTimeout(2221, TimeUnit.SECONDS) .followRedirects(true) - .header(HttpHeader.CONTENT_TYPE, "application/json") - .header("X-Some-Custom-Header", "some-value")); + .headers(headers -> headers.put(HttpHeader.CONTENT_TYPE, "application/json")) + .headers(headers -> headers.put("X-Some-Custom-Header", "some-value"))); assertCopyRequest(client.newRequest("https://example.com") .method(HttpMethod.POST) @@ -1657,30 +1656,30 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(123231, TimeUnit.SECONDS) .idleTimeout(232342, TimeUnit.SECONDS) .followRedirects(false) - .header(HttpHeader.ACCEPT, "application/json") - .header("X-Some-Other-Custom-Header", "some-other-value")); + .headers(headers -> headers.put(HttpHeader.ACCEPT, "application/json")) + .headers(headers -> headers.put("X-Some-Other-Custom-Header", "some-other-value"))); assertCopyRequest(client.newRequest("https://example.com") - .header(HttpHeader.ACCEPT, "application/json") - .header(HttpHeader.ACCEPT, "application/xml") - .header("x-same-name", "value1") - .header("x-same-name", "value2")); + .headers(headers -> headers.add(HttpHeader.ACCEPT, "application/json")) + .headers(headers -> headers.add(HttpHeader.ACCEPT, "application/xml")) + .headers(headers -> headers.add("x-same-name", "value1")) + .headers(headers -> headers.add("x-same-name", "value2"))); assertCopyRequest(client.newRequest("https://example.com") - .header(HttpHeader.ACCEPT, "application/json") - .header(HttpHeader.CONTENT_TYPE, "application/json")); + .headers(headers -> headers.put(HttpHeader.ACCEPT, "application/json")) + .headers(headers -> headers.put(HttpHeader.CONTENT_TYPE, "application/json"))); assertCopyRequest(client.newRequest("https://example.com") - .header("Accept", "application/json") - .header("Content-Type", "application/json")); + .headers(headers -> headers.put("Accept", "application/json")) + .headers(headers -> headers.put("Content-Type", "application/json"))); assertCopyRequest(client.newRequest("https://example.com") - .header("X-Custom-Header-1", "value1") - .header("X-Custom-Header-2", "value2")); + .headers(headers -> headers.put("X-Custom-Header-1", "value1")) + .headers(headers -> headers.put("X-Custom-Header-2", "value2"))); assertCopyRequest(client.newRequest("https://example.com") - .header("X-Custom-Header-1", "value") - .header("X-Custom-Header-2", "value")); + .headers(headers -> headers.put("X-Custom-Header-1", "value")) + .headers(headers -> headers.put("X-Custom-Header-2", "value"))); } @ParameterizedTest diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java index 5d622444395..a06fd83957d 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java @@ -189,7 +189,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest public void onBegin(Request request) { // Remove the host header, this will make the request invalid - request.header(HttpHeader.HOST, null); + request.headers(headers -> headers.remove(HttpHeader.HOST)); } @Override @@ -251,7 +251,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest public void onBegin(Request request) { // Remove the host header, this will make the request invalid - request.header(HttpHeader.HOST, null); + request.headers(headers -> headers.remove(HttpHeader.HOST)); } @Override diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java index 6699c7cb336..9b58e6afee1 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java @@ -198,7 +198,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -207,7 +207,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -259,7 +259,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo/bar") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -268,7 +268,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -320,7 +320,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -329,7 +329,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -381,7 +381,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo/bar") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -390,7 +390,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -444,7 +444,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -453,7 +453,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -514,7 +514,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -523,7 +523,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -587,7 +587,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -596,7 +596,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); @@ -648,7 +648,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/foo/bar") - .header(headerName, "0") + .headers(headers -> headers.put(headerName, "0")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, response.getStatus()); @@ -657,7 +657,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path(path) - .header(headerName, "1") + .headers(headers -> headers.put(headerName, "1")) .timeout(5, TimeUnit.SECONDS)); assertEquals(HttpStatus.OK_200, r.getStatus()); }); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/NetworkTrafficListenerTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/NetworkTrafficListenerTest.java index af495308727..7b866206883 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/NetworkTrafficListenerTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/NetworkTrafficListenerTest.java @@ -188,7 +188,7 @@ public class NetworkTrafficListenerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .send(); assertEquals(HttpStatus.OK_200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java b/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java index 81a06f8ec8f..0bc41c78721 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java @@ -81,7 +81,7 @@ public class Usage .path("/uri") .version(HttpVersion.HTTP_1_1) .param("a", "b") - .header("X-Header", "Y-value") + .headers(headers -> headers.put("X-Header", "Y-value")) .agent("Jetty HTTP Client") .idleTimeout(5000, TimeUnit.MILLISECONDS) .timeout(20, TimeUnit.SECONDS); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java index 49e8c0c46a3..e2543bee6a3 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java @@ -262,7 +262,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest int port = connector.getLocalPort(); Request request = client.newRequest(host, port) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()); + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)); Destination destinationBefore = client.resolveDestination(request); ContentResponse response = request.send(); @@ -275,7 +275,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest request = client.newRequest(host, port) .scheme(scenario.getScheme()) - .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()); + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)); response = request.send(); assertEquals(200, response.getStatus()); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java index cce0415b3a5..c2b5cb3b973 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.client.util; import java.io.IOException; import java.nio.charset.StandardCharsets; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -57,7 +56,7 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest start(scenario, new AbstractHandler() { @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { baseRequest.setHandled(true); assertEquals("POST", request.getMethod()); @@ -90,13 +89,13 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest Fields fields = new Fields(); fields.put(name1, value1); fields.add(name2, value2); - final String content = FormContentProvider.convert(fields); + final String content = FormRequestContent.convert(fields); final String contentType = "text/plain;charset=UTF-8"; start(scenario, new AbstractHandler() { @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { baseRequest.setHandled(true); assertEquals("POST", request.getMethod()); @@ -109,7 +108,7 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest .scheme(scenario.getScheme()) .method(HttpMethod.POST) .body(new FormRequestContent(fields)) - .header(HttpHeader.CONTENT_TYPE, contentType) + .headers(headers -> headers.put(HttpHeader.CONTENT_TYPE, contentType)) .send(); assertEquals(200, response.getStatus()); @@ -124,7 +123,7 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest start(scenario, new AbstractHandler() { @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { baseRequest.setHandled(true); assertEquals("GET", request.getMethod()); diff --git a/jetty-documentation/src/main/java/embedded/client/http/HTTPClientDocs.java b/jetty-documentation/src/main/java/embedded/client/http/HTTPClientDocs.java index 60161cf3c21..3e788294e90 100644 --- a/jetty-documentation/src/main/java/embedded/client/http/HTTPClientDocs.java +++ b/jetty-documentation/src/main/java/embedded/client/http/HTTPClientDocs.java @@ -739,7 +739,7 @@ public class HTTPClientDocs // end::dynamicDefault[] } - public void dynamicOneProtocol() throws Exception + public void dynamicOneProtocol() { // tag::dynamicOneProtocol[] ClientConnector connector = new ClientConnector(); @@ -798,9 +798,10 @@ public class HTTPClientDocs // Make a clear-text upgrade request from HTTP/1.1 to HTTP/2. // The request will start as HTTP/1.1, but the response will be HTTP/2. ContentResponse upgradedResponse = client.newRequest("host", 8080) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.HTTP2_SETTINGS, "") - .header(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings") + .headers(headers -> headers + .put(HttpHeader.UPGRADE, "h2c") + .put(HttpHeader.HTTP2_SETTINGS, "") + .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) .send(); // end::dynamicClearText[] } diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java index c4720e32318..87b0885687a 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java @@ -34,6 +34,7 @@ import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpConnection; import org.eclipse.jetty.client.HttpDestination; import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.client.HttpRequest; import org.eclipse.jetty.client.IConnection; import org.eclipse.jetty.client.SendFailure; import org.eclipse.jetty.client.api.Connection; @@ -357,7 +358,7 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne @Override public SendFailure send(HttpExchange exchange) { - Request request = exchange.getRequest(); + HttpRequest request = exchange.getRequest(); normalizeRequest(request); // FCGI may be multiplexed, so one channel for each exchange. diff --git a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java index c04580d4f8b..2359ba5bc06 100644 --- a/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java +++ b/jetty-fcgi/fcgi-server/src/main/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.java @@ -182,12 +182,14 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent // If the Host header is missing, add it. if (!proxyRequest.getHeaders().contains(HttpHeader.HOST)) { - String host = request.getServerName(); + String server = request.getServerName(); int port = request.getServerPort(); if (!getHttpClient().isDefaultPort(request.getScheme(), port)) - host += ":" + port; - proxyRequest.header(HttpHeader.HOST, host); - proxyRequest.header(HttpHeader.X_FORWARDED_HOST, host); + server += ":" + port; + String host = server; + proxyRequest.headers(headers -> headers + .put(HttpHeader.HOST, host) + .put(HttpHeader.X_FORWARDED_HOST, host)); } // PHP does not like multiple Cookie headers, coalesce into one. @@ -202,8 +204,7 @@ public class FastCGIProxyServlet extends AsyncProxyServlet.Transparent String cookie = cookies.get(i); builder.append(cookie); } - proxyRequest.header(HttpHeader.COOKIE, null); - proxyRequest.header(HttpHeader.COOKIE, builder.toString()); + proxyRequest.headers(headers -> headers.put(HttpHeader.COOKIE, builder.toString())); } super.sendProxyRequest(request, proxyResponse, proxyRequest); diff --git a/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java b/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java index 88fe6a48db9..aae916d81c4 100644 --- a/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java +++ b/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.hazelcast.session; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -29,6 +28,7 @@ import javax.servlet.http.HttpSession; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; @@ -42,17 +42,13 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; public class TestHazelcastSessions { - public static class TestServlet - extends HttpServlet + public static class TestServlet extends HttpServlet { - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String arg = req.getParameter("action"); if (arg == null) @@ -154,16 +150,17 @@ public class TestHazelcastSessions client.GET("http://localhost:" + port + contextPath + "?action=set&value=" + value); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String sessionCookie = response.getHeaders().get("Set-Cookie"); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); // Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); + sessionCookie = sessionCookie.replaceFirst("(\\W)([Pp])ath=", "$1\\$Path="); String resp = response.getContentAsString(); assertEquals(resp.trim(), String.valueOf(value)); // Be sure the session value is still there + HttpField cookie = new HttpField("Cookie", sessionCookie); Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); - request.header("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); @@ -172,13 +169,13 @@ public class TestHazelcastSessions //Delete the session request = client.newRequest("http://localhost:" + port + contextPath + "?action=del"); - request.header("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); //Check that the session is gone request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); - request.header("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); resp = response.getContentAsString(); diff --git a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java index f8f3d5c6e0a..8a4224c49ea 100644 --- a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java +++ b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpConnectionOverHTTP2.java @@ -37,7 +37,6 @@ import org.eclipse.jetty.client.HttpRequest; import org.eclipse.jetty.client.HttpResponse; import org.eclipse.jetty.client.HttpUpgrader; import org.eclipse.jetty.client.SendFailure; -import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpURI; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.http.MetaData; @@ -126,14 +125,14 @@ public class HttpConnectionOverHTTP2 extends HttpConnection implements Sweeper.S } @Override - protected void normalizeRequest(Request request) + protected void normalizeRequest(HttpRequest request) { super.normalizeRequest(request); if (request instanceof HttpUpgrader.Factory) { HttpUpgrader upgrader = ((HttpUpgrader.Factory)request).newHttpUpgrader(HttpVersion.HTTP_2); - ((HttpRequest)request).getConversation().setAttribute(HttpUpgrader.class.getName(), upgrader); - upgrader.prepare((HttpRequest)request); + request.getConversation().setAttribute(HttpUpgrader.class.getName(), upgrader); + upgrader.prepare(request); } } diff --git a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java index ea2e1f93a22..e2cfc1e8650 100644 --- a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java +++ b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java @@ -50,9 +50,13 @@ import org.eclipse.jetty.http2.frames.ResetFrame; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.Client { + private static final Logger LOG = LoggerFactory.getLogger(HttpReceiverOverHTTP2.class); + private final ContentNotifier contentNotifier = new ContentNotifier(this); public HttpReceiverOverHTTP2(HttpChannel channel) diff --git a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java index 9debffeb235..0870135808b 100644 --- a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java +++ b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.memcached.session; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -29,6 +28,7 @@ import javax.servlet.http.HttpSession; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.server.NetworkConnector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.session.CachingSessionDataStore; @@ -40,7 +40,6 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; /** * TestMemcachedSessions @@ -49,9 +48,8 @@ public class TestMemcachedSessions { public static class TestServlet extends HttpServlet { - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String arg = req.getParameter("action"); if (arg == null) @@ -117,16 +115,17 @@ public class TestMemcachedSessions ContentResponse response = client.GET("http://localhost:" + port + contextPath + "?action=set&value=" + value); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String sessionCookie = response.getHeaders().get("Set-Cookie"); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); // Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); + sessionCookie = sessionCookie.replaceFirst("(\\W)([Pp])ath=", "$1\\$Path="); String resp = response.getContentAsString(); assertEquals(resp.trim(), String.valueOf(value)); // Be sure the session value is still there + HttpField cookie = new HttpField("Cookie", sessionCookie); Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); - request.header("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); @@ -135,13 +134,13 @@ public class TestMemcachedSessions //Delete the session request = client.newRequest("http://localhost:" + port + contextPath + "?action=del"); - request.header("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); //Check that the session is gone request = client.newRequest("http://localhost:" + port + contextPath + "?action=get"); - request.header("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); resp = response.getContentAsString(); diff --git a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java index d29dbad3b26..4f2c8a74960 100644 --- a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java +++ b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java @@ -499,7 +499,7 @@ public abstract class AbstractProxyServlet extends HttpServlet if (_hostHeader != null) newHeaders.add(HttpHeader.HOST, _hostHeader); - proxyRequest.set(newHeaders); + proxyRequest.headers(headers -> headers.clear().add(newHeaders)); } protected Set findConnectionHeaders(HttpServletRequest clientRequest) @@ -531,15 +531,15 @@ public abstract class AbstractProxyServlet extends HttpServlet protected void addViaHeader(Request proxyRequest) { - proxyRequest.header(HttpHeader.VIA, "http/1.1 " + getViaHost()); + proxyRequest.headers(headers -> headers.add(HttpHeader.VIA, "http/1.1 " + getViaHost())); } protected void addXForwardedHeaders(HttpServletRequest clientRequest, Request proxyRequest) { - proxyRequest.header(HttpHeader.X_FORWARDED_FOR, clientRequest.getRemoteAddr()); - proxyRequest.header(HttpHeader.X_FORWARDED_PROTO, clientRequest.getScheme()); - proxyRequest.header(HttpHeader.X_FORWARDED_HOST, clientRequest.getHeader(HttpHeader.HOST.asString())); - proxyRequest.header(HttpHeader.X_FORWARDED_SERVER, clientRequest.getLocalName()); + proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_FOR, clientRequest.getRemoteAddr())); + proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_PROTO, clientRequest.getScheme())); + proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_HOST, clientRequest.getHeader(HttpHeader.HOST.asString()))); + proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_SERVER, clientRequest.getLocalName())); } protected void sendProxyRequest(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest) @@ -633,13 +633,9 @@ public abstract class AbstractProxyServlet extends HttpServlet } builder.append(System.lineSeparator()); } - _log.debug("{} proxying to downstream:{}{}{}{}{}", + _log.debug("{} proxying to downstream:{}{}", getRequestId(clientRequest), System.lineSeparator(), - serverResponse, - System.lineSeparator(), - serverResponse.getHeaders().toString().trim(), - System.lineSeparator(), builder); } } diff --git a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AsyncMiddleManServlet.java b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AsyncMiddleManServlet.java index cd5c5e2fbad..d66a93a1eda 100644 --- a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AsyncMiddleManServlet.java +++ b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AsyncMiddleManServlet.java @@ -396,7 +396,7 @@ public class AsyncMiddleManServlet extends AbstractProxyServlet clientRequest.setAttribute(PROXY_REQUEST_CONTENT_COMMITTED_ATTRIBUTE, true); if (!expects100Continue) { - proxyRequest.header(HttpHeader.CONTENT_LENGTH, null); + proxyRequest.headers(headers -> headers.remove(HttpHeader.CONTENT_LENGTH)); sendProxyRequest(clientRequest, proxyResponse, proxyRequest); } } diff --git a/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/AsyncMiddleManServletTest.java b/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/AsyncMiddleManServletTest.java index 11bb328dd78..d520d3c8fa7 100644 --- a/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/AsyncMiddleManServletTest.java +++ b/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/AsyncMiddleManServletTest.java @@ -226,7 +226,7 @@ public class AsyncMiddleManServletTest Request.Content gzipContent = new BytesRequestContent(gzipBytes); ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.CONTENT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.CONTENT_ENCODING, HttpHeaderValue.GZIP)) .body(gzipContent) .timeout(5, TimeUnit.SECONDS) .send(); @@ -301,7 +301,7 @@ public class AsyncMiddleManServletTest startClient(); ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.CONTENT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.CONTENT_ENCODING, HttpHeaderValue.GZIP)) .body(new BytesRequestContent(gzip(bytes))) .timeout(5, TimeUnit.SECONDS) .send(); @@ -348,7 +348,7 @@ public class AsyncMiddleManServletTest startClient(); ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.CONTENT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.CONTENT_ENCODING, HttpHeaderValue.GZIP)) .timeout(5, TimeUnit.SECONDS) .send(); @@ -393,7 +393,7 @@ public class AsyncMiddleManServletTest AsyncRequestContent content = new AsyncRequestContent(); Request request = client.newRequest("localhost", serverConnector.getLocalPort()); FutureResponseListener listener = new FutureResponseListener(request); - request.header(HttpHeader.CONTENT_ENCODING, "gzip") + request.headers(headers -> headers.put(HttpHeader.CONTENT_ENCODING, HttpHeaderValue.GZIP)) .body(content) .send(listener); byte[] bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.UTF_8); @@ -438,7 +438,7 @@ public class AsyncMiddleManServletTest byte[] bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.UTF_8); ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.CONTENT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.CONTENT_ENCODING, HttpHeaderValue.GZIP)) .body(new BytesRequestContent(gzip(bytes))) .timeout(5, TimeUnit.SECONDS) .send(); @@ -482,7 +482,7 @@ public class AsyncMiddleManServletTest startClient(); ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.CONTENT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.CONTENT_ENCODING, HttpHeaderValue.GZIP)) .body(new BytesRequestContent(gzip(bytes))) .timeout(5, TimeUnit.SECONDS) .send(); diff --git a/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ForwardProxyTLSServerTest.java b/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ForwardProxyTLSServerTest.java index 053de8b782a..41d12de38e8 100644 --- a/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ForwardProxyTLSServerTest.java +++ b/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ForwardProxyTLSServerTest.java @@ -251,12 +251,13 @@ public class ForwardProxyTLSServerTest assertEquals(body, content); content = "body=" + body; + int contentLength = content.length(); ContentResponse response2 = httpClient.newRequest("localhost", serverConnector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) .method(HttpMethod.POST) .path("/echo") - .header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString()) - .header(HttpHeader.CONTENT_LENGTH, String.valueOf(content.length())) + .headers(headers -> headers.put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())) + .headers(headers -> headers.put(HttpHeader.CONTENT_LENGTH, String.valueOf(contentLength))) .body(new StringRequestContent(content)) .timeout(5, TimeUnit.SECONDS) .send(); @@ -318,8 +319,8 @@ public class ForwardProxyTLSServerTest .scheme(HttpScheme.HTTPS.asString()) .method(HttpMethod.POST) .path("/echo") - .header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString()) - .header(HttpHeader.CONTENT_LENGTH, String.valueOf(body2.length())) + .headers(headers -> headers.put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())) + .headers(headers -> headers.put(HttpHeader.CONTENT_LENGTH, String.valueOf(body2.length()))) .body(new StringRequestContent(body2)); // Make sure the second connection can send the exchange via the tunnel diff --git a/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ProxyServletTest.java b/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ProxyServletTest.java index d39e94d9457..e944ec8c51b 100644 --- a/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ProxyServletTest.java +++ b/jetty-proxy/src/test/java/org/eclipse/jetty/proxy/ProxyServletTest.java @@ -988,7 +988,7 @@ public class ProxyServletTest String value1 = "1"; ContentResponse response1 = client.newRequest("localhost", serverConnector.getLocalPort()) - .header(name, value1) + .headers(headers -> headers.put(name, value1)) .timeout(5, TimeUnit.SECONDS) .send(); assertEquals(200, response1.getStatus()); @@ -1003,7 +1003,7 @@ public class ProxyServletTest { String value2 = "2"; ContentResponse response2 = client2.newRequest("localhost", serverConnector.getLocalPort()) - .header(name, value2) + .headers(headers -> headers.put(name, value2)) .timeout(5, TimeUnit.SECONDS) .send(); assertEquals(200, response2.getStatus()); @@ -1236,10 +1236,7 @@ public class ProxyServletTest startClient(); Request request = client.newRequest("localhost", serverConnector.getLocalPort()); - for (Map.Entry entry : hopHeaders.entrySet()) - { - request.header(entry.getKey(), entry.getValue()); - } + hopHeaders.forEach((key, value) -> request.headers(headers -> headers.add(key, value))); ContentResponse response = request .timeout(5, TimeUnit.SECONDS) .send(); @@ -1283,7 +1280,7 @@ public class ProxyServletTest CountDownLatch contentLatch = new CountDownLatch(1); CountDownLatch clientLatch = new CountDownLatch(1); client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString())) .body(new BytesRequestContent(content)) .onRequestContent((request, buffer) -> contentLatch.countDown()) .send(new BufferingResponseListener() @@ -1340,7 +1337,7 @@ public class ProxyServletTest requestContent.offer(ByteBuffer.wrap(content, 0, chunk1)); CountDownLatch clientLatch = new CountDownLatch(1); client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString())) .body(requestContent) .send(new BufferingResponseListener() { @@ -1400,7 +1397,7 @@ public class ProxyServletTest requestContent.offer(ByteBuffer.wrap(content, 0, chunk1)); CountDownLatch clientLatch = new CountDownLatch(1); client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString())) .body(requestContent) .send(result -> { @@ -1448,7 +1445,7 @@ public class ProxyServletTest CountDownLatch contentLatch = new CountDownLatch(1); CountDownLatch clientLatch = new CountDownLatch(1); client.newRequest("localhost", serverConnector.getLocalPort()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString())) .body(new BytesRequestContent(content)) .onRequestContent((request, buffer) -> contentLatch.countDown()) .send(result -> diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/FormTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/FormTest.java index f6789252dbc..820b5d62dac 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/FormTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/FormTest.java @@ -136,7 +136,7 @@ public class FormTest ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .method(HttpMethod.POST) .path(contextPath + servletPath) - .header(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString()) + .headers(headers -> headers.put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.FORM_ENCODED.asString())) .body(content) .onRequestBegin(request -> { diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/GzipHandlerBreakEvenSizeTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/GzipHandlerBreakEvenSizeTest.java index 2f6609016a5..2739bbe77d7 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/GzipHandlerBreakEvenSizeTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/GzipHandlerBreakEvenSizeTest.java @@ -29,6 +29,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.gzip.GzipHandler; @@ -85,7 +86,7 @@ public class GzipHandlerBreakEvenSizeTest { URI uri = server.getURI().resolve("/content?size=" + size); ContentResponse response = client.newRequest(uri) - .header(HttpHeader.ACCEPT_ENCODING, "gzip") + .headers(headers -> headers.put(HttpHeader.ACCEPT_ENCODING, HttpHeaderValue.GZIP)) .send(); assertThat("Status Code", response.getStatus(), is(200)); diff --git a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP.java b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP.java index 0e21f6104a2..54048a41692 100644 --- a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP.java +++ b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP.java @@ -54,16 +54,17 @@ public class HttpUpgraderOverHTTP implements HttpUpgrader public void prepare(HttpRequest request) { request.method(HttpMethod.GET).version(HttpVersion.HTTP_1_1) - .add(WS_VERSION_FIELD) - .add(WS_UPGRADE_FIELD) - .add(WS_CONNECTION_FIELD) - .header(HttpHeader.SEC_WEBSOCKET_KEY, generateRandomKey()) - // Per the hybi list: Add no-cache headers to avoid compatibility issue. - // There are some proxies that rewrite "Connection: upgrade" to - // "Connection: close" in the response if a request doesn't contain - // these headers. - .add(PRAGMA_NO_CACHE_FIELD) - .add(CACHE_CONTROL_NO_CACHE_FIELD); + .headers(headers -> headers + .put(WS_VERSION_FIELD) + .put(WS_UPGRADE_FIELD) + .put(WS_CONNECTION_FIELD) + .put(HttpHeader.SEC_WEBSOCKET_KEY, generateRandomKey()) + // Per the hybi list: Add no-cache headers to avoid compatibility issue. + // There are some proxies that rewrite "Connection: upgrade" to + // "Connection: close" in the response if a request doesn't contain + // these headers. + .put(PRAGMA_NO_CACHE_FIELD) + .put(CACHE_CONTROL_NO_CACHE_FIELD)); // Notify the UpgradeListeners now the headers are set. clientUpgradeRequest.requestComplete(); diff --git a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP2.java b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP2.java index e1904a0b419..422e4a14187 100644 --- a/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP2.java +++ b/jetty-websocket/websocket-core/src/main/java/org/eclipse/jetty/websocket/core/client/HttpUpgraderOverHTTP2.java @@ -41,9 +41,9 @@ public class HttpUpgraderOverHTTP2 implements HttpUpgrader @Override public void prepare(HttpRequest request) { - request.method(HttpMethod.CONNECT); - request.upgradeProtocol("websocket"); - request.add(WS_VERSION_FIELD); + request.upgradeProtocol("websocket") + .method(HttpMethod.CONNECT) + .headers(headers -> headers.put(WS_VERSION_FIELD)); // Notify the UpgradeListeners now the headers are set. clientUpgradeRequest.requestComplete(); diff --git a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/WebSocketNegotiationTest.java b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/WebSocketNegotiationTest.java index 4cee6345c71..ae25d7bbe94 100644 --- a/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/WebSocketNegotiationTest.java +++ b/jetty-websocket/websocket-core/src/test/java/org/eclipse/jetty/websocket/core/WebSocketNegotiationTest.java @@ -387,7 +387,7 @@ public class WebSocketNegotiationTest extends WebSocketTester @Override public void onHandshakeRequest(HttpRequest request) { - request.header(HttpHeader.SEC_WEBSOCKET_EXTENSIONS, "permessage-deflate"); + request.headers(headers -> headers.put(HttpHeader.SEC_WEBSOCKET_EXTENSIONS, "permessage-deflate")); } @Override diff --git a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/ConfiguratorTest.java b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/ConfiguratorTest.java index 573ccd47b3c..82f3fd3f76c 100644 --- a/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/ConfiguratorTest.java +++ b/jetty-websocket/websocket-javax-tests/src/test/java/org/eclipse/jetty/websocket/javax/tests/server/ConfiguratorTest.java @@ -115,7 +115,7 @@ public class ConfiguratorTest else { return "negotiatedExtensions=" + negotiatedExtensions.stream() - .map((ext) -> ext.getName()) + .map(Extension::getName) .collect(Collectors.joining(",", "[", "]")); } } @@ -198,7 +198,7 @@ public class ConfiguratorTest public static class UniqueUserPropsConfigurator extends ServerEndpointConfig.Configurator { - private AtomicInteger upgradeCount = new AtomicInteger(0); + private final AtomicInteger upgradeCount = new AtomicInteger(0); @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) @@ -479,7 +479,7 @@ public class ConfiguratorTest FrameHandlerTracker clientSocket = new FrameHandlerTracker(); ClientUpgradeRequest upgradeRequest = ClientUpgradeRequest.from(client, wsUri, clientSocket); - upgradeRequest.header("X-Dummy", "Bogus"); + upgradeRequest.headers(headers -> headers.put("X-Dummy", "Bogus")); Future clientConnectFuture = client.connect(upgradeRequest); CoreSession coreSession = clientConnectFuture.get(Timeouts.CONNECT_MS, TimeUnit.MILLISECONDS); diff --git a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/AsyncIOServletTest.java b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/AsyncIOServletTest.java index 38eabbc25e0..f2239a533b9 100644 --- a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/AsyncIOServletTest.java +++ b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/AsyncIOServletTest.java @@ -56,6 +56,7 @@ import org.eclipse.jetty.client.util.BufferingResponseListener; import org.eclipse.jetty.client.util.InputStreamRequestContent; import org.eclipse.jetty.client.util.StringRequestContent; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http2.HTTP2Session; @@ -629,7 +630,7 @@ public class AsyncIOServletTest extends AbstractTest headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .body(new StringRequestContent(text)) .timeout(5, TimeUnit.SECONDS) .send(); @@ -895,7 +896,7 @@ public class AsyncIOServletTest extends AbstractTest headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .body(new StringRequestContent("XYZ")) .timeout(5, TimeUnit.SECONDS) .send(); @@ -951,7 +952,7 @@ public class AsyncIOServletTest extends AbstractTest headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .timeout(5, TimeUnit.SECONDS) .send(); diff --git a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/ConnectionStatisticsTest.java b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/ConnectionStatisticsTest.java index 47e3c28b362..2a4b3c508f7 100644 --- a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/ConnectionStatisticsTest.java +++ b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/ConnectionStatisticsTest.java @@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.util.BytesRequestContent; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.ConnectionStatistics; @@ -101,7 +102,7 @@ public class ConnectionStatisticsTest extends AbstractTest byte[] content = new byte[3072]; long contentLength = content.length; ContentResponse response = scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .body(new BytesRequestContent(content)) .timeout(5, TimeUnit.SECONDS) .send(); diff --git a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientContinueTest.java b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientContinueTest.java index 1fd46c84b6d..53e4f9ae8f8 100644 --- a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientContinueTest.java +++ b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientContinueTest.java @@ -103,7 +103,7 @@ public class HttpClientContinueTest extends AbstractTest }); ContentResponse response = scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(contents)) .timeout(5, TimeUnit.SECONDS) .send(); @@ -144,7 +144,7 @@ public class HttpClientContinueTest extends AbstractTest byte[] content1 = new byte[10240]; byte[] content2 = new byte[16384]; ContentResponse response = scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content1, content2) { @Override @@ -202,7 +202,7 @@ public class HttpClientContinueTest extends AbstractTest byte[] content2 = new byte[16384]; CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content1, content2)) .send(new BufferingResponseListener() { @@ -254,7 +254,7 @@ public class HttpClientContinueTest extends AbstractTest scenario.client.newRequest(scenario.newURI()) .method(HttpMethod.POST) .path("/continue") - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content)) .send(new BufferingResponseListener() { @@ -304,7 +304,7 @@ public class HttpClientContinueTest extends AbstractTest scenario.client.newRequest(scenario.newURI()) .method(HttpMethod.POST) .path("/redirect") - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content)) .send(new BufferingResponseListener() { @@ -351,7 +351,7 @@ public class HttpClientContinueTest extends AbstractTest byte[] content = new byte[1024]; CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content)) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .send(new BufferingResponseListener() @@ -400,7 +400,7 @@ public class HttpClientContinueTest extends AbstractTest byte[] content = new byte[1024]; CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content)) .send(new BufferingResponseListener() { @@ -460,7 +460,7 @@ public class HttpClientContinueTest extends AbstractTest byte[] content = new byte[1024]; CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(content)) .send(new BufferingResponseListener() { @@ -504,7 +504,7 @@ public class HttpClientContinueTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); AsyncRequestContent content = new AsyncRequestContent(); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(content) .send(new BufferingResponseListener() { @@ -555,7 +555,7 @@ public class HttpClientContinueTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); AsyncRequestContent content = new AsyncRequestContent(ByteBuffer.wrap(chunk1)); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(content) .send(new BufferingResponseListener() { @@ -596,7 +596,7 @@ public class HttpClientContinueTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .onRequestHeaders(request -> { content.offer(ByteBuffer.wrap(data)); @@ -660,7 +660,7 @@ public class HttpClientContinueTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest(scenario.newURI()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(content) .send(new BufferingResponseListener() { @@ -694,7 +694,7 @@ public class HttpClientContinueTest extends AbstractTest CountDownLatch latch = new CountDownLatch(1); scenario.client.newRequest("localhost", server.getLocalPort()) - .header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()) + .headers(headers -> headers.put(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE)) .body(new BytesRequestContent(new byte[]{0})) .send(result -> { diff --git a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientLoadTest.java b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientLoadTest.java index f25ef0fa80f..f03b5570f11 100644 --- a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientLoadTest.java +++ b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientLoadTest.java @@ -43,6 +43,7 @@ import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.client.util.BytesRequestContent; import org.eclipse.jetty.fcgi.client.http.HttpClientTransportOverFCGI; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.io.ByteBufferPool; @@ -224,23 +225,23 @@ public class HttpClientLoadTest extends AbstractTest headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)); else if (serverClose) - request.header("X-Close", "true"); + request.headers(headers -> headers.put("X-Close", "true")); if (clientTimeout > 0) { - request.header("X-Timeout", String.valueOf(clientTimeout)); + request.headers(headers -> headers.put("X-Timeout", String.valueOf(clientTimeout))); request.idleTimeout(clientTimeout, TimeUnit.MILLISECONDS); } switch (method) { case "GET": - request.header("X-Download", String.valueOf(contentLength)); + request.headers(headers -> headers.put("X-Download", String.valueOf(contentLength))); break; case "POST": - request.header("X-Upload", String.valueOf(contentLength)); + request.headers(headers -> headers.put("X-Upload", String.valueOf(contentLength))); request.body(new BytesRequestContent(new byte[contentLength])); break; } diff --git a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTest.java b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTest.java index f1e679e9aa7..a48de6bbf96 100644 --- a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTest.java +++ b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTest.java @@ -619,7 +619,7 @@ public class HttpClientTest extends AbstractTest ContentResponse response = scenario.client.newRequest(scenario.newURI()) .method(HttpMethod.HEAD) .path(scenario.servletPath) - .header(HttpHeader.ACCEPT, "*/*") + .headers(headers -> headers.put(HttpHeader.ACCEPT, "*/*")) .send(); assertEquals(status, response.getStatus()); diff --git a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTransportDynamicTest.java b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTransportDynamicTest.java index 4ce25b5eb2e..01b8d14eda6 100644 --- a/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTransportDynamicTest.java +++ b/tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/HttpClientTransportDynamicTest.java @@ -515,9 +515,10 @@ public class HttpClientTransportDynamicTest // Make an upgrade request from HTTP/1.1 to H2C. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.HTTP2_SETTINGS, "") - .header(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings") + .headers(headers -> headers + .put(HttpHeader.UPGRADE, "h2c") + .put(HttpHeader.HTTP2_SETTINGS, "") + .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) .timeout(5, TimeUnit.SECONDS) .send(); @@ -595,9 +596,10 @@ public class HttpClientTransportDynamicTest // Make an upgrade request from HTTP/1.1 to H2C. int serverPort = proxyPort + 1; // Any port will do. ContentResponse response = client.newRequest("localhost", serverPort) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.HTTP2_SETTINGS, "") - .header(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings") + .headers(headers -> headers + .put(HttpHeader.UPGRADE, "h2c") + .put(HttpHeader.HTTP2_SETTINGS, "") + .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) .timeout(5, TimeUnit.SECONDS) .send(); @@ -628,9 +630,10 @@ public class HttpClientTransportDynamicTest // Make an upgrade request from HTTP/1.1 to H2C. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.HTTP2_SETTINGS, "") - .header(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings") + .headers(headers -> headers + .put(HttpHeader.UPGRADE, "h2c") + .put(HttpHeader.HTTP2_SETTINGS, "") + .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) .timeout(5, TimeUnit.SECONDS) .send(); @@ -665,9 +668,10 @@ public class HttpClientTransportDynamicTest CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) .method(HttpMethod.POST) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.HTTP2_SETTINGS, "") - .header(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings") + .headers(headers -> headers + .put(HttpHeader.UPGRADE, "h2c") + .put(HttpHeader.HTTP2_SETTINGS, "") + .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) .body(new BytesRequestContent(bytes)) .timeout(5, TimeUnit.SECONDS) .send(new BufferingResponseListener(bytes.length) @@ -698,8 +702,8 @@ public class HttpClientTransportDynamicTest // The upgrade request is missing the required HTTP2-Settings header. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.CONNECTION, "Upgrade") + .headers(headers -> headers.add(HttpHeader.UPGRADE, "h2c")) + .headers(headers -> headers.add(HttpHeader.CONNECTION, "Upgrade")) .timeout(5, TimeUnit.SECONDS) .send(); @@ -725,9 +729,10 @@ public class HttpClientTransportDynamicTest // Make an upgrade request from HTTP/1.1 to H2C. CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .header(HttpHeader.UPGRADE, "h2c") - .header(HttpHeader.HTTP2_SETTINGS, "") - .header(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings") + .headers(headers -> headers + .put(HttpHeader.UPGRADE, "h2c") + .put(HttpHeader.HTTP2_SETTINGS, "") + .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) .send(result -> { if (result.isFailed()) diff --git a/tests/test-integration/src/test/java/org/eclipse/jetty/test/FailedSelectorTest.java b/tests/test-integration/src/test/java/org/eclipse/jetty/test/FailedSelectorTest.java index a1aa817edd3..6aaa535a18e 100644 --- a/tests/test-integration/src/test/java/org/eclipse/jetty/test/FailedSelectorTest.java +++ b/tests/test-integration/src/test/java/org/eclipse/jetty/test/FailedSelectorTest.java @@ -42,6 +42,7 @@ import org.eclipse.jetty.client.HttpClientTransport; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.io.EndPoint; @@ -180,7 +181,7 @@ public class FailedSelectorTest ContentResponse response = client.newRequest(dest) .method(HttpMethod.GET) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .send(); assertThat(dest + " status", response.getStatus(), is(HttpStatus.OK_200)); @@ -193,7 +194,7 @@ public class FailedSelectorTest LOG.info("Requesting GET on {}", dest); ContentResponse response = client.newRequest(dest) .method(HttpMethod.GET) - .header(HttpHeader.CONNECTION, "close") + .headers(headers -> headers.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE)) .send(); assertThat(dest + " status", response.getStatus(), is(HttpStatus.OK_200)); diff --git a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionMigrationTest.java b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionMigrationTest.java index 96131d3edc6..361fd148efa 100644 --- a/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionMigrationTest.java +++ b/tests/test-sessions/test-jdbc-sessions/src/test/java/org/eclipse/jetty/server/session/ClusteredSessionMigrationTest.java @@ -20,7 +20,6 @@ package org.eclipse.jetty.server.session; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -29,11 +28,12 @@ import javax.servlet.http.HttpSession; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * ClusteredSessionMigrationTest @@ -106,14 +106,15 @@ public class ClusteredSessionMigrationTest extends AbstractTestBase ContentResponse response1 = request1.send(); assertEquals(HttpServletResponse.SC_OK, response1.getStatus()); String sessionCookie = response1.getHeaders().get("Set-Cookie"); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); // Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); + sessionCookie = sessionCookie.replaceFirst("(\\W)([Pp])ath=", "$1\\$Path="); // Perform a request to server2 using the session cookie from the previous request // This should migrate the session from server1 to server2. Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping.substring(1) + "?action=get"); - request2.header("Cookie", sessionCookie); + HttpField cookie = new HttpField("Cookie", sessionCookie); + request2.headers(headers -> headers.put(cookie)); ContentResponse response2 = request2.send(); assertEquals(HttpServletResponse.SC_OK, response2.getStatus()); } @@ -140,13 +141,13 @@ public class ClusteredSessionMigrationTest extends AbstractTestBase private static long createTime = 0; @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(false); diff --git a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/AttributeNameTest.java b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/AttributeNameTest.java index 1d545059ea7..9b641c11ac4 100644 --- a/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/AttributeNameTest.java +++ b/tests/test-sessions/test-mongodb-sessions/src/test/java/org/eclipse/jetty/nosql/mongodb/AttributeNameTest.java @@ -21,7 +21,6 @@ package org.eclipse.jetty.nosql.mongodb; import java.io.IOException; import java.io.PrintWriter; import java.util.concurrent.TimeUnit; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -29,6 +28,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.server.session.DefaultSessionCacheFactory; import org.eclipse.jetty.server.session.Session; @@ -40,7 +40,6 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; /** * AttributeNameTest @@ -109,14 +108,15 @@ public class AttributeNameTest String sessionCookie = response.getHeaders().get(HttpHeader.SET_COOKIE); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); //Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); + sessionCookie = sessionCookie.replaceFirst("(\\W)([Pp])ath=", "$1\\$Path="); //Make a request to the 2nd server which will do a refresh, use TestServlet to ensure that the //session attribute with dotted name is not removed Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get"); - request2.header("Cookie", sessionCookie); + HttpField cookie = new HttpField("Cookie", sessionCookie); + request2.headers(headers -> headers.put(cookie)); ContentResponse response2 = request2.send(); assertEquals(HttpServletResponse.SC_OK, response2.getStatus()); } @@ -135,7 +135,7 @@ public class AttributeNameTest public static class TestServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException + protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws IOException { String action = request.getParameter("action"); if ("init".equals(action)) diff --git a/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractClusteredOrphanedSessionTest.java b/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractClusteredOrphanedSessionTest.java index 521086eb56d..c0bc2578da5 100644 --- a/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractClusteredOrphanedSessionTest.java +++ b/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractClusteredOrphanedSessionTest.java @@ -29,10 +29,12 @@ import javax.servlet.http.HttpSession; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * AbstractClusteredOrphanedSessionTest @@ -90,9 +92,9 @@ public abstract class AbstractClusteredOrphanedSessionTest extends AbstractTestB ContentResponse response1 = client.GET("http://localhost:" + port1 + contextPath + servletMapping.substring(1) + "?action=init"); assertEquals(HttpServletResponse.SC_OK, response1.getStatus()); String sessionCookie = response1.getHeaders().get("Set-Cookie"); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); // Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); + sessionCookie = sessionCookie.replaceFirst("(\\W)([Pp])ath=", "$1\\$Path="); // Wait for the session to expire. // The first node does not do any scavenging, but the session @@ -101,7 +103,8 @@ public abstract class AbstractClusteredOrphanedSessionTest extends AbstractTestB // Perform one request to server2 to be sure that the session has been expired Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping.substring(1) + "?action=check"); - request.header("Cookie", sessionCookie); + HttpField cookie = new HttpField("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); ContentResponse response2 = request.send(); assertEquals(HttpServletResponse.SC_OK, response2.getStatus()); } @@ -141,7 +144,7 @@ public abstract class AbstractClusteredOrphanedSessionTest extends AbstractTestB else if ("check".equals(action)) { HttpSession session = request.getSession(false); - assertTrue(session == null); + assertNull(session); } } } diff --git a/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractWebAppObjectInSessionTest.java b/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractWebAppObjectInSessionTest.java index dbe70cce2c1..84302679316 100644 --- a/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractWebAppObjectInSessionTest.java +++ b/tests/test-sessions/test-sessions-common/src/main/java/org/eclipse/jetty/server/session/AbstractWebAppObjectInSessionTest.java @@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.resource.Resource; @@ -35,7 +36,7 @@ import org.eclipse.jetty.webapp.WebAppContext; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * AbstractWebAppObjectInSessionTest @@ -133,9 +134,9 @@ public abstract class AbstractWebAppObjectInSessionTest extends AbstractTestBase ContentResponse response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String sessionCookie = response.getHeaders().get("Set-Cookie"); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); // Mangle the cookie, replacing Path with $Path, etc. - sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); + sessionCookie = sessionCookie.replaceFirst("(\\W)([Pp])ath=", "$1\\$Path="); //ensure request has finished being handled synchronizer.await(5, TimeUnit.SECONDS); @@ -143,7 +144,8 @@ public abstract class AbstractWebAppObjectInSessionTest extends AbstractTestBase // Perform a request to server2 using the session cookie from the previous request Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get"); request2.method(HttpMethod.GET); - request2.header("Cookie", sessionCookie); + HttpField cookie = new HttpField("Cookie", sessionCookie); + request2.headers(headers -> headers.put(cookie)); ContentResponse response2 = request2.send(); assertEquals(HttpServletResponse.SC_OK, response2.getStatus()); diff --git a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/ClientCrossContextSessionTest.java b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/ClientCrossContextSessionTest.java index f6a6c6458ed..72473677ff7 100644 --- a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/ClientCrossContextSessionTest.java +++ b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/ClientCrossContextSessionTest.java @@ -28,12 +28,14 @@ import javax.servlet.http.HttpSession; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * ClientCrossContextSessionTest @@ -81,12 +83,13 @@ public class ClientCrossContextSessionTest assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String sessionCookie = response.getHeaders().get("Set-Cookie"); - assertTrue(sessionCookie != null); + assertNotNull(sessionCookie); String sessionId = TestServer.extractSessionId(sessionCookie); // Perform a request to contextB with the same session cookie Request request = client.newRequest("http://localhost:" + port + contextB + servletMapping); - request.header("Cookie", "JSESSIONID=" + sessionId); + HttpField cookie = new HttpField("Cookie", "JSESSIONID=" + sessionId); + request.headers(headers -> headers.put(cookie)); ContentResponse responseB = request.send(); assertEquals(HttpServletResponse.SC_OK, responseB.getStatus()); assertEquals(servletA.sessionId, servletB.sessionId); @@ -122,7 +125,7 @@ public class ClientCrossContextSessionTest // Check that we don't see things put in session by contextB Object objectB = session.getAttribute("B"); - assertTrue(objectB == null); + assertNull(objectB); } } @@ -145,7 +148,7 @@ public class ClientCrossContextSessionTest // Check that we don't see things put in session by contextA Object objectA = session.getAttribute("A"); - assertTrue(objectA == null); + assertNull(objectA); } } } diff --git a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java index 02c1e3edeee..9673fbd094e 100644 --- a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java +++ b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DeleteUnloadableSessionTest.java @@ -31,6 +31,7 @@ import javax.servlet.http.HttpSession; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.logging.StacklessLogging; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; @@ -45,14 +46,11 @@ import static org.junit.jupiter.api.Assertions.assertNull; */ public class DeleteUnloadableSessionTest { - /** * DelSessionDataStore */ public static class DelSessionDataStore extends AbstractSessionDataStore { - int count = 0; - Object o = new Object(); String unloadableId = null; @@ -64,7 +62,7 @@ public class DeleteUnloadableSessionTest } @Override - public boolean exists(String id) throws Exception + public boolean exists(String id) { return o != null; } @@ -77,7 +75,7 @@ public class DeleteUnloadableSessionTest } @Override - public boolean delete(String id) throws Exception + public boolean delete(String id) { if (id.equals(unloadableId)) { @@ -88,7 +86,7 @@ public class DeleteUnloadableSessionTest } @Override - public void doStore(String id, SessionData data, long lastSaveTime) throws Exception + public void doStore(String id, SessionData data, long lastSaveTime) { //pretend it was saved } @@ -102,9 +100,8 @@ public class DeleteUnloadableSessionTest public static class DelSessionDataStoreFactory extends AbstractSessionDataStoreFactory { - @Override - public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception + public SessionDataStore getSessionDataStore(SessionHandler handler) { return new DelSessionDataStore(); } @@ -141,8 +138,8 @@ public class DeleteUnloadableSessionTest DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory(); cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT); cacheFactory.setRemoveUnloadableSessions(true); - SessionDataStoreFactory storeFactory = new DelSessionDataStoreFactory(); - ((AbstractSessionDataStoreFactory)storeFactory).setGracePeriodSec(scavengePeriod); + AbstractSessionDataStoreFactory storeFactory = new DelSessionDataStoreFactory(); + storeFactory.setGracePeriodSec(scavengePeriod); TestServer server = new TestServer(0, inactivePeriod, scavengePeriod, cacheFactory, storeFactory); ServletContextHandler context = server.addContext(contextPath); @@ -154,7 +151,7 @@ public class DeleteUnloadableSessionTest ServletHolder holder = new ServletHolder(servlet); context.addServlet(holder, servletMapping); - try (StacklessLogging stackless = new StacklessLogging(DeleteUnloadableSessionTest.class.getPackage())) + try (StacklessLogging ignored = new StacklessLogging(DeleteUnloadableSessionTest.class.getPackage())) { server.start(); int port = server.getPort(); @@ -166,7 +163,8 @@ public class DeleteUnloadableSessionTest scopeListener.setExitSynchronizer(latch); String sessionCookie = "JSESSIONID=w0rm3zxpa6h1zg1mevtv76b3te00.w0;$Path=/"; Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=test"); - request.header("Cookie", sessionCookie); + HttpField cookie = new HttpField("Cookie", sessionCookie); + request.headers(headers -> headers.put(cookie)); ContentResponse response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); diff --git a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DuplicateCookieTest.java b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DuplicateCookieTest.java index a254d2fe3cd..e6513c376ec 100644 --- a/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DuplicateCookieTest.java +++ b/tests/test-sessions/test-sessions-common/src/test/java/org/eclipse/jetty/server/session/DuplicateCookieTest.java @@ -61,7 +61,7 @@ public class DuplicateCookieTest server1.start(); int port1 = server1.getPort(); - try (StacklessLogging stackless = new StacklessLogging(DuplicateCookieTest.class.getPackage())) + try (StacklessLogging ignored = new StacklessLogging(DuplicateCookieTest.class.getPackage())) { //create a valid session createUnExpiredSession(contextHandler.getSessionHandler().getSessionCache(), @@ -73,8 +73,8 @@ public class DuplicateCookieTest //make a request with another session cookie in there that does not exist Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=check"); - request.header("Cookie", "JSESSIONID=123"); //doesn't exist - request.header("Cookie", "JSESSIONID=4422"); //does exist + request.headers(headers -> headers.add("Cookie", "JSESSIONID=123")); //doesn't exist + request.headers(headers -> headers.add("Cookie", "JSESSIONID=4422")); //does exist ContentResponse response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); assertEquals("4422", response.getContentAsString()); @@ -104,7 +104,7 @@ public class DuplicateCookieTest server1.start(); int port1 = server1.getPort(); - try (StacklessLogging stackless = new StacklessLogging(DuplicateCookieTest.class.getPackage())) + try (StacklessLogging ignored = new StacklessLogging(DuplicateCookieTest.class.getPackage())) { //create a valid session createUnExpiredSession(contextHandler.getSessionHandler().getSessionCache(), @@ -120,8 +120,8 @@ public class DuplicateCookieTest //make a request with another session cookie in there that is not valid Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=check"); - request.header("Cookie", "JSESSIONID=1122"); //is valid - request.header("Cookie", "JSESSIONID=2233"); //is invalid + request.headers(headers -> headers.add("Cookie", "JSESSIONID=1122")); //is valid + request.headers(headers -> headers.add("Cookie", "JSESSIONID=2233")); //is invalid ContentResponse response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); assertEquals("1122", response.getContentAsString()); @@ -151,7 +151,7 @@ public class DuplicateCookieTest server1.start(); int port1 = server1.getPort(); - try (StacklessLogging stackless = new StacklessLogging(DuplicateCookieTest.class.getPackage())) + try (StacklessLogging ignored = new StacklessLogging(DuplicateCookieTest.class.getPackage())) { //create some of unexpired sessions createUnExpiredSession(contextHandler.getSessionHandler().getSessionCache(), @@ -169,8 +169,8 @@ public class DuplicateCookieTest //make a request with multiple valid session ids Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=check"); - request.header("Cookie", "JSESSIONID=1234"); - request.header("Cookie", "JSESSIONID=5678"); + request.headers(headers -> headers.add("Cookie", "JSESSIONID=1234")); + request.headers(headers -> headers.add("Cookie", "JSESSIONID=5678")); ContentResponse response = request.send(); assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); } From a93b2c608470ecb2853fdc8417ae54b5424268f6 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Tue, 5 May 2020 14:48:36 +0200 Subject: [PATCH 2/3] Fixes #4808 - Review HttpClient Request header APIs. Fixed test failures. Signed-off-by: Simone Bordet --- .../main/java/org/eclipse/jetty/client/HttpResponse.java | 2 +- .../org/eclipse/jetty/proxy/AbstractProxyServlet.java | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java index 28c0dcf0df6..012cd425b5d 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java @@ -118,7 +118,7 @@ public class HttpResponse implements Response public HttpFields getTrailers() { - return trailers.asImmutable(); + return trailers == null ? null : trailers.asImmutable(); } public HttpResponse trailer(HttpField trailer) diff --git a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java index 4f2c8a74960..8e5669e1a26 100644 --- a/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java +++ b/jetty-proxy/src/main/java/org/eclipse/jetty/proxy/AbstractProxyServlet.java @@ -538,8 +538,12 @@ public abstract class AbstractProxyServlet extends HttpServlet { proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_FOR, clientRequest.getRemoteAddr())); proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_PROTO, clientRequest.getScheme())); - proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_HOST, clientRequest.getHeader(HttpHeader.HOST.asString()))); - proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_SERVER, clientRequest.getLocalName())); + String hostHeader = clientRequest.getHeader(HttpHeader.HOST.asString()); + if (hostHeader != null) + proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_HOST, hostHeader)); + String localName = clientRequest.getLocalName(); + if (localName != null) + proxyRequest.headers(headers -> headers.add(HttpHeader.X_FORWARDED_SERVER, localName)); } protected void sendProxyRequest(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest) From b6c6684c70cee4cb45361fa3d61852370ae4a743 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Fri, 8 May 2020 17:52:27 +0200 Subject: [PATCH 3/3] Fixes #4808 - Review HttpClient Request header APIs. Updates after review. Signed-off-by: Simone Bordet --- .../main/java/org/eclipse/jetty/client/HttpClient.java | 2 +- .../java/org/eclipse/jetty/client/HttpConnection.java | 8 ++++---- .../main/java/org/eclipse/jetty/client/HttpReceiver.java | 2 +- .../main/java/org/eclipse/jetty/client/HttpRequest.java | 4 +++- .../main/java/org/eclipse/jetty/client/HttpResponse.java | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java index a662c16bbb1..51939e50163 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpClient.java @@ -472,7 +472,7 @@ public class HttpClient extends ContainerLifeCycle continue; if (!newRequest.getHeaders().contains(field)) - newRequest.header(field); + newRequest.addHeader(field); } return newRequest; } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java index 3546ce7192f..f603d9978f4 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java @@ -153,7 +153,7 @@ public abstract class HttpConnection implements IConnection if (version.getVersion() <= 11) { if (!headers.contains(HttpHeader.HOST)) - request.header(getHttpDestination().getHostField()); + request.addHeader(getHttpDestination().getHostField()); } // Add content headers @@ -172,14 +172,14 @@ public abstract class HttpConnection implements IConnection if (contentType != null) { HttpField field = new HttpField(HttpHeader.CONTENT_TYPE, contentType); - request.header(field); + request.addHeader(field); } } long contentLength = content.getLength(); if (contentLength >= 0) { if (!headers.contains(HttpHeader.CONTENT_LENGTH)) - request.header(new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH, contentLength)); + request.addHeader(new HttpField.LongValueHttpField(HttpHeader.CONTENT_LENGTH, contentLength)); } } @@ -194,7 +194,7 @@ public abstract class HttpConnection implements IConnection if (cookies != null) { HttpField cookieField = new HttpField(HttpHeader.COOKIE, cookies.toString()); - request.header(cookieField); + request.addHeader(cookieField); } } diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java index 937e4e3679c..85fe08b44d6 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java @@ -242,7 +242,7 @@ public abstract class HttpReceiver boolean process = notifier.notifyHeader(exchange.getConversation().getResponseListeners(), response, field); if (process) { - response.header(field); + response.addHeader(field); HttpHeader fieldHeader = field.getHeader(); if (fieldHeader != null) { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java index 30c9eb9b113..c6c329d2507 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpRequest.java @@ -307,6 +307,7 @@ public class HttpRequest implements Request } @Override + @Deprecated public Request header(String name, String value) { if (value == null) @@ -317,6 +318,7 @@ public class HttpRequest implements Request } @Override + @Deprecated public Request header(HttpHeader header, String value) { if (value == null) @@ -382,7 +384,7 @@ public class HttpRequest implements Request return this; } - public HttpRequest header(HttpField header) + public HttpRequest addHeader(HttpField header) { headers.add(header); return this; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java index 012cd425b5d..0eca051d6a0 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpResponse.java @@ -92,7 +92,7 @@ public class HttpResponse implements Response return headers.asImmutable(); } - public HttpResponse header(HttpField header) + public HttpResponse addHeader(HttpField header) { headers.add(header); return this;