Skip to content

Commit

Permalink
Adapted to new HttpHeaders API
Browse files Browse the repository at this point in the history
  • Loading branch information
pderop committed Sep 14, 2022
1 parent 0060895 commit 7062ace
Show file tree
Hide file tree
Showing 34 changed files with 157 additions and 162 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ public class Application {
public static void main(String[] args) {
HttpClient client =
HttpClient.create()
.headers(h -> h.set(HttpHeaderNames.CONTENT_LENGTH, 5)); //<1>
.headers(h -> h.set(HttpHeaderNames.CONTENT_LENGTH, "5")); //<1>

client.post()
.uri("https://example.com/")
.send(BufferFlux.fromString(Mono.just("hello")))
.response()
.block();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ public static void main(String[] args) {
DisposableServer server =
HttpServer.create()
.forwarded((connectionInfo, request) -> { // <1>
String hostHeader = request.headers().get("X-Forwarded-Host");
CharSequence hostHeader = request.headers().get("X-Forwarded-Host");
if (hostHeader != null) {
String[] hosts = hostHeader.split(",", 2);
String[] hosts = hostHeader.toString().split(",", 2);
InetSocketAddress hostAddress = AddressUtils.createUnresolved(
hosts[hosts.length - 1].trim(),
connectionInfo.getHostAddress().getPort());
Expand All @@ -48,4 +48,4 @@ public static void main(String[] args) {
server.onDispose()
.block();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

import io.netty5.buffer.Buffer;
import io.netty5.buffer.BufferAllocator;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import io.netty5.util.Resource;
import io.netty5.channel.ChannelHandler;
import io.netty5.channel.CombinedChannelDuplexHandler;
Expand Down Expand Up @@ -229,12 +230,12 @@ public final NettyOutbound sendFile(Path file, long position, long count) {
if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage()) && !HttpUtil.isContentLengthSet(
outboundHttpMessage()) && count < Integer.MAX_VALUE) {
outboundHttpMessage().headers()
.setInt(HttpHeaderNames.CONTENT_LENGTH, (int) count);
.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(count));
}
else if (!HttpUtil.isContentLengthSet(outboundHttpMessage())) {
outboundHttpMessage().headers()
.remove(HttpHeaderNames.CONTENT_LENGTH)
.remove(HttpHeaderNames.TRANSFER_ENCODING);
HttpHeaders headers = outboundHttpMessage().headers();
headers.remove(HttpHeaderNames.CONTENT_LENGTH);
headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1358,7 +1358,7 @@ public final HttpClient wiretap(boolean enable) {
}

static boolean isCompressing(HttpHeaders h) {
return h.contains(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP, true);
return h.containsIgnoreCase(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
}

static String reactorNettyVersion() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import io.netty5.channel.ChannelInitializer;
import io.netty5.channel.ChannelOption;
import io.netty5.channel.ChannelPipeline;
import io.netty5.handler.codec.http.DefaultHttpHeaders;
import io.netty5.handler.codec.http.HttpClientCodec;
import io.netty5.handler.codec.http.HttpClientUpgradeHandler;
import io.netty5.handler.codec.http.HttpContentDecompressor;
Expand Down Expand Up @@ -327,7 +326,7 @@ public WebsocketClientSpec websocketClientSpec() {
this.cookieDecoder = ClientCookieDecoder.STRICT;
this.cookieEncoder = ClientCookieEncoder.STRICT;
this.decoder = new HttpResponseDecoderSpec();
this.headers = new DefaultHttpHeaders();
this.headers = HttpHeaders.newHeaders();
this.method = HttpMethod.GET;
this.protocols = new HttpProtocol[]{HttpProtocol.HTTP11};
this._protocols = h11;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -503,18 +503,19 @@ Publisher<Void> requestWithBody(HttpClientOperations ch) {
Consumer<HttpClientRequest> consumer = null;
if (fromURI != null && !toURI.equals(fromURI)) {
if (handler instanceof RedirectSendHandler) {
headers.remove(HttpHeaderNames.EXPECT)
.remove(HttpHeaderNames.COOKIE)
.remove(HttpHeaderNames.AUTHORIZATION)
.remove(HttpHeaderNames.PROXY_AUTHORIZATION);
headers.remove(HttpHeaderNames.EXPECT);
headers.remove(HttpHeaderNames.COOKIE);
headers.remove(HttpHeaderNames.AUTHORIZATION);
headers.remove(HttpHeaderNames.PROXY_AUTHORIZATION);
}
else {
consumer = request ->
request.requestHeaders()
.remove(HttpHeaderNames.EXPECT)
.remove(HttpHeaderNames.COOKIE)
.remove(HttpHeaderNames.AUTHORIZATION)
.remove(HttpHeaderNames.PROXY_AUTHORIZATION);
consumer = request -> {
HttpHeaders requestHeaders = request.requestHeaders();
requestHeaders.remove(HttpHeaderNames.EXPECT);
requestHeaders.remove(HttpHeaderNames.COOKIE);
requestHeaders.remove(HttpHeaderNames.AUTHORIZATION);
requestHeaders.remove(HttpHeaderNames.PROXY_AUTHORIZATION);
};
}
}
if (this.redirectRequestConsumer != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ public HttpClientRequest header(CharSequence name, CharSequence value) {
@Override
public HttpClientRequest headers(HttpHeaders headers) {
if (!hasSentHeaders()) {
String host = requestHeaders.get(HttpHeaderNames.HOST);
CharSequence host = requestHeaders.get(HttpHeaderNames.HOST);
this.requestHeaders.set(headers);
this.requestHeaders.set(HttpHeaderNames.HOST, host);
}
Expand Down Expand Up @@ -439,7 +439,7 @@ final URI websocketUri() {
uri = new URI(url);
}
else {
String host = requestHeaders().get(HttpHeaderNames.HOST);
CharSequence host = requestHeaders().get(HttpHeaderNames.HOST);
uri = new URI((isSecure ? HttpClient.WSS_SCHEME :
HttpClient.WS_SCHEME) + "://" + host + (url.startsWith("/") ? url : "/" + url));
}
Expand Down Expand Up @@ -598,8 +598,7 @@ protected void onInboundNext(ChannelHandlerContext ctx, Object msg) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Received response (auto-read:{}) : {}"),
channel().getOption(ChannelOption.AUTO_READ),
responseHeaders().entries()
.toString());
responseHeaders().toString());
}

if (notRedirected(response)) {
Expand Down Expand Up @@ -703,7 +702,6 @@ final boolean notRedirected(HttpResponse response) {
if (log.isDebugEnabled()) {
log.debug(format(channel(), "Received redirect location: {}"),
response.headers()
.entries()
.toString());
}
redirecting = new RedirectClientException(response.headers(), response.status());
Expand All @@ -716,7 +714,7 @@ final boolean notRedirected(HttpResponse response) {
protected HttpMessage newFullBodyMessage(Buffer body) {
HttpRequest request = new DefaultFullHttpRequest(version(), method(), uri(), body);

requestHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, body.readableBytes());
requestHeaders.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(body.readableBytes()));
requestHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);

request.headers()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import io.netty.contrib.handler.proxy.HttpProxyHandler;
import io.netty.contrib.handler.proxy.ProxyHandler;
import io.netty5.handler.codec.http.DefaultHttpHeaders;
import io.netty5.handler.codec.http.headers.HttpHeaders;
import reactor.netty5.transport.ProxyProvider;

Expand Down Expand Up @@ -103,10 +102,10 @@ public Build get() {
@Override
public Build httpHeaders(Consumer<HttpHeaders> headers) {
if (headers != null) {
this.httpHeaders = () -> new DefaultHttpHeaders() {
{
headers.accept(this);
}
this.httpHeaders = () -> {
HttpHeaders newHeaders = HttpHeaders.newHeaders();
headers.accept(newHeaders);
return newHeaders;
};
}
return get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ final class RedirectClientException extends RuntimeException {
final HttpResponseStatus status;

RedirectClientException(HttpHeaders headers, HttpResponseStatus status) {
location = Objects.requireNonNull(headers.get(HttpHeaderNames.LOCATION));
location = Objects.requireNonNull(headers.get(HttpHeaderNames.LOCATION)).toString();
this.status = Objects.requireNonNull(status);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,13 @@ final class WebsocketClientOperations extends HttpClientOperations
onCloseState = Sinks.unsafe().one();

String subprotocols = websocketClientSpec.protocols();
HttpHeaders replacedRequestHeaders = replaced.requestHeaders();
replacedRequestHeaders.remove(HttpHeaderNames.HOST);
handshaker = WebSocketClientHandshakerFactory.newHandshaker(currentURI,
websocketClientSpec.version(),
subprotocols != null && !subprotocols.isEmpty() ? subprotocols : null,
true,
replaced.requestHeaders()
.remove(HttpHeaderNames.HOST),
replacedRequestHeaders,
websocketClientSpec.maxFramePayloadLength());

handshaker.handshake(channel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ final class DefaultHttpForwardedHeaderHandler implements BiFunction<ConnectionIn

@Override
public ConnectionInfo apply(ConnectionInfo connectionInfo, HttpRequest request) {
String forwardedHeader = request.headers().get(FORWARDED_HEADER);
CharSequence forwardedHeader = request.headers().get(FORWARDED_HEADER);
if (forwardedHeader != null) {
return parseForwardedInfo(connectionInfo, forwardedHeader);
return parseForwardedInfo(connectionInfo, forwardedHeader.toString());
}
return parseXForwardedInfo(connectionInfo, request);
}
Expand All @@ -69,17 +69,17 @@ private ConnectionInfo parseForwardedInfo(ConnectionInfo connectionInfo, String
}

private ConnectionInfo parseXForwardedInfo(ConnectionInfo connectionInfo, HttpRequest request) {
String ipHeader = request.headers().get(X_FORWARDED_IP_HEADER);
CharSequence ipHeader = request.headers().get(X_FORWARDED_IP_HEADER);
if (ipHeader != null) {
connectionInfo = connectionInfo.withRemoteAddress(
AddressUtils.parseAddress(ipHeader.split(",", 2)[0], connectionInfo.getRemoteAddress().getPort()));
AddressUtils.parseAddress(ipHeader.toString().split(",", 2)[0], connectionInfo.getRemoteAddress().getPort()));
}
String hostHeader = request.headers().get(X_FORWARDED_HOST_HEADER);
CharSequence hostHeader = request.headers().get(X_FORWARDED_HOST_HEADER);
if (hostHeader != null) {
String portHeader = request.headers().get(X_FORWARDED_PORT_HEADER);
CharSequence portHeader = request.headers().get(X_FORWARDED_PORT_HEADER);
int port = connectionInfo.getHostAddress().getPort();
if (portHeader != null && !portHeader.isEmpty()) {
String portStr = portHeader.split(",", 2)[0].trim();
if (portHeader != null && !portHeader.toString().isEmpty()) {
String portStr = portHeader.toString().split(",", 2)[0].trim();
if (portStr.chars().allMatch(Character::isDigit)) {
port = Integer.parseInt(portStr);
}
Expand All @@ -88,11 +88,11 @@ private ConnectionInfo parseXForwardedInfo(ConnectionInfo connectionInfo, HttpRe
}
}
connectionInfo = connectionInfo.withHostAddress(
AddressUtils.createUnresolved(hostHeader.split(",", 2)[0].trim(), port));
AddressUtils.createUnresolved(hostHeader.toString().split(",", 2)[0].trim(), port));
}
String protoHeader = request.headers().get(X_FORWARDED_PROTO_HEADER);
CharSequence protoHeader = request.headers().get(X_FORWARDED_PROTO_HEADER);
if (protoHeader != null) {
connectionInfo = connectionInfo.withScheme(protoHeader.split(",", 2)[0].trim());
connectionInfo = connectionInfo.withScheme(protoHeader.toString().split(",", 2)[0].trim());
}
return connectionInfo;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -482,15 +482,15 @@ static BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate(

BiPredicate<HttpServerRequest, HttpServerResponse> lengthPredicate =
(req, res) -> {
String length = res.responseHeaders()
CharSequence length = res.responseHeaders()
.get(HttpHeaderNames.CONTENT_LENGTH);

if (length == null) {
return true;
}

try {
return Long.parseLong(length) >= minResponseSize;
return Long.parseLong(length.toString()) >= minResponseSize;
}
catch (NumberFormatException nfe) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,8 @@
import io.netty5.channel.ChannelFutureListeners;
import io.netty5.channel.ChannelHandlerContext;
import io.netty5.channel.ChannelOption;
import io.netty5.handler.codec.DefaultHeaders;
import io.netty5.handler.codec.TooLongFrameException;
import io.netty5.handler.codec.http.DefaultFullHttpResponse;
import io.netty5.handler.codec.http.DefaultHttpHeaders;
import io.netty5.handler.codec.http.DefaultHttpResponse;
import io.netty5.handler.codec.http.DefaultLastHttpContent;
import io.netty5.handler.codec.http.EmptyLastHttpContent;
Expand Down Expand Up @@ -206,7 +204,7 @@ protected HttpMessage newFullBodyMessage(Buffer body) {
if (!HttpResponseStatus.NOT_MODIFIED.equals(status())) {

if (HttpUtil.getContentLength(nettyResponse, -1) == -1) {
responseHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, body.readableBytes());
responseHeaders.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(body.readableBytes()));
}
}
}
Expand Down Expand Up @@ -602,8 +600,8 @@ protected void onInboundClose() {
@Override
protected void afterMarkSentHeaders() {
if (HttpResponseStatus.NOT_MODIFIED.equals(status())) {
responseHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING)
.remove(HttpHeaderNames.CONTENT_LENGTH);
responseHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
responseHeaders.remove(HttpHeaderNames.CONTENT_LENGTH);
}
if (compressionPredicate != null && compressionPredicate.test(this, this)) {
compression(true);
Expand Down Expand Up @@ -653,9 +651,9 @@ else if (markSentBody()) {
// of trailer fields at the end of the message, the sender SHOULD
// generate a Trailer header field before the message body to indicate
// which fields will be present in the trailers.
String declaredHeaderNames = responseHeaders.get(HttpHeaderNames.TRAILER);
CharSequence declaredHeaderNames = responseHeaders.get(HttpHeaderNames.TRAILER);
if (declaredHeaderNames != null) {
HttpHeaders trailerHeaders = new TrailerHeaders(declaredHeaderNames);
HttpHeaders trailerHeaders = new TrailerHeaders(declaredHeaderNames.toString());
try {
trailerHeadersConsumer.accept(trailerHeaders);
}
Expand Down Expand Up @@ -735,7 +733,7 @@ static void sendDecodingFailures(
HttpResponseStatus.BAD_REQUEST,
ctx.bufferAllocator().allocate(0));
response.headers()
.setInt(HttpHeaderNames.CONTENT_LENGTH, 0)
.set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO)
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);

Connection ops = ChannelOperations.get(ctx.channel());
Expand Down Expand Up @@ -928,8 +926,23 @@ static final class TrailerHeaders extends DefaultHttpHeaders {
DISALLOWED_TRAILER_HEADER_NAMES.add("warning");
}

/**
* Contains the headers names specified with {@link HttpHeaderNames#TRAILER}
*/
final Set<String> declaredHeaderNames;

TrailerHeaders(String declaredHeaderNames) {
super(true, new TrailerNameValidator(filterHeaderNames(declaredHeaderNames)));
super(16, true, true, true);
this.declaredHeaderNames = filterHeaderNames(declaredHeaderNames);
}

@Override
protected CharSequence validateKey(@Nullable CharSequence name) {
if (!declaredHeaderNames.contains(name.toString())) {
throw new IllegalArgumentException("Trailer header name [" + name +
"] not declared with [Trailer] header, or it is not a valid trailer header name");
}
return name;
}

static Set<String> filterHeaderNames(String declaredHeaderNames) {
Expand All @@ -946,25 +959,5 @@ static Set<String> filterHeaderNames(String declaredHeaderNames) {
}
return result;
}

static final class TrailerNameValidator implements DefaultHeaders.NameValidator<CharSequence> {

/**
* Contains the headers names specified with {@link HttpHeaderNames#TRAILER}
*/
final Set<String> declaredHeaderNames;

TrailerNameValidator(Set<String> declaredHeaderNames) {
this.declaredHeaderNames = declaredHeaderNames;
}

@Override
public void validateName(CharSequence name) {
if (!declaredHeaderNames.contains(name.toString())) {
throw new IllegalArgumentException("Trailer header name [" + name +
"] not declared with [Trailer] header, or it is not a valid trailer header name");
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ default HttpServerRoutes ws(Predicate<? super HttpServerRequest> condition,
WebsocketServerSpec websocketServerSpec) {
return route(condition, (req, resp) -> {
if (req.requestHeaders()
.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
.containsIgnoreCase(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)) {
HttpServerOperations ops = (HttpServerOperations) req;
return ops.withWebsocketSupport(req.uri(), websocketServerSpec, handler);
}
Expand Down

0 comments on commit 7062ace

Please sign in to comment.