Replace HttpHeaders.Names/Values with HttpHeaderNames/Values

Related: 4ce994dd4f

Motivation:

In 4.1, we were not able to change the type of the HTTP header name and
value constants from String to AsciiString due to backward compatibility
reasons.

Instead of breaking backward compatibility in 4.1, we introduced new
types called HttpHeaderNames and HttpHeaderValues which provides the
AsciiString version of the constants, and then deprecated
HttpHeaders.Names/Values.

We should make the same changes while deleting the deprecated classes
activaly.

Modifications:

- Remove HttpHeaders.Names/Values and RtspHeaders
- Add HttpHeaderNames/Values and RtspHeaderNames/Values
  - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually
    lowercased in all WebSocket versions but the oldest one
- Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of
  the parameters are AsciiString
  - Avoid using AsciiString.toString() repetitively
    - Change the parameter type of some methods from String to
      CharSequence

Result:

A user who upgraded from 4.0 to 4.1 first and removed the references to
the deprecated classes and methods can easily upgrade from 4.1 to 5.0.
This commit is contained in:
Trustin Lee 2014-11-01 02:15:14 +09:00
parent afe4833e4e
commit f793f395d6
83 changed files with 1736 additions and 1740 deletions

View File

@ -17,13 +17,10 @@ package io.netty.handler.codec.http;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.AsciiString;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
import java.util.Map; import java.util.Map;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
/** /**
* The default {@link LastHttpContent} implementation. * The default {@link LastHttpContent} implementation.
*/ */
@ -119,9 +116,9 @@ public class DefaultLastHttpContent extends DefaultHttpContent implements LastHt
public CharSequence convertName(CharSequence name) { public CharSequence convertName(CharSequence name) {
name = super.convertName(name); name = super.convertName(name);
if (validate) { if (validate) {
if (AsciiString.equalsIgnoreCase(CONTENT_LENGTH, name) if (HttpHeaderNames.CONTENT_LENGTH.equalsIgnoreCase(name)
|| AsciiString.equalsIgnoreCase(TRANSFER_ENCODING, name) || HttpHeaderNames.TRANSFER_ENCODING.equalsIgnoreCase(name)
|| AsciiString.equalsIgnoreCase(TRAILER, name)) { || HttpHeaderNames.TRAILER.equalsIgnoreCase(name)) {
throw new IllegalArgumentException("prohibited trailing header: " + name); throw new IllegalArgumentException("prohibited trailing header: " + name);
} }
} }

View File

@ -23,7 +23,6 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.util.ReferenceCountUtil.*; import static io.netty.util.ReferenceCountUtil.*;
@ -178,7 +177,7 @@ public class HttpClientUpgradeHandler extends HttpObjectAggregator {
return; return;
} }
CharSequence upgradeHeader = response.headers().get(UPGRADE); CharSequence upgradeHeader = response.headers().get(HttpHeaderNames.UPGRADE);
if (upgradeHeader == null) { if (upgradeHeader == null) {
throw new IllegalStateException( throw new IllegalStateException(
"Switching Protocols response missing UPGRADE header"); "Switching Protocols response missing UPGRADE header");
@ -217,7 +216,7 @@ public class HttpClientUpgradeHandler extends HttpObjectAggregator {
*/ */
private void setUpgradeRequestHeaders(ChannelHandlerContext ctx, HttpRequest request) { private void setUpgradeRequestHeaders(ChannelHandlerContext ctx, HttpRequest request) {
// Set the UPGRADE header on the request. // Set the UPGRADE header on the request.
request.headers().set(UPGRADE, upgradeCodec.protocol()); request.headers().set(HttpHeaderNames.UPGRADE, upgradeCodec.protocol());
// Add all protocol-specific headers to the request. // Add all protocol-specific headers to the request.
Set<String> connectionParts = new LinkedHashSet<String>(2); Set<String> connectionParts = new LinkedHashSet<String>(2);
@ -229,7 +228,7 @@ public class HttpClientUpgradeHandler extends HttpObjectAggregator {
builder.append(part); builder.append(part);
builder.append(','); builder.append(',');
} }
builder.append(UPGRADE); builder.append(HttpHeaderNames.UPGRADE);
request.headers().set(CONNECTION, builder.toString()); request.headers().set(HttpHeaderNames.CONNECTION, builder.toString());
} }
} }

View File

@ -16,7 +16,6 @@
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.compression.ZlibCodecFactory; import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
@ -95,9 +94,9 @@ public class HttpContentCompressor extends HttpContentEncoder {
@Override @Override
protected Result beginEncode(HttpResponse headers, CharSequence acceptEncoding) throws Exception { protected Result beginEncode(HttpResponse headers, CharSequence acceptEncoding) throws Exception {
CharSequence contentEncoding = headers.headers().get(HttpHeaders.Names.CONTENT_ENCODING); CharSequence contentEncoding = headers.headers().get(HttpHeaderNames.CONTENT_ENCODING);
if (contentEncoding != null && if (contentEncoding != null &&
!AsciiString.equalsIgnoreCase(HttpHeaders.Values.IDENTITY, contentEncoding)) { !HttpHeaderValues.IDENTITY.equalsIgnoreCase(contentEncoding)) {
return null; return null;
} }

View File

@ -44,6 +44,8 @@ import java.util.List;
*/ */
public abstract class HttpContentDecoder extends MessageToMessageDecoder<HttpObject> { public abstract class HttpContentDecoder extends MessageToMessageDecoder<HttpObject> {
private static final String IDENTITY = HttpHeaderValues.IDENTITY.toString();
private EmbeddedChannel decoder; private EmbeddedChannel decoder;
private HttpMessage message; private HttpMessage message;
private boolean decodeStarted; private boolean decodeStarted;
@ -87,30 +89,30 @@ public abstract class HttpContentDecoder extends MessageToMessageDecoder<HttpObj
this.message = null; this.message = null;
// Determine the content encoding. // Determine the content encoding.
String contentEncoding = headers.getAndConvert(HttpHeaders.Names.CONTENT_ENCODING); String contentEncoding = headers.getAndConvert(HttpHeaderNames.CONTENT_ENCODING);
if (contentEncoding != null) { if (contentEncoding != null) {
contentEncoding = contentEncoding.trim(); contentEncoding = contentEncoding.trim();
} else { } else {
contentEncoding = HttpHeaders.Values.IDENTITY.toString(); contentEncoding = IDENTITY;
} }
if ((decoder = newContentDecoder(contentEncoding)) != null) { if ((decoder = newContentDecoder(contentEncoding)) != null) {
// Decode the content and remove or replace the existing headers // Decode the content and remove or replace the existing headers
// so that the message looks like a decoded message. // so that the message looks like a decoded message.
CharSequence targetContentEncoding = getTargetContentEncoding(contentEncoding); CharSequence targetContentEncoding = getTargetContentEncoding(contentEncoding);
if (HttpHeaders.Values.IDENTITY.equals(targetContentEncoding)) { if (HttpHeaderValues.IDENTITY.equals(targetContentEncoding)) {
// Do NOT set the 'Content-Encoding' header if the target encoding is 'identity' // Do NOT set the 'Content-Encoding' header if the target encoding is 'identity'
// as per: http://tools.ietf.org/html/rfc2616#section-14.11 // as per: http://tools.ietf.org/html/rfc2616#section-14.11
headers.remove(HttpHeaders.Names.CONTENT_ENCODING); headers.remove(HttpHeaderNames.CONTENT_ENCODING);
} else { } else {
headers.set(HttpHeaders.Names.CONTENT_ENCODING, targetContentEncoding); headers.set(HttpHeaderNames.CONTENT_ENCODING, targetContentEncoding);
} }
out.add(message); out.add(message);
decodeContent(c, out); decodeContent(c, out);
// Replace the content length. // Replace the content length.
if (headers.contains(HttpHeaders.Names.CONTENT_LENGTH)) { if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
int contentLength = 0; int contentLength = 0;
int size = out.size(); int size = out.size();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
@ -120,7 +122,7 @@ public abstract class HttpContentDecoder extends MessageToMessageDecoder<HttpObj
} }
} }
headers.set( headers.set(
HttpHeaders.Names.CONTENT_LENGTH, HttpHeaderNames.CONTENT_LENGTH,
Integer.toString(contentLength)); Integer.toString(contentLength));
} }
return; return;
@ -186,7 +188,7 @@ public abstract class HttpContentDecoder extends MessageToMessageDecoder<HttpObj
*/ */
protected CharSequence getTargetContentEncoding( protected CharSequence getTargetContentEncoding(
@SuppressWarnings("UnusedParameters") String contentEncoding) throws Exception { @SuppressWarnings("UnusedParameters") String contentEncoding) throws Exception {
return HttpHeaders.Values.IDENTITY; return HttpHeaderValues.IDENTITY;
} }
@Override @Override

View File

@ -47,12 +47,12 @@ public class HttpContentDecompressor extends HttpContentDecoder {
@Override @Override
protected EmbeddedChannel newContentDecoder(String contentEncoding) throws Exception { protected EmbeddedChannel newContentDecoder(String contentEncoding) throws Exception {
if (HttpHeaders.Values.GZIP.equalsIgnoreCase(contentEncoding) || if (HttpHeaderValues.GZIP.equalsIgnoreCase(contentEncoding) ||
HttpHeaders.Values.XGZIP.equalsIgnoreCase(contentEncoding)) { HttpHeaderValues.X_GZIP.equalsIgnoreCase(contentEncoding)) {
return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
} }
if (HttpHeaders.Values.DEFLATE.equalsIgnoreCase(contentEncoding) || if (HttpHeaderValues.DEFLATE.equalsIgnoreCase(contentEncoding) ||
HttpHeaders.Values.XDEFLATE.equalsIgnoreCase(contentEncoding)) { HttpHeaderValues.X_DEFLATE.equalsIgnoreCase(contentEncoding)) {
final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE; final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE;
// To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly. // To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.
return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(wrapper)); return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(wrapper));

View File

@ -20,8 +20,6 @@ import io.netty.buffer.ByteBufHolder;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.MessageToMessageCodec; import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import java.util.ArrayDeque; import java.util.ArrayDeque;
@ -71,9 +69,9 @@ public abstract class HttpContentEncoder extends MessageToMessageCodec<HttpReque
@Override @Override
protected void decode(ChannelHandlerContext ctx, HttpRequest msg, List<Object> out) protected void decode(ChannelHandlerContext ctx, HttpRequest msg, List<Object> out)
throws Exception { throws Exception {
CharSequence acceptedEncoding = msg.headers().get(HttpHeaders.Names.ACCEPT_ENCODING); CharSequence acceptedEncoding = msg.headers().get(HttpHeaderNames.ACCEPT_ENCODING);
if (acceptedEncoding == null) { if (acceptedEncoding == null) {
acceptedEncoding = HttpHeaders.Values.IDENTITY; acceptedEncoding = HttpHeaderValues.IDENTITY;
} }
acceptEncodingQueue.add(acceptedEncoding); acceptEncodingQueue.add(acceptedEncoding);
out.add(ReferenceCountUtil.retain(msg)); out.add(ReferenceCountUtil.retain(msg));
@ -133,11 +131,11 @@ public abstract class HttpContentEncoder extends MessageToMessageCodec<HttpReque
// Encode the content and remove or replace the existing headers // Encode the content and remove or replace the existing headers
// so that the message looks like a decoded message. // so that the message looks like a decoded message.
res.headers().set(Names.CONTENT_ENCODING, result.targetContentEncoding()); res.headers().set(HttpHeaderNames.CONTENT_ENCODING, result.targetContentEncoding());
// Make the response chunked to simplify content transformation. // Make the response chunked to simplify content transformation.
res.headers().remove(Names.CONTENT_LENGTH); res.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
res.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
// Output the rewritten response. // Output the rewritten response.
if (isFull) { if (isFull) {

View File

@ -0,0 +1,351 @@
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http;
import io.netty.handler.codec.AsciiString;
/**
* Standard HTTP header names.
* <p>
* These are all defined as lowercase to support HTTP/2 requirements while also not
* violating HTTP/1.x requirements. New header names should always be lowercase.
*/
public final class HttpHeaderNames {
/**
* {@code "accept"}
*/
public static final AsciiString ACCEPT = new AsciiString("accept");
/**
* {@code "accept-charset"}
*/
public static final AsciiString ACCEPT_CHARSET = new AsciiString("accept-charset");
/**
* {@code "accept-encoding"}
*/
public static final AsciiString ACCEPT_ENCODING = new AsciiString("accept-encoding");
/**
* {@code "accept-language"}
*/
public static final AsciiString ACCEPT_LANGUAGE = new AsciiString("accept-language");
/**
* {@code "accept-ranges"}
*/
public static final AsciiString ACCEPT_RANGES = new AsciiString("accept-ranges");
/**
* {@code "accept-patch"}
*/
public static final AsciiString ACCEPT_PATCH = new AsciiString("accept-patch");
/**
* {@code "access-control-allow-credentials"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_CREDENTIALS =
new AsciiString("access-control-allow-credentials");
/**
* {@code "access-control-allow-headers"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_HEADERS =
new AsciiString("access-control-allow-headers");
/**
* {@code "access-control-allow-methods"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_METHODS =
new AsciiString("access-control-allow-methods");
/**
* {@code "access-control-allow-origin"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_ORIGIN =
new AsciiString("access-control-allow-origin");
/**
* {@code "access-control-expose-headers"}
*/
public static final AsciiString ACCESS_CONTROL_EXPOSE_HEADERS =
new AsciiString("access-control-expose-headers");
/**
* {@code "access-control-max-age"}
*/
public static final AsciiString ACCESS_CONTROL_MAX_AGE = new AsciiString("access-control-max-age");
/**
* {@code "access-control-request-headers"}
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_HEADERS =
new AsciiString("access-control-request-headers");
/**
* {@code "access-control-request-method"}
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_METHOD =
new AsciiString("access-control-request-method");
/**
* {@code "age"}
*/
public static final AsciiString AGE = new AsciiString("age");
/**
* {@code "allow"}
*/
public static final AsciiString ALLOW = new AsciiString("allow");
/**
* {@code "authorization"}
*/
public static final AsciiString AUTHORIZATION = new AsciiString("authorization");
/**
* {@code "cache-control"}
*/
public static final AsciiString CACHE_CONTROL = new AsciiString("cache-control");
/**
* {@code "connection"}
*/
public static final AsciiString CONNECTION = new AsciiString("connection");
/**
* {@code "content-base"}
*/
public static final AsciiString CONTENT_BASE = new AsciiString("content-base");
/**
* {@code "content-encoding"}
*/
public static final AsciiString CONTENT_ENCODING = new AsciiString("content-encoding");
/**
* {@code "content-language"}
*/
public static final AsciiString CONTENT_LANGUAGE = new AsciiString("content-language");
/**
* {@code "content-length"}
*/
public static final AsciiString CONTENT_LENGTH = new AsciiString("content-length");
/**
* {@code "content-location"}
*/
public static final AsciiString CONTENT_LOCATION = new AsciiString("content-location");
/**
* {@code "content-transfer-encoding"}
*/
public static final AsciiString CONTENT_TRANSFER_ENCODING = new AsciiString("content-transfer-encoding");
/**
* {@code "content-disposition"}
*/
public static final AsciiString CONTENT_DISPOSITION = new AsciiString("content-disposition");
/**
* {@code "content-md5"}
*/
public static final AsciiString CONTENT_MD5 = new AsciiString("content-md5");
/**
* {@code "content-range"}
*/
public static final AsciiString CONTENT_RANGE = new AsciiString("content-range");
/**
* {@code "content-type"}
*/
public static final AsciiString CONTENT_TYPE = new AsciiString("content-type");
/**
* {@code "cookie"}
*/
public static final AsciiString COOKIE = new AsciiString("cookie");
/**
* {@code "date"}
*/
public static final AsciiString DATE = new AsciiString("date");
/**
* {@code "etag"}
*/
public static final AsciiString ETAG = new AsciiString("etag");
/**
* {@code "expect"}
*/
public static final AsciiString EXPECT = new AsciiString("expect");
/**
* {@code "expires"}
*/
public static final AsciiString EXPIRES = new AsciiString("expires");
/**
* {@code "from"}
*/
public static final AsciiString FROM = new AsciiString("from");
/**
* {@code "host"}
*/
public static final AsciiString HOST = new AsciiString("host");
/**
* {@code "if-match"}
*/
public static final AsciiString IF_MATCH = new AsciiString("if-match");
/**
* {@code "if-modified-since"}
*/
public static final AsciiString IF_MODIFIED_SINCE = new AsciiString("if-modified-since");
/**
* {@code "if-none-match"}
*/
public static final AsciiString IF_NONE_MATCH = new AsciiString("if-none-match");
/**
* {@code "if-range"}
*/
public static final AsciiString IF_RANGE = new AsciiString("if-range");
/**
* {@code "if-unmodified-since"}
*/
public static final AsciiString IF_UNMODIFIED_SINCE = new AsciiString("if-unmodified-since");
/**
* @deprecated use {@link #CONNECTION}
*
* {@code "keep-alive"}
*/
@Deprecated
public static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");
/**
* {@code "last-modified"}
*/
public static final AsciiString LAST_MODIFIED = new AsciiString("last-modified");
/**
* {@code "location"}
*/
public static final AsciiString LOCATION = new AsciiString("location");
/**
* {@code "max-forwards"}
*/
public static final AsciiString MAX_FORWARDS = new AsciiString("max-forwards");
/**
* {@code "origin"}
*/
public static final AsciiString ORIGIN = new AsciiString("origin");
/**
* {@code "pragma"}
*/
public static final AsciiString PRAGMA = new AsciiString("pragma");
/**
* {@code "proxy-authenticate"}
*/
public static final AsciiString PROXY_AUTHENTICATE = new AsciiString("proxy-authenticate");
/**
* {@code "proxy-authorization"}
*/
public static final AsciiString PROXY_AUTHORIZATION = new AsciiString("proxy-authorization");
/**
* @deprecated use {@link #CONNECTION}
*
* {@code "proxy-connection"}
*/
@Deprecated
public static final AsciiString PROXY_CONNECTION = new AsciiString("proxy-connection");
/**
* {@code "range"}
*/
public static final AsciiString RANGE = new AsciiString("range");
/**
* {@code "referer"}
*/
public static final AsciiString REFERER = new AsciiString("referer");
/**
* {@code "retry-after"}
*/
public static final AsciiString RETRY_AFTER = new AsciiString("retry-after");
/**
* {@code "sec-websocket-key1"}
*/
public static final AsciiString SEC_WEBSOCKET_KEY1 = new AsciiString("sec-websocket-key1");
/**
* {@code "sec-websocket-key2"}
*/
public static final AsciiString SEC_WEBSOCKET_KEY2 = new AsciiString("sec-websocket-key2");
/**
* {@code "sec-websocket-location"}
*/
public static final AsciiString SEC_WEBSOCKET_LOCATION = new AsciiString("sec-websocket-location");
/**
* {@code "sec-websocket-origin"}
*/
public static final AsciiString SEC_WEBSOCKET_ORIGIN = new AsciiString("sec-websocket-origin");
/**
* {@code "sec-websocket-protocol"}
*/
public static final AsciiString SEC_WEBSOCKET_PROTOCOL = new AsciiString("sec-websocket-protocol");
/**
* {@code "sec-websocket-version"}
*/
public static final AsciiString SEC_WEBSOCKET_VERSION = new AsciiString("sec-websocket-version");
/**
* {@code "sec-websocket-key"}
*/
public static final AsciiString SEC_WEBSOCKET_KEY = new AsciiString("sec-websocket-key");
/**
* {@code "sec-websocket-accept"}
*/
public static final AsciiString SEC_WEBSOCKET_ACCEPT = new AsciiString("sec-websocket-accept");
/**
* {@code "sec-websocket-protocol"}
*/
public static final AsciiString SEC_WEBSOCKET_EXTENSIONS = new AsciiString("sec-websocket-extensions");
/**
* {@code "server"}
*/
public static final AsciiString SERVER = new AsciiString("server");
/**
* {@code "set-cookie"}
*/
public static final AsciiString SET_COOKIE = new AsciiString("set-cookie");
/**
* {@code "set-cookie2"}
*/
public static final AsciiString SET_COOKIE2 = new AsciiString("set-cookie2");
/**
* {@code "te"}
*/
public static final AsciiString TE = new AsciiString("te");
/**
* {@code "trailer"}
*/
public static final AsciiString TRAILER = new AsciiString("trailer");
/**
* {@code "transfer-encoding"}
*/
public static final AsciiString TRANSFER_ENCODING = new AsciiString("transfer-encoding");
/**
* {@code "upgrade"}
*/
public static final AsciiString UPGRADE = new AsciiString("upgrade");
/**
* {@code "user-agent"}
*/
public static final AsciiString USER_AGENT = new AsciiString("user-agent");
/**
* {@code "vary"}
*/
public static final AsciiString VARY = new AsciiString("vary");
/**
* {@code "via"}
*/
public static final AsciiString VIA = new AsciiString("via");
/**
* {@code "warning"}
*/
public static final AsciiString WARNING = new AsciiString("warning");
/**
* {@code "websocket-location"}
*/
public static final AsciiString WEBSOCKET_LOCATION = new AsciiString("websocket-location");
/**
* {@code "websocket-origin"}
*/
public static final AsciiString WEBSOCKET_ORIGIN = new AsciiString("websocket-origin");
/**
* {@code "websocket-protocol"}
*/
public static final AsciiString WEBSOCKET_PROTOCOL = new AsciiString("websocket-protocol");
/**
* {@code "www-authenticate"}
*/
public static final AsciiString WWW_AUTHENTICATE = new AsciiString("www-authenticate");
private HttpHeaderNames() { }
}

View File

@ -17,9 +17,6 @@
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -33,15 +30,15 @@ public final class HttpHeaderUtil {
* {@link HttpVersion#isKeepAliveDefault()}. * {@link HttpVersion#isKeepAliveDefault()}.
*/ */
public static boolean isKeepAlive(HttpMessage message) { public static boolean isKeepAlive(HttpMessage message) {
CharSequence connection = message.headers().get(Names.CONNECTION); CharSequence connection = message.headers().get(HttpHeaderNames.CONNECTION);
if (connection != null && AsciiString.equalsIgnoreCase(Values.CLOSE, connection)) { if (connection != null && HttpHeaderValues.CLOSE.equalsIgnoreCase(connection)) {
return false; return false;
} }
if (message.protocolVersion().isKeepAliveDefault()) { if (message.protocolVersion().isKeepAliveDefault()) {
return !AsciiString.equalsIgnoreCase(Values.CLOSE, connection); return !HttpHeaderValues.CLOSE.equalsIgnoreCase(connection);
} else { } else {
return AsciiString.equalsIgnoreCase(Values.KEEP_ALIVE, connection); return HttpHeaderValues.KEEP_ALIVE.equalsIgnoreCase(connection);
} }
} }
@ -68,15 +65,15 @@ public final class HttpHeaderUtil {
HttpHeaders h = message.headers(); HttpHeaders h = message.headers();
if (message.protocolVersion().isKeepAliveDefault()) { if (message.protocolVersion().isKeepAliveDefault()) {
if (keepAlive) { if (keepAlive) {
h.remove(Names.CONNECTION); h.remove(HttpHeaderNames.CONNECTION);
} else { } else {
h.set(Names.CONNECTION, Values.CLOSE); h.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
} }
} else { } else {
if (keepAlive) { if (keepAlive) {
h.set(Names.CONNECTION, Values.KEEP_ALIVE); h.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
} else { } else {
h.remove(Names.CONNECTION); h.remove(HttpHeaderNames.CONNECTION);
} }
} }
} }
@ -94,7 +91,7 @@ public final class HttpHeaderUtil {
* or its value is not a number * or its value is not a number
*/ */
public static long getContentLength(HttpMessage message) { public static long getContentLength(HttpMessage message) {
Long value = message.headers().getLong(Names.CONTENT_LENGTH); Long value = message.headers().getLong(HttpHeaderNames.CONTENT_LENGTH);
if (value != null) { if (value != null) {
return value; return value;
} }
@ -107,7 +104,7 @@ public final class HttpHeaderUtil {
} }
// Otherwise we don't. // Otherwise we don't.
throw new NumberFormatException("header not found: " + Names.CONTENT_LENGTH); throw new NumberFormatException("header not found: " + HttpHeaderNames.CONTENT_LENGTH);
} }
/** /**
@ -121,7 +118,7 @@ public final class HttpHeaderUtil {
* a number * a number
*/ */
public static long getContentLength(HttpMessage message, long defaultValue) { public static long getContentLength(HttpMessage message, long defaultValue) {
Long value = message.headers().getLong(Names.CONTENT_LENGTH); Long value = message.headers().getLong(HttpHeaderNames.CONTENT_LENGTH);
if (value != null) { if (value != null) {
return value; return value;
} }
@ -147,15 +144,15 @@ public final class HttpHeaderUtil {
if (message instanceof HttpRequest) { if (message instanceof HttpRequest) {
HttpRequest req = (HttpRequest) message; HttpRequest req = (HttpRequest) message;
if (HttpMethod.GET.equals(req.method()) && if (HttpMethod.GET.equals(req.method()) &&
h.contains(Names.SEC_WEBSOCKET_KEY1) && h.contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) &&
h.contains(Names.SEC_WEBSOCKET_KEY2)) { h.contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2)) {
return 8; return 8;
} }
} else if (message instanceof HttpResponse) { } else if (message instanceof HttpResponse) {
HttpResponse res = (HttpResponse) message; HttpResponse res = (HttpResponse) message;
if (res.status().code() == 101 && if (res.status().code() == 101 &&
h.contains(Names.SEC_WEBSOCKET_ORIGIN) && h.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN) &&
h.contains(Names.SEC_WEBSOCKET_LOCATION)) { h.contains(HttpHeaderNames.SEC_WEBSOCKET_LOCATION)) {
return 16; return 16;
} }
} }
@ -168,11 +165,11 @@ public final class HttpHeaderUtil {
* Sets the {@code "Content-Length"} header. * Sets the {@code "Content-Length"} header.
*/ */
public static void setContentLength(HttpMessage message, long length) { public static void setContentLength(HttpMessage message, long length) {
message.headers().setLong(Names.CONTENT_LENGTH, length); message.headers().setLong(HttpHeaderNames.CONTENT_LENGTH, length);
} }
public static boolean isContentLengthSet(HttpMessage m) { public static boolean isContentLengthSet(HttpMessage m) {
return m.headers().contains(Names.CONTENT_LENGTH); return m.headers().contains(HttpHeaderNames.CONTENT_LENGTH);
} }
/** /**
@ -191,16 +188,16 @@ public final class HttpHeaderUtil {
} }
// In most cases, there will be one or zero 'Expect' header. // In most cases, there will be one or zero 'Expect' header.
CharSequence value = message.headers().get(Names.EXPECT); CharSequence value = message.headers().get(HttpHeaderNames.EXPECT);
if (value == null) { if (value == null) {
return false; return false;
} }
if (AsciiString.equalsIgnoreCase(Values.CONTINUE, value)) { if (HttpHeaderValues.CONTINUE.equalsIgnoreCase(value)) {
return true; return true;
} }
// Multiple 'Expect' headers. Search through them. // Multiple 'Expect' headers. Search through them.
return message.headers().contains(Names.EXPECT, Values.CONTINUE, true); return message.headers().contains(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE, true);
} }
/** /**
@ -212,9 +209,9 @@ public final class HttpHeaderUtil {
*/ */
public static void set100ContinueExpected(HttpMessage message, boolean expected) { public static void set100ContinueExpected(HttpMessage message, boolean expected) {
if (expected) { if (expected) {
message.headers().set(Names.EXPECT, Values.CONTINUE); message.headers().set(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE);
} else { } else {
message.headers().remove(Names.EXPECT); message.headers().remove(HttpHeaderNames.EXPECT);
} }
} }
@ -225,29 +222,29 @@ public final class HttpHeaderUtil {
* @return True if transfer encoding is chunked, otherwise false * @return True if transfer encoding is chunked, otherwise false
*/ */
public static boolean isTransferEncodingChunked(HttpMessage message) { public static boolean isTransferEncodingChunked(HttpMessage message) {
return message.headers().contains(Names.TRANSFER_ENCODING, Values.CHUNKED, true); return message.headers().contains(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED, true);
} }
public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) { public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) {
if (chunked) { if (chunked) {
m.headers().add(Names.TRANSFER_ENCODING, Values.CHUNKED); m.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
m.headers().remove(Names.CONTENT_LENGTH); m.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
} else { } else {
List<CharSequence> values = m.headers().getAll(Names.TRANSFER_ENCODING); List<CharSequence> values = m.headers().getAll(HttpHeaderNames.TRANSFER_ENCODING);
if (values.isEmpty()) { if (values.isEmpty()) {
return; return;
} }
Iterator<CharSequence> valuesIt = values.iterator(); Iterator<CharSequence> valuesIt = values.iterator();
while (valuesIt.hasNext()) { while (valuesIt.hasNext()) {
CharSequence value = valuesIt.next(); CharSequence value = valuesIt.next();
if (AsciiString.equalsIgnoreCase(value, Values.CHUNKED)) { if (HttpHeaderValues.CHUNKED.equalsIgnoreCase(value)) {
valuesIt.remove(); valuesIt.remove();
} }
} }
if (values.isEmpty()) { if (values.isEmpty()) {
m.headers().remove(Names.TRANSFER_ENCODING); m.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
} else { } else {
m.headers().set(Names.TRANSFER_ENCODING, values); m.headers().set(HttpHeaderNames.TRANSFER_ENCODING, values);
} }
} }
} }

View File

@ -0,0 +1,201 @@
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http;
import io.netty.handler.codec.AsciiString;
/**
* Standard HTTP header values.
*/
public final class HttpHeaderValues {
/**
* {@code "application/x-www-form-urlencoded"}
*/
public static final AsciiString APPLICATION_X_WWW_FORM_URLENCODED =
new AsciiString("application/x-www-form-urlencoded");
/**
* {@code "application/octet-stream"}
*/
public static final AsciiString APPLICATION_OCTET_STREAM = new AsciiString("application/octet-stream");
/**
* {@code "attachment"}
* See {@link HttpHeaderNames#CONTENT_DISPOSITION}
*/
public static final AsciiString ATTACHMENT = new AsciiString("attachment");
/**
* {@code "base64"}
*/
public static final AsciiString BASE64 = new AsciiString("base64");
/**
* {@code "binary"}
*/
public static final AsciiString BINARY = new AsciiString("binary");
/**
* {@code "boundary"}
*/
public static final AsciiString BOUNDARY = new AsciiString("boundary");
/**
* {@code "bytes"}
*/
public static final AsciiString BYTES = new AsciiString("bytes");
/**
* {@code "charset"}
*/
public static final AsciiString CHARSET = new AsciiString("charset");
/**
* {@code "chunked"}
*/
public static final AsciiString CHUNKED = new AsciiString("chunked");
/**
* {@code "close"}
*/
public static final AsciiString CLOSE = new AsciiString("close");
/**
* {@code "compress"}
*/
public static final AsciiString COMPRESS = new AsciiString("compress");
/**
* {@code "100-continue"}
*/
public static final AsciiString CONTINUE = new AsciiString("100-continue");
/**
* {@code "deflate"}
*/
public static final AsciiString DEFLATE = new AsciiString("deflate");
/**
* {@code "file"}
* See {@link HttpHeaderNames#CONTENT_DISPOSITION}
*/
public static final AsciiString FILE = new AsciiString("file");
/**
* {@code "filename"}
* See {@link HttpHeaderNames#CONTENT_DISPOSITION}
*/
public static final AsciiString FILENAME = new AsciiString("filename");
/**
* {@code "form-data"}
* See {@link HttpHeaderNames#CONTENT_DISPOSITION}
*/
public static final AsciiString FORM_DATA = new AsciiString("form-data");
/**
* {@code "gzip"}
*/
public static final AsciiString GZIP = new AsciiString("gzip");
/**
* {@code "identity"}
*/
public static final AsciiString IDENTITY = new AsciiString("identity");
/**
* {@code "keep-alive"}
*/
public static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");
/**
* {@code "max-age"}
*/
public static final AsciiString MAX_AGE = new AsciiString("max-age");
/**
* {@code "max-stale"}
*/
public static final AsciiString MAX_STALE = new AsciiString("max-stale");
/**
* {@code "min-fresh"}
*/
public static final AsciiString MIN_FRESH = new AsciiString("min-fresh");
/**
* {@code "multipart/form-data"}
*/
public static final AsciiString MULTIPART_FORM_DATA = new AsciiString("multipart/form-data");
/**
* {@code "multipart/mixed"}
*/
public static final AsciiString MULTIPART_MIXED = new AsciiString("multipart/mixed");
/**
* {@code "must-revalidate"}
*/
public static final AsciiString MUST_REVALIDATE = new AsciiString("must-revalidate");
/**
* {@code "name"}
* See {@link HttpHeaderNames#CONTENT_DISPOSITION}
*/
public static final AsciiString NAME = new AsciiString("name");
/**
* {@code "no-cache"}
*/
public static final AsciiString NO_CACHE = new AsciiString("no-cache");
/**
* {@code "no-store"}
*/
public static final AsciiString NO_STORE = new AsciiString("no-store");
/**
* {@code "no-transform"}
*/
public static final AsciiString NO_TRANSFORM = new AsciiString("no-transform");
/**
* {@code "none"}
*/
public static final AsciiString NONE = new AsciiString("none");
/**
* {@code "only-if-cached"}
*/
public static final AsciiString ONLY_IF_CACHED = new AsciiString("only-if-cached");
/**
* {@code "private"}
*/
public static final AsciiString PRIVATE = new AsciiString("private");
/**
* {@code "proxy-revalidate"}
*/
public static final AsciiString PROXY_REVALIDATE = new AsciiString("proxy-revalidate");
/**
* {@code "public"}
*/
public static final AsciiString PUBLIC = new AsciiString("public");
/**
* {@code "quoted-printable"}
*/
public static final AsciiString QUOTED_PRINTABLE = new AsciiString("quoted-printable");
/**
* {@code "s-maxage"}
*/
public static final AsciiString S_MAXAGE = new AsciiString("s-maxage");
/**
* {@code "text/plain"}
*/
public static final AsciiString TEXT_PLAIN = new AsciiString("text/plain");
/**
* {@code "trailers"}
*/
public static final AsciiString TRAILERS = new AsciiString("trailers");
/**
* {@code "Upgrade"}
*/
public static final AsciiString UPGRADE = new AsciiString("Upgrade");
/**
* {@code "websocket"}
*/
public static final AsciiString WEBSOCKET = new AsciiString("websocket");
/**
* {@code "x-deflate"}
*/
public static final AsciiString X_DEFLATE = new AsciiString("x-deflate");
/**
* {@code "x-gzip"}
*/
public static final AsciiString X_GZIP = new AsciiString("x-gzip");
private HttpHeaderValues() { }
}

View File

@ -15,7 +15,6 @@
*/ */
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.TextHeaders; import io.netty.handler.codec.TextHeaders;
@ -24,520 +23,6 @@ import io.netty.handler.codec.TextHeaders;
* commonly used utility methods that accesses an {@link HttpMessage}. * commonly used utility methods that accesses an {@link HttpMessage}.
*/ */
public interface HttpHeaders extends TextHeaders { public interface HttpHeaders extends TextHeaders {
/**
* Standard HTTP header names.
* <p>
* These are all defined as lowercase to support HTTP/2 requirements while also not
* violating HTTP/1.x requirements. New header names should always be lowercase.
*/
final class Names {
/**
* {@code "accept"}
*/
public static final AsciiString ACCEPT = new AsciiString("accept");
/**
* {@code "accept-charset"}
*/
public static final AsciiString ACCEPT_CHARSET = new AsciiString("accept-charset");
/**
* {@code "accept-encoding"}
*/
public static final AsciiString ACCEPT_ENCODING = new AsciiString("accept-encoding");
/**
* {@code "accept-language"}
*/
public static final AsciiString ACCEPT_LANGUAGE = new AsciiString("accept-language");
/**
* {@code "accept-ranges"}
*/
public static final AsciiString ACCEPT_RANGES = new AsciiString("accept-ranges");
/**
* {@code "accept-patch"}
*/
public static final AsciiString ACCEPT_PATCH = new AsciiString("accept-patch");
/**
* {@code "access-control-allow-credentials"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_CREDENTIALS =
new AsciiString("access-control-allow-credentials");
/**
* {@code "access-control-allow-headers"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_HEADERS =
new AsciiString("access-control-allow-headers");
/**
* {@code "access-control-allow-methods"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_METHODS =
new AsciiString("access-control-allow-methods");
/**
* {@code "access-control-allow-origin"}
*/
public static final AsciiString ACCESS_CONTROL_ALLOW_ORIGIN =
new AsciiString("access-control-allow-origin");
/**
* {@code "access-control-expose-headers"}
*/
public static final AsciiString ACCESS_CONTROL_EXPOSE_HEADERS =
new AsciiString("access-control-expose-headers");
/**
* {@code "access-control-max-age"}
*/
public static final AsciiString ACCESS_CONTROL_MAX_AGE = new AsciiString("access-control-max-age");
/**
* {@code "access-control-request-headers"}
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_HEADERS =
new AsciiString("access-control-request-headers");
/**
* {@code "access-control-request-method"}
*/
public static final AsciiString ACCESS_CONTROL_REQUEST_METHOD =
new AsciiString("access-control-request-method");
/**
* {@code "age"}
*/
public static final AsciiString AGE = new AsciiString("age");
/**
* {@code "allow"}
*/
public static final AsciiString ALLOW = new AsciiString("allow");
/**
* {@code "authorization"}
*/
public static final AsciiString AUTHORIZATION = new AsciiString("authorization");
/**
* {@code "cache-control"}
*/
public static final AsciiString CACHE_CONTROL = new AsciiString("cache-control");
/**
* {@code "connection"}
*/
public static final AsciiString CONNECTION = new AsciiString("connection");
/**
* {@code "content-base"}
*/
public static final AsciiString CONTENT_BASE = new AsciiString("content-base");
/**
* {@code "content-encoding"}
*/
public static final AsciiString CONTENT_ENCODING = new AsciiString("content-encoding");
/**
* {@code "content-language"}
*/
public static final AsciiString CONTENT_LANGUAGE = new AsciiString("content-language");
/**
* {@code "content-length"}
*/
public static final AsciiString CONTENT_LENGTH = new AsciiString("content-length");
/**
* {@code "content-location"}
*/
public static final AsciiString CONTENT_LOCATION = new AsciiString("content-location");
/**
* {@code "content-transfer-encoding"}
*/
public static final AsciiString CONTENT_TRANSFER_ENCODING = new AsciiString("content-transfer-encoding");
/**
* {@code "content-disposition"}
*/
public static final AsciiString CONTENT_DISPOSITION = new AsciiString("content-disposition");
/**
* {@code "content-md5"}
*/
public static final AsciiString CONTENT_MD5 = new AsciiString("content-md5");
/**
* {@code "content-range"}
*/
public static final AsciiString CONTENT_RANGE = new AsciiString("content-range");
/**
* {@code "content-type"}
*/
public static final AsciiString CONTENT_TYPE = new AsciiString("content-type");
/**
* {@code "cookie"}
*/
public static final AsciiString COOKIE = new AsciiString("cookie");
/**
* {@code "date"}
*/
public static final AsciiString DATE = new AsciiString("date");
/**
* {@code "etag"}
*/
public static final AsciiString ETAG = new AsciiString("etag");
/**
* {@code "expect"}
*/
public static final AsciiString EXPECT = new AsciiString("expect");
/**
* {@code "expires"}
*/
public static final AsciiString EXPIRES = new AsciiString("expires");
/**
* {@code "from"}
*/
public static final AsciiString FROM = new AsciiString("from");
/**
* {@code "host"}
*/
public static final AsciiString HOST = new AsciiString("host");
/**
* {@code "if-match"}
*/
public static final AsciiString IF_MATCH = new AsciiString("if-match");
/**
* {@code "if-modified-since"}
*/
public static final AsciiString IF_MODIFIED_SINCE = new AsciiString("if-modified-since");
/**
* {@code "if-none-match"}
*/
public static final AsciiString IF_NONE_MATCH = new AsciiString("if-none-match");
/**
* {@code "if-range"}
*/
public static final AsciiString IF_RANGE = new AsciiString("if-range");
/**
* {@code "if-unmodified-since"}
*/
public static final AsciiString IF_UNMODIFIED_SINCE = new AsciiString("if-unmodified-since");
/**
* {@code "last-modified"}
*/
public static final AsciiString LAST_MODIFIED = new AsciiString("last-modified");
/**
* {@code "location"}
*/
public static final AsciiString LOCATION = new AsciiString("location");
/**
* {@code "max-forwards"}
*/
public static final AsciiString MAX_FORWARDS = new AsciiString("max-forwards");
/**
* {@code "origin"}
*/
public static final AsciiString ORIGIN = new AsciiString("origin");
/**
* {@code "pragma"}
*/
public static final AsciiString PRAGMA = new AsciiString("pragma");
/**
* {@code "proxy-authenticate"}
*/
public static final AsciiString PROXY_AUTHENTICATE = new AsciiString("proxy-authenticate");
/**
* {@code "proxy-authorization"}
*/
public static final AsciiString PROXY_AUTHORIZATION = new AsciiString("proxy-authorization");
/**
* {@code "range"}
*/
public static final AsciiString RANGE = new AsciiString("range");
/**
* {@code "referer"}
*/
public static final AsciiString REFERER = new AsciiString("referer");
/**
* {@code "retry-after"}
*/
public static final AsciiString RETRY_AFTER = new AsciiString("retry-after");
/**
* {@code "sec-websocket-key1"}
*/
public static final AsciiString SEC_WEBSOCKET_KEY1 = new AsciiString("sec-websocket-key1");
/**
* {@code "sec-websocket-key2"}
*/
public static final AsciiString SEC_WEBSOCKET_KEY2 = new AsciiString("sec-websocket-key2");
/**
* {@code "sec-websocket-location"}
*/
public static final AsciiString SEC_WEBSOCKET_LOCATION = new AsciiString("sec-websocket-location");
/**
* {@code "sec-websocket-origin"}
*/
public static final AsciiString SEC_WEBSOCKET_ORIGIN = new AsciiString("sec-websocket-origin");
/**
* {@code "sec-websocket-protocol"}
*/
public static final AsciiString SEC_WEBSOCKET_PROTOCOL = new AsciiString("sec-websocket-protocol");
/**
* {@code "sec-websocket-version"}
*/
public static final AsciiString SEC_WEBSOCKET_VERSION = new AsciiString("sec-websocket-version");
/**
* {@code "sec-websocket-key"}
*/
public static final AsciiString SEC_WEBSOCKET_KEY = new AsciiString("sec-websocket-key");
/**
* {@code "sec-websocket-accept"}
*/
public static final AsciiString SEC_WEBSOCKET_ACCEPT = new AsciiString("sec-websocket-accept");
/**
* {@code "sec-websocket-protocol"}
*/
public static final AsciiString SEC_WEBSOCKET_EXTENSIONS = new AsciiString("sec-websocket-extensions");
/**
* {@code "server"}
*/
public static final AsciiString SERVER = new AsciiString("server");
/**
* {@code "set-cookie"}
*/
public static final AsciiString SET_COOKIE = new AsciiString("set-cookie");
/**
* {@code "set-cookie2"}
*/
public static final AsciiString SET_COOKIE2 = new AsciiString("set-cookie2");
/**
* {@code "te"}
*/
public static final AsciiString TE = new AsciiString("te");
/**
* {@code "trailer"}
*/
public static final AsciiString TRAILER = new AsciiString("trailer");
/**
* {@code "transfer-encoding"}
*/
public static final AsciiString TRANSFER_ENCODING = new AsciiString("transfer-encoding");
/**
* {@code "upgrade"}
*/
public static final AsciiString UPGRADE = new AsciiString("upgrade");
/**
* {@code "user-agent"}
*/
public static final AsciiString USER_AGENT = new AsciiString("user-agent");
/**
* {@code "vary"}
*/
public static final AsciiString VARY = new AsciiString("vary");
/**
* {@code "via"}
*/
public static final AsciiString VIA = new AsciiString("via");
/**
* {@code "warning"}
*/
public static final AsciiString WARNING = new AsciiString("warning");
/**
* {@code "websocket-location"}
*/
public static final AsciiString WEBSOCKET_LOCATION = new AsciiString("websocket-location");
/**
* {@code "websocket-origin"}
*/
public static final AsciiString WEBSOCKET_ORIGIN = new AsciiString("websocket-origin");
/**
* {@code "websocket-protocol"}
*/
public static final AsciiString WEBSOCKET_PROTOCOL = new AsciiString("websocket-protocol");
/**
* {@code "www-authenticate"}
*/
public static final AsciiString WWW_AUTHENTICATE = new AsciiString("www-authenticate");
/**
* {@code "keep-alive"}
* @deprecated use {@link #CONNECTION}
*/
@Deprecated
public static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");
/**
* {@code "proxy-connection"}
* @deprecated use {@link #CONNECTION}
*/
@Deprecated
public static final AsciiString PROXY_CONNECTION = new AsciiString("proxy-connection");
private Names() {
}
}
/**
* Standard HTTP header values.
*/
final class Values {
/**
* {@code "application/x-www-form-urlencoded"}
*/
public static final AsciiString APPLICATION_X_WWW_FORM_URLENCODED =
new AsciiString("application/x-www-form-urlencoded");
/**
* {@code "application/octet-stream"}
*/
public static final AsciiString APPLICATION_OCTET_STREAM = new AsciiString("application/octet-stream");
/**
* {@code "text/plain"}
*/
public static final AsciiString TEXT_PLAIN = new AsciiString("text/plain");
/**
* {@code "base64"}
*/
public static final AsciiString BASE64 = new AsciiString("base64");
/**
* {@code "binary"}
*/
public static final AsciiString BINARY = new AsciiString("binary");
/**
* {@code "boundary"}
*/
public static final AsciiString BOUNDARY = new AsciiString("boundary");
/**
* {@code "bytes"}
*/
public static final AsciiString BYTES = new AsciiString("bytes");
/**
* {@code "charset"}
*/
public static final AsciiString CHARSET = new AsciiString("charset");
/**
* {@code "chunked"}
*/
public static final AsciiString CHUNKED = new AsciiString("chunked");
/**
* {@code "close"}
*/
public static final AsciiString CLOSE = new AsciiString("close");
/**
* {@code "compress"}
*/
public static final AsciiString COMPRESS = new AsciiString("compress");
/**
* {@code "100-continue"}
*/
public static final AsciiString CONTINUE = new AsciiString("100-continue");
/**
* {@code "deflate"}
*/
public static final AsciiString DEFLATE = new AsciiString("deflate");
/**
* {@code "x-deflate"}
*/
public static final AsciiString XDEFLATE = new AsciiString("deflate");
/**
* {@code "gzip"}
*/
public static final AsciiString GZIP = new AsciiString("gzip");
/**
* {@code "x-gzip"}
*/
public static final AsciiString XGZIP = new AsciiString("x-gzip");
/**
* {@code "identity"}
*/
public static final AsciiString IDENTITY = new AsciiString("identity");
/**
* {@code "keep-alive"}
*/
public static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");
/**
* {@code "max-age"}
*/
public static final AsciiString MAX_AGE = new AsciiString("max-age");
/**
* {@code "max-stale"}
*/
public static final AsciiString MAX_STALE = new AsciiString("max-stale");
/**
* {@code "min-fresh"}
*/
public static final AsciiString MIN_FRESH = new AsciiString("min-fresh");
/**
* {@code "multipart/form-data"}
*/
public static final AsciiString MULTIPART_FORM_DATA = new AsciiString("multipart/form-data");
/**
* {@code "multipart/mixed"}
*/
public static final AsciiString MULTIPART_MIXED = new AsciiString("multipart/mixed");
/**
* {@code "must-revalidate"}
*/
public static final AsciiString MUST_REVALIDATE = new AsciiString("must-revalidate");
/**
* {@code "no-cache"}
*/
public static final AsciiString NO_CACHE = new AsciiString("no-cache");
/**
* {@code "no-store"}
*/
public static final AsciiString NO_STORE = new AsciiString("no-store");
/**
* {@code "no-transform"}
*/
public static final AsciiString NO_TRANSFORM = new AsciiString("no-transform");
/**
* {@code "none"}
*/
public static final AsciiString NONE = new AsciiString("none");
/**
* {@code "only-if-cached"}
*/
public static final AsciiString ONLY_IF_CACHED = new AsciiString("only-if-cached");
/**
* {@code "private"}
*/
public static final AsciiString PRIVATE = new AsciiString("private");
/**
* {@code "proxy-revalidate"}
*/
public static final AsciiString PROXY_REVALIDATE = new AsciiString("proxy-revalidate");
/**
* {@code "public"}
*/
public static final AsciiString PUBLIC = new AsciiString("public");
/**
* {@code "quoted-printable"}
*/
public static final AsciiString QUOTED_PRINTABLE = new AsciiString("quoted-printable");
/**
* {@code "s-maxage"}
*/
public static final AsciiString S_MAXAGE = new AsciiString("s-maxage");
/**
* {@code "trailers"}
*/
public static final AsciiString TRAILERS = new AsciiString("trailers");
/**
* {@code "Upgrade"}
*/
public static final AsciiString UPGRADE = new AsciiString("Upgrade");
/**
* {@code "WebSocket"}
*/
public static final AsciiString WEBSOCKET = new AsciiString("WebSocket");
/**
* {@code "name"}
* See {@link Names#CONTENT_DISPOSITION}
*/
public static final AsciiString NAME = new AsciiString("name");
/**
* {@code "filename"}
* See {@link Names#CONTENT_DISPOSITION}
*/
public static final AsciiString FILENAME = new AsciiString("filename");
/**
* {@code "form-data"}
* See {@link Names#CONTENT_DISPOSITION}
*/
public static final AsciiString FORM_DATA = new AsciiString("form-data");
/**
* {@code "attachment"}
* See {@link Names#CONTENT_DISPOSITION}
*/
public static final AsciiString ATTACHMENT = new AsciiString("attachment");
/**
* {@code "file"}
* See {@link Names#CONTENT_DISPOSITION}
*/
public static final AsciiString FILE = new AsciiString("file");
private Values() {
}
}
@Override @Override
HttpHeaders add(CharSequence name, CharSequence value); HttpHeaders add(CharSequence name, CharSequence value);

View File

@ -58,7 +58,7 @@ public class HttpObjectAggregator
HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER); HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
static { static {
TOO_LARGE.headers().setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); TOO_LARGE.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
} }
/** /**
@ -142,7 +142,7 @@ public class HttpObjectAggregator
protected void finishAggregation(FullHttpMessage aggregated) throws Exception { protected void finishAggregation(FullHttpMessage aggregated) throws Exception {
// Set the 'Content-Length' header. // Set the 'Content-Length' header.
aggregated.headers().set( aggregated.headers().set(
HttpHeaders.Names.CONTENT_LENGTH, HttpHeaderNames.CONTENT_LENGTH,
String.valueOf(aggregated.content().readableBytes())); String.valueOf(aggregated.content().readableBytes()));
} }

View File

@ -20,7 +20,6 @@ import io.netty.buffer.ByteBufProcessor;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
@ -422,7 +421,7 @@ public abstract class HttpObjectDecoder extends ReplayingDecoder<State> {
// - https://github.com/netty/netty/issues/222 // - https://github.com/netty/netty/issues/222
if (code >= 100 && code < 200) { if (code >= 100 && code < 200) {
// One exception: Hixie 76 websocket handshake response // One exception: Hixie 76 websocket handshake response
return !(code == 101 && !res.headers().contains(HttpHeaders.Names.SEC_WEBSOCKET_ACCEPT)); return !(code == 101 && !res.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT));
} }
switch (code) { switch (code) {
@ -571,9 +570,9 @@ public abstract class HttpObjectDecoder extends ReplayingDecoder<State> {
} else { } else {
splitHeader(line); splitHeader(line);
CharSequence headerName = name; CharSequence headerName = name;
if (!AsciiString.equalsIgnoreCase(headerName, HttpHeaders.Names.CONTENT_LENGTH) && if (!HttpHeaderNames.CONTENT_LENGTH.equalsIgnoreCase(headerName) &&
!AsciiString.equalsIgnoreCase(headerName, HttpHeaders.Names.TRANSFER_ENCODING) && !HttpHeaderNames.TRANSFER_ENCODING.equalsIgnoreCase(headerName) &&
!AsciiString.equalsIgnoreCase(headerName, HttpHeaders.Names.TRAILER)) { !HttpHeaderNames.TRAILER.equalsIgnoreCase(headerName)) {
trailer.trailingHeaders().add(headerName, value); trailer.trailingHeaders().add(headerName, value);
} }
lastHeader = name; lastHeader = name;

View File

@ -14,11 +14,6 @@
*/ */
package io.netty.handler.codec.http; package io.netty.handler.codec.http;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.UPGRADE;
import static io.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
@ -35,6 +30,9 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;
/** /**
* A server-side handler that receives HTTP requests and optionally performs a protocol switch if * A server-side handler that receives HTTP requests and optionally performs a protocol switch if
* the requested protocol is supported. Once an upgrade is performed, this handler removes itself * the requested protocol is supported. Once an upgrade is performed, this handler removes itself
@ -58,13 +56,13 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
public interface UpgradeCodec { public interface UpgradeCodec {
/** /**
* Returns the name of the protocol supported by this codec, as indicated by the * Returns the name of the protocol supported by this codec, as indicated by the
* {@link HttpHeaders.Names#UPGRADE} header. * {@link HttpHeaderNames#UPGRADE} header.
*/ */
String protocol(); String protocol();
/** /**
* Gets all protocol-specific headers required by this protocol for a successful upgrade. * Gets all protocol-specific headers required by this protocol for a successful upgrade.
* Any supplied header will be required to appear in the {@link HttpHeaders.Names#CONNECTION} header as well. * Any supplied header will be required to appear in the {@link HttpHeaderNames#CONNECTION} header as well.
*/ */
Collection<String> requiredUpgradeHeaders(); Collection<String> requiredUpgradeHeaders();
@ -82,7 +80,7 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
* @param upgradeRequest the request that triggered the upgrade to this protocol. The * @param upgradeRequest the request that triggered the upgrade to this protocol. The
* upgraded protocol is responsible for sending the response. * upgraded protocol is responsible for sending the response.
* @param upgradeResponse a 101 Switching Protocols response that is populated with the * @param upgradeResponse a 101 Switching Protocols response that is populated with the
* {@link HttpHeaders.Names#CONNECTION} and {@link HttpHeaders.Names#UPGRADE} headers. * {@link HttpHeaderNames#CONNECTION} and {@link HttpHeaderNames#UPGRADE} headers.
* The protocol is required to send this before sending any other frames back to the client. * The protocol is required to send this before sending any other frames back to the client.
* The headers may be augmented as necessary by the protocol before sending. * The headers may be augmented as necessary by the protocol before sending.
*/ */
@ -237,11 +235,11 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
* Determines whether or not the message is an HTTP upgrade request. * Determines whether or not the message is an HTTP upgrade request.
*/ */
private static boolean isUpgradeRequest(HttpObject msg) { private static boolean isUpgradeRequest(HttpObject msg) {
return msg instanceof HttpRequest && ((HttpRequest) msg).headers().get(UPGRADE) != null; return msg instanceof HttpRequest && ((HttpRequest) msg).headers().get(HttpHeaderNames.UPGRADE) != null;
} }
/** /**
* Attempts to upgrade to the protocol(s) identified by the {@link HttpHeaders.Names#UPGRADE} header (if provided * Attempts to upgrade to the protocol(s) identified by the {@link HttpHeaderNames#UPGRADE} header (if provided
* in the request). * in the request).
* *
* @param ctx the context for this handler. * @param ctx the context for this handler.
@ -250,7 +248,7 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
*/ */
private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) { private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) {
// Select the best protocol based on those requested in the UPGRADE header. // Select the best protocol based on those requested in the UPGRADE header.
CharSequence upgradeHeader = request.headers().get(UPGRADE); CharSequence upgradeHeader = request.headers().get(HttpHeaderNames.UPGRADE);
final UpgradeCodec upgradeCodec = selectUpgradeCodec(upgradeHeader); final UpgradeCodec upgradeCodec = selectUpgradeCodec(upgradeHeader);
if (upgradeCodec == null) { if (upgradeCodec == null) {
// None of the requested protocols are supported, don't upgrade. // None of the requested protocols are supported, don't upgrade.
@ -258,7 +256,7 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
} }
// Make sure the CONNECTION header is present. // Make sure the CONNECTION header is present.
CharSequence connectionHeader = request.headers().get(CONNECTION); CharSequence connectionHeader = request.headers().get(HttpHeaderNames.CONNECTION);
if (connectionHeader == null) { if (connectionHeader == null) {
return false; return false;
} }
@ -266,7 +264,7 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
// Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers. // Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers.
Collection<String> requiredHeaders = upgradeCodec.requiredUpgradeHeaders(); Collection<String> requiredHeaders = upgradeCodec.requiredUpgradeHeaders();
Set<CharSequence> values = splitHeader(connectionHeader); Set<CharSequence> values = splitHeader(connectionHeader);
if (!values.contains(UPGRADE) || !values.containsAll(requiredHeaders)) { if (!values.contains(HttpHeaderNames.UPGRADE) || !values.containsAll(requiredHeaders)) {
return false; return false;
} }
@ -336,9 +334,9 @@ public class HttpServerUpgradeHandler extends HttpObjectAggregator {
*/ */
private static FullHttpResponse createUpgradeResponse(UpgradeCodec upgradeCodec) { private static FullHttpResponse createUpgradeResponse(UpgradeCodec upgradeCodec) {
DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS);
res.headers().add(CONNECTION, UPGRADE); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
res.headers().add(UPGRADE, upgradeCodec.protocol()); res.headers().add(HttpHeaderNames.UPGRADE, upgradeCodec.protocol());
res.headers().add(CONTENT_LENGTH, "0"); res.headers().add(HttpHeaderNames.CONTENT_LENGTH, "0");
return res; return res;
} }

View File

@ -18,7 +18,7 @@ package io.netty.handler.codec.http.cors;
import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders; import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
@ -511,8 +511,8 @@ public final class CorsConfig {
*/ */
public CorsConfig build() { public CorsConfig build() {
if (preflightHeaders.isEmpty() && !noPreflightHeaders) { if (preflightHeaders.isEmpty() && !noPreflightHeaders) {
preflightHeaders.put(Names.DATE, new DateValueGenerator()); preflightHeaders.put(HttpHeaderNames.DATE, new DateValueGenerator());
preflightHeaders.put(Names.CONTENT_LENGTH, new ConstantValueGenerator("0")); preflightHeaders.put(HttpHeaderNames.CONTENT_LENGTH, new ConstantValueGenerator("0"));
} }
return new CorsConfig(this); return new CorsConfig(this);
} }

View File

@ -20,16 +20,16 @@ import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.InternalLoggerFactory;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.util.ReferenceCountUtil.release; import static io.netty.util.ReferenceCountUtil.*;
/** /**
* Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests. * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests.
@ -88,7 +88,7 @@ public class CorsHandler extends ChannelHandlerAdapter {
} }
private boolean setOrigin(final HttpResponse response) { private boolean setOrigin(final HttpResponse response) {
final CharSequence origin = request.headers().get(ORIGIN); final CharSequence origin = request.headers().get(HttpHeaderNames.ORIGIN);
if (origin != null) { if (origin != null) {
if ("null".equals(origin) && config.isNullOriginAllowed()) { if ("null".equals(origin) && config.isNullOriginAllowed()) {
setAnyOrigin(response); setAnyOrigin(response);
@ -118,7 +118,7 @@ public class CorsHandler extends ChannelHandlerAdapter {
return true; return true;
} }
final CharSequence origin = request.headers().get(ORIGIN); final CharSequence origin = request.headers().get(HttpHeaderNames.ORIGIN);
if (origin == null) { if (origin == null) {
// Not a CORS request so we cannot validate it. It may be a non CORS request. // Not a CORS request so we cannot validate it. It may be a non CORS request.
return true; return true;
@ -132,11 +132,11 @@ public class CorsHandler extends ChannelHandlerAdapter {
} }
private void echoRequestOrigin(final HttpResponse response) { private void echoRequestOrigin(final HttpResponse response) {
setOrigin(response, request.headers().get(ORIGIN)); setOrigin(response, request.headers().get(HttpHeaderNames.ORIGIN));
} }
private static void setVaryHeader(final HttpResponse response) { private static void setVaryHeader(final HttpResponse response) {
response.headers().set(VARY, ORIGIN); response.headers().set(HttpHeaderNames.VARY, HttpHeaderNames.ORIGIN);
} }
private static void setAnyOrigin(final HttpResponse response) { private static void setAnyOrigin(final HttpResponse response) {
@ -144,38 +144,38 @@ public class CorsHandler extends ChannelHandlerAdapter {
} }
private static void setOrigin(final HttpResponse response, final CharSequence origin) { private static void setOrigin(final HttpResponse response, final CharSequence origin) {
response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
} }
private void setAllowCredentials(final HttpResponse response) { private void setAllowCredentials(final HttpResponse response) {
if (config.isCredentialsAllowed()) { if (config.isCredentialsAllowed()) {
response.headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
} }
} }
private static boolean isPreflightRequest(final HttpRequest request) { private static boolean isPreflightRequest(final HttpRequest request) {
final HttpHeaders headers = request.headers(); final HttpHeaders headers = request.headers();
return request.method().equals(OPTIONS) && return request.method().equals(OPTIONS) &&
headers.contains(ORIGIN) && headers.contains(HttpHeaderNames.ORIGIN) &&
headers.contains(ACCESS_CONTROL_REQUEST_METHOD); headers.contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD);
} }
private void setExposeHeaders(final HttpResponse response) { private void setExposeHeaders(final HttpResponse response) {
if (!config.exposedHeaders().isEmpty()) { if (!config.exposedHeaders().isEmpty()) {
response.headers().set(ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders());
} }
} }
private void setAllowMethods(final HttpResponse response) { private void setAllowMethods(final HttpResponse response) {
response.headers().setObject(ACCESS_CONTROL_ALLOW_METHODS, config.allowedRequestMethods()); response.headers().setObject(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, config.allowedRequestMethods());
} }
private void setAllowHeaders(final HttpResponse response) { private void setAllowHeaders(final HttpResponse response) {
response.headers().set(ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders()); response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders());
} }
private void setMaxAge(final HttpResponse response) { private void setMaxAge(final HttpResponse response) {
response.headers().setLong(ACCESS_CONTROL_MAX_AGE, config.maxAge()); response.headers().setLong(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, config.maxAge());
} }
@Override @Override

View File

@ -17,7 +17,8 @@ package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelException; import io.netty.channel.ChannelException;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -132,12 +133,12 @@ public class DiskFileUpload extends AbstractDiskHttpData implements FileUpload {
// Should not occur. // Should not occur.
} }
return HttpPostBodyUtil.CONTENT_DISPOSITION + ": " + return HttpHeaderNames.CONTENT_DISPOSITION + ": " +
HttpPostBodyUtil.FORM_DATA + "; " + HttpPostBodyUtil.NAME + "=\"" + getName() + HttpHeaderValues.FORM_DATA + "; " + HttpHeaderValues.NAME + "=\"" + getName() +
"\"; " + HttpPostBodyUtil.FILENAME + "=\"" + filename + "\"\r\n" + "\"; " + HttpHeaderValues.FILENAME + "=\"" + filename + "\"\r\n" +
HttpHeaders.Names.CONTENT_TYPE + ": " + contentType + HttpHeaderNames.CONTENT_TYPE + ": " + contentType +
(getCharset() != null? "; " + HttpHeaders.Values.CHARSET + '=' + getCharset() + "\r\n" : "\r\n") + (getCharset() != null? "; " + HttpHeaderValues.CHARSET + '=' + getCharset() + "\r\n" : "\r\n") +
HttpHeaders.Names.CONTENT_LENGTH + ": " + length() + "\r\n" + HttpHeaderNames.CONTENT_LENGTH + ": " + length() + "\r\n" +
"Completed: " + isCompleted() + "Completed: " + isCompleted() +
"\r\nIsInMemory: " + isInMemory() + "\r\nRealFile: " + "\r\nIsInMemory: " + isInMemory() + "\r\nRealFile: " +
(file != null ? file.getAbsolutePath() : "null") + " DefaultDeleteAfter: " + (file != null ? file.getAbsolutePath() : "null") + " DefaultDeleteAfter: " +

View File

@ -16,10 +16,7 @@
package io.netty.handler.codec.http.multipart; package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
/** /**
* Shared Static object between HttpMessageDecoder, HttpPostRequestDecoder and HttpPostRequestEncoder * Shared Static object between HttpMessageDecoder, HttpPostRequestDecoder and HttpPostRequestEncoder
@ -27,54 +24,16 @@ import java.nio.charset.Charset;
final class HttpPostBodyUtil { final class HttpPostBodyUtil {
public static final int chunkSize = 8096; public static final int chunkSize = 8096;
/**
* HTTP content disposition header name.
*/
public static final String CONTENT_DISPOSITION = HttpHeaders.Names.CONTENT_DISPOSITION.toString();
public static final String NAME = HttpHeaders.Values.NAME.toString();
public static final String FILENAME = HttpHeaders.Values.FILENAME.toString();
/**
* Content-disposition value for form data.
*/
public static final String FORM_DATA = HttpHeaders.Values.FORM_DATA.toString();
/**
* Content-disposition value for file attachment.
*/
public static final String ATTACHMENT = HttpHeaders.Values.ATTACHMENT.toString();
/**
* Content-disposition value for file attachment.
*/
public static final String FILE = HttpHeaders.Values.FILE.toString();
/**
* HTTP content type body attribute for multiple uploads.
*/
public static final String MULTIPART_MIXED = HttpHeaders.Values.MULTIPART_MIXED.toString();
/**
* Charset for 8BIT
*/
public static final Charset ISO_8859_1 = CharsetUtil.ISO_8859_1;
/**
* Charset for 7BIT
*/
public static final Charset US_ASCII = CharsetUtil.US_ASCII;
/** /**
* Default Content-Type in binary form * Default Content-Type in binary form
*/ */
public static final String DEFAULT_BINARY_CONTENT_TYPE = HttpHeaders.Values.APPLICATION_OCTET_STREAM.toString(); public static final String DEFAULT_BINARY_CONTENT_TYPE = HttpHeaderValues.APPLICATION_OCTET_STREAM.toString();
/** /**
* Default Content-Type in Text form * Default Content-Type in Text form
*/ */
public static final String DEFAULT_TEXT_CONTENT_TYPE = HttpHeaders.Values.TEXT_PLAIN.toString(); public static final String DEFAULT_TEXT_CONTENT_TYPE = HttpHeaderValues.TEXT_PLAIN.toString();
/** /**
* Allowed mechanism for multipart * Allowed mechanism for multipart

View File

@ -18,7 +18,8 @@ package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpConstants; import io.netty.handler.codec.http.HttpConstants;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.multipart.HttpPostBodyUtil.SeekAheadNoBackArrayException; import io.netty.handler.codec.http.multipart.HttpPostBodyUtil.SeekAheadNoBackArrayException;
@ -28,6 +29,7 @@ import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDec
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.MultiPartStatus; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.MultiPartStatus;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.NotEnoughDataDecoderException; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.NotEnoughDataDecoderException;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
import java.io.IOException; import java.io.IOException;
@ -181,7 +183,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
this.factory = factory; this.factory = factory;
// Fill default values // Fill default values
setMultipart(this.request.headers().getAndConvert(HttpHeaders.Names.CONTENT_TYPE)); setMultipart(this.request.headers().getAndConvert(HttpHeaderNames.CONTENT_TYPE));
if (request instanceof HttpContent) { if (request instanceof HttpContent) {
// Offer automatically if the given request is als type of HttpContent // Offer automatically if the given request is als type of HttpContent
// See #1089 // See #1089
@ -489,7 +491,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
case FIELD: { case FIELD: {
// Now get value according to Content-Type and Charset // Now get value according to Content-Type and Charset
Charset localCharset = null; Charset localCharset = null;
Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaders.Values.CHARSET); Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaderValues.CHARSET);
if (charsetAttribute != null) { if (charsetAttribute != null) {
try { try {
localCharset = Charset.forName(charsetAttribute.getValue()); localCharset = Charset.forName(charsetAttribute.getValue());
@ -497,7 +499,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} }
} }
Attribute nameAttribute = currentFieldAttributes.get(HttpPostBodyUtil.NAME); Attribute nameAttribute = currentFieldAttributes.get(HttpHeaderValues.NAME);
if (currentAttribute == null) { if (currentAttribute == null) {
try { try {
currentAttribute = factory.createAttribute(request, currentAttribute = factory.createAttribute(request,
@ -661,13 +663,13 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
return null; return null;
} }
String[] contents = splitMultipartHeader(newline); String[] contents = splitMultipartHeader(newline);
if (contents[0].equalsIgnoreCase(HttpPostBodyUtil.CONTENT_DISPOSITION)) { if (HttpHeaderNames.CONTENT_DISPOSITION.equalsIgnoreCase(contents[0])) {
boolean checkSecondArg; boolean checkSecondArg;
if (currentStatus == MultiPartStatus.DISPOSITION) { if (currentStatus == MultiPartStatus.DISPOSITION) {
checkSecondArg = contents[1].equalsIgnoreCase(HttpPostBodyUtil.FORM_DATA); checkSecondArg = HttpHeaderValues.FORM_DATA.equalsIgnoreCase(contents[1]);
} else { } else {
checkSecondArg = contents[1].equalsIgnoreCase(HttpPostBodyUtil.ATTACHMENT) checkSecondArg = HttpHeaderValues.ATTACHMENT.equalsIgnoreCase(contents[1])
|| contents[1].equalsIgnoreCase(HttpPostBodyUtil.FILE); || HttpHeaderValues.FILE.equalsIgnoreCase(contents[1]);
} }
if (checkSecondArg) { if (checkSecondArg) {
// read next values and store them in the map as Attribute // read next values and store them in the map as Attribute
@ -679,7 +681,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
String value = values[1]; String value = values[1];
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
if (HttpPostBodyUtil.FILENAME.equals(name)) { if (HttpHeaderValues.FILENAME.contentEquals(name)) {
// filename value is quoted string so strip them // filename value is quoted string so strip them
value = value.substring(1, value.length() - 1); value = value.substring(1, value.length() - 1);
} else { } else {
@ -695,31 +697,31 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
currentFieldAttributes.put(attribute.getName(), attribute); currentFieldAttributes.put(attribute.getName(), attribute);
} }
} }
} else if (contents[0].equalsIgnoreCase(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING.toString())) { } else if (HttpHeaderNames.CONTENT_TRANSFER_ENCODING.equalsIgnoreCase(contents[0])) {
Attribute attribute; Attribute attribute;
try { try {
attribute = factory.createAttribute(request, HttpHeaders.Names.CONTENT_TRANSFER_ENCODING.toString(), attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_TRANSFER_ENCODING.toString(),
cleanString(contents[1])); cleanString(contents[1]));
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} }
currentFieldAttributes.put(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING.toString(), attribute); currentFieldAttributes.put(HttpHeaderNames.CONTENT_TRANSFER_ENCODING.toString(), attribute);
} else if (contents[0].equalsIgnoreCase(HttpHeaders.Names.CONTENT_LENGTH.toString())) { } else if (HttpHeaderNames.CONTENT_LENGTH.equalsIgnoreCase(contents[0])) {
Attribute attribute; Attribute attribute;
try { try {
attribute = factory.createAttribute(request, HttpHeaders.Names.CONTENT_LENGTH.toString(), attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_LENGTH.toString(),
cleanString(contents[1])); cleanString(contents[1]));
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} }
currentFieldAttributes.put(HttpHeaders.Names.CONTENT_LENGTH.toString(), attribute); currentFieldAttributes.put(HttpHeaderNames.CONTENT_LENGTH.toString(), attribute);
} else if (contents[0].equalsIgnoreCase(HttpHeaders.Names.CONTENT_TYPE.toString())) { } else if (HttpHeaderNames.CONTENT_TYPE.equalsIgnoreCase(contents[0])) {
// Take care of possible "multipart/mixed" // Take care of possible "multipart/mixed"
if (contents[1].equalsIgnoreCase(HttpPostBodyUtil.MULTIPART_MIXED)) { if (HttpHeaderValues.MULTIPART_MIXED.equalsIgnoreCase(contents[1])) {
if (currentStatus == MultiPartStatus.DISPOSITION) { if (currentStatus == MultiPartStatus.DISPOSITION) {
String values = StringUtil.substringAfter(contents[2], '='); String values = StringUtil.substringAfter(contents[2], '=');
multipartMixedBoundary = "--" + values; multipartMixedBoundary = "--" + values;
@ -730,18 +732,18 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
} }
} else { } else {
for (int i = 1; i < contents.length; i++) { for (int i = 1; i < contents.length; i++) {
if (contents[i].toLowerCase().startsWith(HttpHeaders.Values.CHARSET.toString())) { if (contents[i].toLowerCase().startsWith(HttpHeaderValues.CHARSET.toString())) {
String values = StringUtil.substringAfter(contents[i], '='); String values = StringUtil.substringAfter(contents[i], '=');
Attribute attribute; Attribute attribute;
try { try {
attribute = factory.createAttribute(request, HttpHeaders.Values.CHARSET.toString(), attribute = factory.createAttribute(request, HttpHeaderValues.CHARSET.toString(),
cleanString(values)); cleanString(values));
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} }
currentFieldAttributes.put(HttpHeaders.Values.CHARSET.toString(), attribute); currentFieldAttributes.put(HttpHeaderValues.CHARSET.toString(), attribute);
} else { } else {
Attribute attribute; Attribute attribute;
try { try {
@ -761,7 +763,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
} }
} }
// Is it a FileUpload // Is it a FileUpload
Attribute filenameAttribute = currentFieldAttributes.get(HttpPostBodyUtil.FILENAME); Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
if (currentStatus == MultiPartStatus.DISPOSITION) { if (currentStatus == MultiPartStatus.DISPOSITION) {
if (filenameAttribute != null) { if (filenameAttribute != null) {
// FileUpload // FileUpload
@ -798,7 +800,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
protected InterfaceHttpData getFileUpload(String delimiter) { protected InterfaceHttpData getFileUpload(String delimiter) {
// eventually restart from existing FileUpload // eventually restart from existing FileUpload
// Now get value according to Content-Type and Charset // Now get value according to Content-Type and Charset
Attribute encoding = currentFieldAttributes.get(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING.toString()); Attribute encoding = currentFieldAttributes.get(HttpHeaderNames.CONTENT_TRANSFER_ENCODING.toString());
Charset localCharset = charset; Charset localCharset = charset;
// Default // Default
TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7; TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7;
@ -810,9 +812,9 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
throw new ErrorDataDecoderException(e); throw new ErrorDataDecoderException(e);
} }
if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value())) { if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value())) {
localCharset = HttpPostBodyUtil.US_ASCII; localCharset = CharsetUtil.US_ASCII;
} else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value())) { } else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value())) {
localCharset = HttpPostBodyUtil.ISO_8859_1; localCharset = CharsetUtil.ISO_8859_1;
mechanism = TransferEncodingMechanism.BIT8; mechanism = TransferEncodingMechanism.BIT8;
} else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) { } else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) {
// no real charset, so let the default // no real charset, so let the default
@ -821,7 +823,7 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
throw new ErrorDataDecoderException("TransferEncoding Unknown: " + code); throw new ErrorDataDecoderException("TransferEncoding Unknown: " + code);
} }
} }
Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaders.Values.CHARSET.toString()); Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaderValues.CHARSET.toString());
if (charsetAttribute != null) { if (charsetAttribute != null) {
try { try {
localCharset = Charset.forName(charsetAttribute.getValue()); localCharset = Charset.forName(charsetAttribute.getValue());
@ -830,13 +832,13 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
} }
} }
if (currentFileUpload == null) { if (currentFileUpload == null) {
Attribute filenameAttribute = currentFieldAttributes.get(HttpPostBodyUtil.FILENAME); Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
Attribute nameAttribute = currentFieldAttributes.get(HttpPostBodyUtil.NAME); Attribute nameAttribute = currentFieldAttributes.get(HttpHeaderValues.NAME);
Attribute contentTypeAttribute = currentFieldAttributes.get(HttpHeaders.Names.CONTENT_TYPE); Attribute contentTypeAttribute = currentFieldAttributes.get(HttpHeaderNames.CONTENT_TYPE);
if (contentTypeAttribute == null) { if (contentTypeAttribute == null) {
throw new ErrorDataDecoderException("Content-Type is absent but required"); throw new ErrorDataDecoderException("Content-Type is absent but required");
} }
Attribute lengthAttribute = currentFieldAttributes.get(HttpHeaders.Names.CONTENT_LENGTH); Attribute lengthAttribute = currentFieldAttributes.get(HttpHeaderNames.CONTENT_LENGTH);
long size; long size;
try { try {
size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L; size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L;
@ -932,11 +934,11 @@ public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequest
* Mixed mode * Mixed mode
*/ */
private void cleanMixedAttributes() { private void cleanMixedAttributes() {
currentFieldAttributes.remove(HttpHeaders.Values.CHARSET); currentFieldAttributes.remove(HttpHeaderValues.CHARSET);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_LENGTH); currentFieldAttributes.remove(HttpHeaderNames.CONTENT_LENGTH);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING); currentFieldAttributes.remove(HttpHeaderNames.CONTENT_TRANSFER_ENCODING);
currentFieldAttributes.remove(HttpHeaders.Names.CONTENT_TYPE); currentFieldAttributes.remove(HttpHeaderNames.CONTENT_TYPE);
currentFieldAttributes.remove(HttpPostBodyUtil.FILENAME); currentFieldAttributes.remove(HttpHeaderValues.FILENAME);
} }
/** /**

View File

@ -18,7 +18,8 @@ package io.netty.handler.codec.http.multipart;
import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http.HttpConstants; import io.netty.handler.codec.http.HttpConstants;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
@ -139,8 +140,8 @@ public class HttpPostRequestDecoder implements InterfaceHttpPostRequestDecoder {
* @return True if the request is a Multipart request * @return True if the request is a Multipart request
*/ */
public static boolean isMultipart(HttpRequest request) { public static boolean isMultipart(HttpRequest request) {
if (request.headers().contains(HttpHeaders.Names.CONTENT_TYPE)) { if (request.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {
return getMultipartDataBoundary(request.headers().getAndConvert(HttpHeaders.Names.CONTENT_TYPE)) != null; return getMultipartDataBoundary(request.headers().getAndConvert(HttpHeaderNames.CONTENT_TYPE)) != null;
} else { } else {
return false; return false;
} }
@ -155,15 +156,15 @@ public class HttpPostRequestDecoder implements InterfaceHttpPostRequestDecoder {
// Check if Post using "multipart/form-data; boundary=--89421926422648 [; charset=xxx]" // Check if Post using "multipart/form-data; boundary=--89421926422648 [; charset=xxx]"
String[] headerContentType = splitHeaderContentType(contentType); String[] headerContentType = splitHeaderContentType(contentType);
if (headerContentType[0].toLowerCase().startsWith( if (headerContentType[0].toLowerCase().startsWith(
HttpHeaders.Values.MULTIPART_FORM_DATA.toString())) { HttpHeaderValues.MULTIPART_FORM_DATA.toString())) {
int mrank; int mrank;
int crank; int crank;
if (headerContentType[1].toLowerCase().startsWith( if (headerContentType[1].toLowerCase().startsWith(
HttpHeaders.Values.BOUNDARY.toString())) { HttpHeaderValues.BOUNDARY.toString())) {
mrank = 1; mrank = 1;
crank = 2; crank = 2;
} else if (headerContentType[2].toLowerCase().startsWith( } else if (headerContentType[2].toLowerCase().startsWith(
HttpHeaders.Values.BOUNDARY.toString())) { HttpHeaderValues.BOUNDARY.toString())) {
mrank = 2; mrank = 2;
crank = 1; crank = 1;
} else { } else {
@ -181,7 +182,7 @@ public class HttpPostRequestDecoder implements InterfaceHttpPostRequestDecoder {
} }
} }
if (headerContentType[crank].toLowerCase().startsWith( if (headerContentType[crank].toLowerCase().startsWith(
HttpHeaders.Values.CHARSET.toString())) { HttpHeaderValues.CHARSET.toString())) {
String charset = StringUtil.substringAfter(headerContentType[crank], '='); String charset = StringUtil.substringAfter(headerContentType[crank], '=');
if (charset != null) { if (charset != null) {
return new String[] {"--" + boundary, charset}; return new String[] {"--" + boundary, charset};

View File

@ -16,9 +16,7 @@
package io.netty.handler.codec.http.multipart; package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpContent;
@ -26,7 +24,9 @@ import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpConstants; import io.netty.handler.codec.http.HttpConstants;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
@ -505,14 +505,14 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
internal.addValue("--" + multipartDataBoundary + "\r\n"); internal.addValue("--" + multipartDataBoundary + "\r\n");
// content-disposition: form-data; name="field1" // content-disposition: form-data; name="field1"
Attribute attribute = (Attribute) data; Attribute attribute = (Attribute) data;
internal.addValue(HttpPostBodyUtil.CONTENT_DISPOSITION + ": " + HttpPostBodyUtil.FORM_DATA + "; " internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
+ HttpPostBodyUtil.NAME + "=\"" + attribute.getName() + "\"\r\n"); + HttpHeaderValues.NAME + "=\"" + attribute.getName() + "\"\r\n");
Charset localcharset = attribute.getCharset(); Charset localcharset = attribute.getCharset();
if (localcharset != null) { if (localcharset != null) {
// Content-Type: text/plain; charset=charset // Content-Type: text/plain; charset=charset
internal.addValue(HttpHeaders.Names.CONTENT_TYPE + ": " + internal.addValue(HttpHeaderNames.CONTENT_TYPE + ": " +
HttpPostBodyUtil.DEFAULT_TEXT_CONTENT_TYPE + "; " + HttpPostBodyUtil.DEFAULT_TEXT_CONTENT_TYPE + "; " +
HttpHeaders.Values.CHARSET + '=' HttpHeaderValues.CHARSET + '='
+ localcharset + "\r\n"); + localcharset + "\r\n");
} }
// CRLF between body header and data // CRLF between body header and data
@ -587,20 +587,20 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
replacement.append(multipartDataBoundary); replacement.append(multipartDataBoundary);
replacement.append("\r\n"); replacement.append("\r\n");
replacement.append(HttpPostBodyUtil.CONTENT_DISPOSITION); replacement.append(HttpHeaderNames.CONTENT_DISPOSITION);
replacement.append(": "); replacement.append(": ");
replacement.append(HttpPostBodyUtil.FORM_DATA); replacement.append(HttpHeaderValues.FORM_DATA);
replacement.append("; "); replacement.append("; ");
replacement.append(HttpPostBodyUtil.NAME); replacement.append(HttpHeaderValues.NAME);
replacement.append("=\""); replacement.append("=\"");
replacement.append(fileUpload.getName()); replacement.append(fileUpload.getName());
replacement.append("\"\r\n"); replacement.append("\"\r\n");
replacement.append(HttpHeaders.Names.CONTENT_TYPE); replacement.append(HttpHeaderNames.CONTENT_TYPE);
replacement.append(": "); replacement.append(": ");
replacement.append(HttpPostBodyUtil.MULTIPART_MIXED); replacement.append(HttpHeaderValues.MULTIPART_MIXED);
replacement.append("; "); replacement.append("; ");
replacement.append(HttpHeaders.Values.BOUNDARY); replacement.append(HttpHeaderValues.BOUNDARY);
replacement.append('='); replacement.append('=');
replacement.append(multipartMixedBoundary); replacement.append(multipartMixedBoundary);
replacement.append("\r\n\r\n"); replacement.append("\r\n\r\n");
@ -609,11 +609,11 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
replacement.append(multipartMixedBoundary); replacement.append(multipartMixedBoundary);
replacement.append("\r\n"); replacement.append("\r\n");
replacement.append(HttpPostBodyUtil.CONTENT_DISPOSITION); replacement.append(HttpHeaderNames.CONTENT_DISPOSITION);
replacement.append(": "); replacement.append(": ");
replacement.append(HttpPostBodyUtil.ATTACHMENT); replacement.append(HttpHeaderValues.ATTACHMENT);
replacement.append("; "); replacement.append("; ");
replacement.append(HttpPostBodyUtil.FILENAME); replacement.append(HttpHeaderValues.FILENAME);
replacement.append("=\""); replacement.append("=\"");
replacement.append(fileUpload.getFilename()); replacement.append(fileUpload.getFilename());
replacement.append("\"\r\n"); replacement.append("\"\r\n");
@ -645,27 +645,27 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
// Data to multipart list // Data to multipart list
internal.addValue("--" + multipartMixedBoundary + "\r\n"); internal.addValue("--" + multipartMixedBoundary + "\r\n");
// Content-Disposition: attachment; filename="file1.txt" // Content-Disposition: attachment; filename="file1.txt"
internal.addValue(HttpPostBodyUtil.CONTENT_DISPOSITION + ": " + HttpPostBodyUtil.ATTACHMENT + "; " internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.ATTACHMENT + "; "
+ HttpPostBodyUtil.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n"); + HttpHeaderValues.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n");
} else { } else {
internal.addValue("--" + multipartDataBoundary + "\r\n"); internal.addValue("--" + multipartDataBoundary + "\r\n");
// Content-Disposition: form-data; name="files"; // Content-Disposition: form-data; name="files";
// filename="file1.txt" // filename="file1.txt"
internal.addValue(HttpPostBodyUtil.CONTENT_DISPOSITION + ": " + HttpPostBodyUtil.FORM_DATA + "; " internal.addValue(HttpHeaderNames.CONTENT_DISPOSITION + ": " + HttpHeaderValues.FORM_DATA + "; "
+ HttpPostBodyUtil.NAME + "=\"" + fileUpload.getName() + "\"; " + HttpHeaderValues.NAME + "=\"" + fileUpload.getName() + "\"; "
+ HttpPostBodyUtil.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n"); + HttpHeaderValues.FILENAME + "=\"" + fileUpload.getFilename() + "\"\r\n");
} }
// Content-Type: image/gif // Content-Type: image/gif
// Content-Type: text/plain; charset=ISO-8859-1 // Content-Type: text/plain; charset=ISO-8859-1
// Content-Transfer-Encoding: binary // Content-Transfer-Encoding: binary
internal.addValue(HttpHeaders.Names.CONTENT_TYPE + ": " + fileUpload.getContentType()); internal.addValue(HttpHeaderNames.CONTENT_TYPE + ": " + fileUpload.getContentType());
String contentTransferEncoding = fileUpload.getContentTransferEncoding(); String contentTransferEncoding = fileUpload.getContentTransferEncoding();
if (contentTransferEncoding != null if (contentTransferEncoding != null
&& contentTransferEncoding.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) { && contentTransferEncoding.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) {
internal.addValue("\r\n" + HttpHeaders.Names.CONTENT_TRANSFER_ENCODING + ": " internal.addValue("\r\n" + HttpHeaderNames.CONTENT_TRANSFER_ENCODING + ": "
+ HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value() + "\r\n\r\n"); + HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value() + "\r\n\r\n");
} else if (fileUpload.getCharset() != null) { } else if (fileUpload.getCharset() != null) {
internal.addValue("; " + HttpHeaders.Values.CHARSET + '=' + fileUpload.getCharset() + "\r\n\r\n"); internal.addValue("; " + HttpHeaderValues.CHARSET + '=' + fileUpload.getCharset() + "\r\n\r\n");
} else { } else {
internal.addValue("\r\n\r\n"); internal.addValue("\r\n\r\n");
} }
@ -711,28 +711,28 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
} }
HttpHeaders headers = request.headers(); HttpHeaders headers = request.headers();
List<String> contentTypes = headers.getAllAndConvert(HttpHeaders.Names.CONTENT_TYPE); List<String> contentTypes = headers.getAllAndConvert(HttpHeaderNames.CONTENT_TYPE);
List<CharSequence> transferEncoding = headers.getAll(HttpHeaders.Names.TRANSFER_ENCODING); List<CharSequence> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING);
if (contentTypes != null) { if (contentTypes != null) {
headers.remove(HttpHeaders.Names.CONTENT_TYPE); headers.remove(HttpHeaderNames.CONTENT_TYPE);
for (String contentType : contentTypes) { for (String contentType : contentTypes) {
// "multipart/form-data; boundary=--89421926422648" // "multipart/form-data; boundary=--89421926422648"
String lowercased = contentType.toLowerCase(); String lowercased = contentType.toLowerCase();
if (lowercased.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA.toString()) || if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) ||
lowercased.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.toString())) { lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
// ignore // ignore
} else { } else {
headers.add(HttpHeaders.Names.CONTENT_TYPE, contentType); headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
} }
} }
} }
if (isMultipart) { if (isMultipart) {
String value = HttpHeaders.Values.MULTIPART_FORM_DATA + "; " + HttpHeaders.Values.BOUNDARY + '=' String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '='
+ multipartDataBoundary; + multipartDataBoundary;
headers.add(HttpHeaders.Names.CONTENT_TYPE, value); headers.add(HttpHeaderNames.CONTENT_TYPE, value);
} else { } else {
// Not multipart // Not multipart
headers.add(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
} }
// Now consider size for chunk or not // Now consider size for chunk or not
long realSize = globalBodySize; long realSize = globalBodySize;
@ -742,16 +742,16 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
realSize -= 1; // last '&' removed realSize -= 1; // last '&' removed
iterator = multipartHttpDatas.listIterator(); iterator = multipartHttpDatas.listIterator();
} }
headers.set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(realSize)); headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize));
if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) { if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
isChunked = true; isChunked = true;
if (transferEncoding != null) { if (transferEncoding != null) {
headers.remove(HttpHeaders.Names.TRANSFER_ENCODING); headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
for (CharSequence v : transferEncoding) { for (CharSequence v : transferEncoding) {
if (AsciiString.equalsIgnoreCase(v, HttpHeaders.Values.CHUNKED)) { if (HttpHeaderValues.CHUNKED.equalsIgnoreCase(v)) {
// ignore // ignore
} else { } else {
headers.add(HttpHeaders.Names.TRANSFER_ENCODING, v); headers.add(HttpHeaderNames.TRANSFER_ENCODING, v);
} }
} }
} }
@ -1223,7 +1223,7 @@ public class HttpPostRequestEncoder implements ChunkedInput<HttpContent> {
DefaultFullHttpRequest copy = new DefaultFullHttpRequest( DefaultFullHttpRequest copy = new DefaultFullHttpRequest(
protocolVersion(), method(), uri(), protocolVersion(), method(), uri(),
copyContent ? content().copy() : copyContent ? content().copy() :
newContent == null ? Unpooled.buffer(0) : newContent); newContent == null ? buffer(0) : newContent);
copy.headers().set(headers()); copy.headers().set(headers());
copy.trailingHeaders().set(trailingHeaders()); copy.trailingHeaders().set(trailingHeaders());
return copy; return copy;

View File

@ -17,7 +17,8 @@ package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelException; import io.netty.channel.ChannelException;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -119,12 +120,12 @@ public class MemoryFileUpload extends AbstractMemoryHttpData implements FileUplo
@Override @Override
public String toString() { public String toString() {
return HttpPostBodyUtil.CONTENT_DISPOSITION + ": " + return HttpHeaderNames.CONTENT_DISPOSITION + ": " +
HttpPostBodyUtil.FORM_DATA + "; " + HttpPostBodyUtil.NAME + "=\"" + getName() + HttpHeaderValues.FORM_DATA + "; " + HttpHeaderValues.NAME + "=\"" + getName() +
"\"; " + HttpPostBodyUtil.FILENAME + "=\"" + filename + "\"\r\n" + "\"; " + HttpHeaderValues.FILENAME + "=\"" + filename + "\"\r\n" +
HttpHeaders.Names.CONTENT_TYPE + ": " + contentType + HttpHeaderNames.CONTENT_TYPE + ": " + contentType +
(getCharset() != null? "; " + HttpHeaders.Values.CHARSET + '=' + getCharset() + "\r\n" : "\r\n") + (getCharset() != null? "; " + HttpHeaderValues.CHARSET + '=' + getCharset() + "\r\n" : "\r\n") +
HttpHeaders.Names.CONTENT_LENGTH + ": " + length() + "\r\n" + HttpHeaderNames.CONTENT_LENGTH + ": " + length() + "\r\n" +
"Completed: " + isCompleted() + "Completed: " + isCompleted() +
"\r\nIsInMemory: " + isInMemory(); "\r\nIsInMemory: " + isInMemory();
} }

View File

@ -25,6 +25,7 @@ import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.HttpResponseDecoder;
@ -203,7 +204,7 @@ public abstract class WebSocketClientHandshaker {
// Verify the subprotocol that we received from the server. // Verify the subprotocol that we received from the server.
// This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol // This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol
String receivedProtocol = response.headers().getAndConvert(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL); String receivedProtocol = response.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null; receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null;
String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : ""; String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : "";
boolean protocolValid = false; boolean protocolValid = false;

View File

@ -21,9 +21,9 @@ import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -43,6 +43,8 @@ import java.nio.ByteBuffer;
*/ */
public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker { public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
private static final AsciiString WEBSOCKET = new AsciiString("WebSocket");
private ByteBuf expectedChallengeResponseBytes; private ByteBuf expectedChallengeResponseBytes;
/** /**
@ -136,9 +138,9 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
// Format request // Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers(); HttpHeaders headers = request.headers();
headers.add(Names.UPGRADE, Values.WEBSOCKET) headers.add(HttpHeaderNames.UPGRADE, WEBSOCKET)
.add(Names.CONNECTION, Values.UPGRADE) .add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.add(Names.HOST, wsURL.getHost()); .add(HttpHeaderNames.HOST, wsURL.getHost());
int wsPort = wsURL.getPort(); int wsPort = wsURL.getPort();
String originValue = "http://" + wsURL.getHost(); String originValue = "http://" + wsURL.getHost();
@ -148,13 +150,13 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
originValue = originValue + ':' + wsPort; originValue = originValue + ':' + wsPort;
} }
headers.add(Names.ORIGIN, originValue) headers.add(HttpHeaderNames.ORIGIN, originValue)
.add(Names.SEC_WEBSOCKET_KEY1, key1) .add(HttpHeaderNames.SEC_WEBSOCKET_KEY1, key1)
.add(Names.SEC_WEBSOCKET_KEY2, key2); .add(HttpHeaderNames.SEC_WEBSOCKET_KEY2, key2);
String expectedSubprotocol = expectedSubprotocol(); String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.add(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); headers.add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
} }
if (customHeaders != null) { if (customHeaders != null) {
@ -163,7 +165,7 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
// Set Content-Length to workaround some known defect. // Set Content-Length to workaround some known defect.
// See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html // See also: http://www.ietf.org/mail-archive/web/hybi/current/msg02149.html
headers.setInt(Names.CONTENT_LENGTH, key3.length); headers.setInt(HttpHeaderNames.CONTENT_LENGTH, key3.length);
request.content().writeBytes(key3); request.content().writeBytes(key3);
return request; return request;
} }
@ -198,14 +200,14 @@ public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
HttpHeaders headers = response.headers(); HttpHeaders headers = response.headers();
CharSequence upgrade = headers.get(Names.UPGRADE); CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
if (!AsciiString.equalsIgnoreCase(Values.WEBSOCKET, upgrade)) { if (!WEBSOCKET.equalsIgnoreCase(upgrade)) {
throw new WebSocketHandshakeException("Invalid handshake response upgrade: " throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
+ upgrade); + upgrade);
} }
CharSequence connection = headers.get(Names.CONNECTION); CharSequence connection = headers.get(HttpHeaderNames.CONNECTION);
if (!AsciiString.equalsIgnoreCase(Values.UPGRADE, connection)) { if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(connection)) {
throw new WebSocketHandshakeException("Invalid handshake response connection: " throw new WebSocketHandshakeException("Invalid handshake response connection: "
+ connection); + connection);
} }

View File

@ -15,13 +15,12 @@
*/ */
package io.netty.handler.codec.http.websocketx; package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -41,7 +40,6 @@ import java.net.URI;
public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker { public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker07.class); private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker07.class);
private static final CharSequence WEBSOCKET = new AsciiString(Values.WEBSOCKET.toString().toLowerCase());
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private String expectedChallengeResponseString; private String expectedChallengeResponseString;
@ -154,10 +152,10 @@ public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers(); HttpHeaders headers = request.headers();
headers.add(Names.UPGRADE, WEBSOCKET) headers.add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.add(Names.CONNECTION, Values.UPGRADE) .add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.add(Names.SEC_WEBSOCKET_KEY, key) .add(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.add(Names.HOST, wsURL.getHost()); .add(HttpHeaderNames.HOST, wsURL.getHost());
int wsPort = wsURL.getPort(); int wsPort = wsURL.getPort();
String originValue = "http://" + wsURL.getHost(); String originValue = "http://" + wsURL.getHost();
@ -166,14 +164,14 @@ public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
// See http://tools.ietf.org/html/rfc6454#section-6.2 // See http://tools.ietf.org/html/rfc6454#section-6.2
originValue = originValue + ':' + wsPort; originValue = originValue + ':' + wsPort;
} }
headers.add(Names.SEC_WEBSOCKET_ORIGIN, originValue); headers.add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, originValue);
String expectedSubprotocol = expectedSubprotocol(); String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.add(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); headers.add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
} }
headers.add(Names.SEC_WEBSOCKET_VERSION, "7"); headers.add(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "7");
if (customHeaders != null) { if (customHeaders != null) {
headers.add(customHeaders); headers.add(customHeaders);
@ -207,17 +205,17 @@ public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status()); throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
} }
CharSequence upgrade = headers.get(Names.UPGRADE); CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
if (!AsciiString.equalsIgnoreCase(Values.WEBSOCKET, upgrade)) { if (!HttpHeaderValues.WEBSOCKET.equalsIgnoreCase(upgrade)) {
throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade); throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
} }
CharSequence connection = headers.get(Names.CONNECTION); CharSequence connection = headers.get(HttpHeaderNames.CONNECTION);
if (!AsciiString.equalsIgnoreCase(Values.UPGRADE, connection)) { if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(connection)) {
throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection); throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
} }
CharSequence accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT); CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
if (accept == null || !accept.equals(expectedChallengeResponseString)) { if (accept == null || !accept.equals(expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format( throw new WebSocketHandshakeException(String.format(
"Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString)); "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));

View File

@ -15,13 +15,12 @@
*/ */
package io.netty.handler.codec.http.websocketx; package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -41,7 +40,6 @@ import java.net.URI;
public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker { public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker08.class); private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker08.class);
private static final CharSequence WEBSOCKET = new AsciiString(Values.WEBSOCKET.toString().toLowerCase());
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
@ -155,10 +153,10 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers(); HttpHeaders headers = request.headers();
headers.add(Names.UPGRADE, WEBSOCKET) headers.add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.add(Names.CONNECTION, Values.UPGRADE) .add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.add(Names.SEC_WEBSOCKET_KEY, key) .add(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.add(Names.HOST, wsURL.getHost()); .add(HttpHeaderNames.HOST, wsURL.getHost());
int wsPort = wsURL.getPort(); int wsPort = wsURL.getPort();
String originValue = "http://" + wsURL.getHost(); String originValue = "http://" + wsURL.getHost();
@ -167,14 +165,14 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
// See http://tools.ietf.org/html/rfc6454#section-6.2 // See http://tools.ietf.org/html/rfc6454#section-6.2
originValue = originValue + ':' + wsPort; originValue = originValue + ':' + wsPort;
} }
headers.add(Names.SEC_WEBSOCKET_ORIGIN, originValue); headers.add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, originValue);
String expectedSubprotocol = expectedSubprotocol(); String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.add(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); headers.add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
} }
headers.add(Names.SEC_WEBSOCKET_VERSION, "8"); headers.add(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
if (customHeaders != null) { if (customHeaders != null) {
headers.add(customHeaders); headers.add(customHeaders);
@ -208,17 +206,17 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status()); throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
} }
CharSequence upgrade = headers.get(Names.UPGRADE); CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
if (!AsciiString.equalsIgnoreCase(Values.WEBSOCKET, upgrade)) { if (!HttpHeaderValues.WEBSOCKET.equalsIgnoreCase(upgrade)) {
throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade); throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
} }
CharSequence connection = headers.get(Names.CONNECTION); CharSequence connection = headers.get(HttpHeaderNames.CONNECTION);
if (!AsciiString.equalsIgnoreCase(Values.UPGRADE, connection)) { if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(connection)) {
throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection); throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
} }
CharSequence accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT); CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
if (accept == null || !accept.equals(expectedChallengeResponseString)) { if (accept == null || !accept.equals(expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format( throw new WebSocketHandshakeException(String.format(
"Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString)); "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));

View File

@ -15,13 +15,12 @@
*/ */
package io.netty.handler.codec.http.websocketx; package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -41,7 +40,6 @@ import java.net.URI;
public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker { public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker13.class); private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker13.class);
private static final CharSequence WEBSOCKET = new AsciiString(Values.WEBSOCKET.toString().toLowerCase());
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
@ -166,10 +164,10 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers(); HttpHeaders headers = request.headers();
headers.add(Names.UPGRADE, WEBSOCKET) headers.add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.add(Names.CONNECTION, Values.UPGRADE) .add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.add(Names.SEC_WEBSOCKET_KEY, key) .add(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.add(Names.HOST, wsURL.getHost() + ':' + wsPort); .add(HttpHeaderNames.HOST, wsURL.getHost() + ':' + wsPort);
String originValue = "http://" + wsURL.getHost(); String originValue = "http://" + wsURL.getHost();
if (wsPort != 80 && wsPort != 443) { if (wsPort != 80 && wsPort != 443) {
@ -177,14 +175,14 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
// See http://tools.ietf.org/html/rfc6454#section-6.2 // See http://tools.ietf.org/html/rfc6454#section-6.2
originValue = originValue + ':' + wsPort; originValue = originValue + ':' + wsPort;
} }
headers.add(Names.SEC_WEBSOCKET_ORIGIN, originValue); headers.add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, originValue);
String expectedSubprotocol = expectedSubprotocol(); String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) { if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.add(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol); headers.add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
} }
headers.add(Names.SEC_WEBSOCKET_VERSION, "13"); headers.add(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
if (customHeaders != null) { if (customHeaders != null) {
headers.add(customHeaders); headers.add(customHeaders);
@ -218,17 +216,17 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status()); throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
} }
CharSequence upgrade = headers.get(Names.UPGRADE); CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
if (!AsciiString.equalsIgnoreCase(Values.WEBSOCKET, upgrade)) { if (!HttpHeaderValues.WEBSOCKET.equalsIgnoreCase(upgrade)) {
throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade); throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
} }
CharSequence connection = headers.get(Names.CONNECTION); CharSequence connection = headers.get(HttpHeaderNames.CONNECTION);
if (!AsciiString.equalsIgnoreCase(Values.UPGRADE, connection)) { if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(connection)) {
throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection); throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
} }
CharSequence accept = headers.get(Names.SEC_WEBSOCKET_ACCEPT); CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
if (accept == null || !accept.equals(expectedChallengeResponseString)) { if (accept == null || !accept.equals(expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format( throw new WebSocketHandshakeException(String.format(
"Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString)); "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));

View File

@ -24,15 +24,13 @@ import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpHeaders.Values.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
/** /**
@ -47,6 +45,8 @@ import static io.netty.handler.codec.http.HttpVersion.*;
*/ */
public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker { public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
private static final AsciiString WEBSOCKET = new AsciiString("WebSocket");
private static final Pattern BEGINNING_DIGIT = Pattern.compile("[^0-9]"); private static final Pattern BEGINNING_DIGIT = Pattern.compile("[^0-9]");
private static final Pattern BEGINNING_SPACE = Pattern.compile("[^ ]"); private static final Pattern BEGINNING_SPACE = Pattern.compile("[^ ]");
@ -110,13 +110,14 @@ public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) { protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
// Serve the WebSocket handshake request. // Serve the WebSocket handshake request.
if (!AsciiString.equalsIgnoreCase(Values.UPGRADE, req.headers().get(CONNECTION)) if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(req.headers().get(HttpHeaderNames.CONNECTION))
|| !AsciiString.equalsIgnoreCase(WEBSOCKET, req.headers().get(Names.UPGRADE))) { || !WEBSOCKET.equalsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) {
throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade"); throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade");
} }
// Hixie 75 does not contain these headers while Hixie 76 does // Hixie 75 does not contain these headers while Hixie 76 does
boolean isHixie76 = req.headers().contains(SEC_WEBSOCKET_KEY1) && req.headers().contains(SEC_WEBSOCKET_KEY2); boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) &&
req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
// Create the WebSocket handshake response. // Create the WebSocket handshake response.
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101, FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101,
@ -125,15 +126,15 @@ public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
res.headers().add(headers); res.headers().add(headers);
} }
res.headers().add(Names.UPGRADE, WEBSOCKET); res.headers().add(HttpHeaderNames.UPGRADE, WEBSOCKET);
res.headers().add(CONNECTION, Values.UPGRADE); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
// Fill in the headers and contents depending on handshake getMethod. // Fill in the headers and contents depending on handshake getMethod.
if (isHixie76) { if (isHixie76) {
// New handshake getMethod with a challenge: // New handshake getMethod with a challenge:
res.headers().add(SEC_WEBSOCKET_ORIGIN, req.headers().get(ORIGIN)); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN));
res.headers().add(SEC_WEBSOCKET_LOCATION, uri()); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, uri());
String subprotocols = req.headers().getAndConvert(SEC_WEBSOCKET_PROTOCOL); String subprotocols = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
if (subprotocols != null) { if (subprotocols != null) {
String selectedSubprotocol = selectSubprotocol(subprotocols); String selectedSubprotocol = selectSubprotocol(subprotocols);
if (selectedSubprotocol == null) { if (selectedSubprotocol == null) {
@ -141,13 +142,13 @@ public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
logger.debug("Requested subprotocol(s) not supported: {}", subprotocols); logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
} }
} else { } else {
res.headers().add(SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
} }
} }
// Calculate the answer of the challenge. // Calculate the answer of the challenge.
String key1 = req.headers().getAndConvert(SEC_WEBSOCKET_KEY1); String key1 = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_KEY1);
String key2 = req.headers().getAndConvert(SEC_WEBSOCKET_KEY2); String key2 = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) / int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) /
BEGINNING_SPACE.matcher(key1).replaceAll("").length()); BEGINNING_SPACE.matcher(key1).replaceAll("").length());
int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) / int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) /
@ -160,11 +161,11 @@ public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
res.content().writeBytes(WebSocketUtil.md5(input.array())); res.content().writeBytes(WebSocketUtil.md5(input.array()));
} else { } else {
// Old Hixie 75 handshake getMethod with no challenge: // Old Hixie 75 handshake getMethod with no challenge:
res.headers().add(WEBSOCKET_ORIGIN, req.headers().get(ORIGIN)); res.headers().add(HttpHeaderNames.WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN));
res.headers().add(WEBSOCKET_LOCATION, uri()); res.headers().add(HttpHeaderNames.WEBSOCKET_LOCATION, uri());
String protocol = req.headers().getAndConvert(WEBSOCKET_PROTOCOL); String protocol = req.headers().getAndConvert(HttpHeaderNames.WEBSOCKET_PROTOCOL);
if (protocol != null) { if (protocol != null) {
res.headers().add(WEBSOCKET_PROTOCOL, selectSubprotocol(protocol)); res.headers().add(HttpHeaderNames.WEBSOCKET_PROTOCOL, selectSubprotocol(protocol));
} }
} }
return res; return res;

View File

@ -15,13 +15,12 @@
*/ */
package io.netty.handler.codec.http.websocketx; package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
@ -36,8 +35,6 @@ import static io.netty.handler.codec.http.HttpVersion.*;
*/ */
public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker { public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker {
private static final CharSequence WEBSOCKET = new AsciiString(Values.WEBSOCKET.toString().toLowerCase());
public static final String WEBSOCKET_07_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final String WEBSOCKET_07_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private final boolean allowExtensions; private final boolean allowExtensions;
@ -130,7 +127,7 @@ public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker {
res.headers().add(headers); res.headers().add(headers);
} }
CharSequence key = req.headers().get(Names.SEC_WEBSOCKET_KEY); CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
if (key == null) { if (key == null) {
throw new WebSocketHandshakeException("not a WebSocket request: missing key"); throw new WebSocketHandshakeException("not a WebSocket request: missing key");
} }
@ -142,10 +139,10 @@ public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker {
logger.debug("WebSocket version 07 server handshake key: {}, response: {}.", key, accept); logger.debug("WebSocket version 07 server handshake key: {}, response: {}.", key, accept);
} }
res.headers().add(Names.UPGRADE, WEBSOCKET); res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
res.headers().add(Names.CONNECTION, Names.UPGRADE); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
res.headers().add(Names.SEC_WEBSOCKET_ACCEPT, accept); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
String subprotocols = req.headers().getAndConvert(Names.SEC_WEBSOCKET_PROTOCOL); String subprotocols = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
if (subprotocols != null) { if (subprotocols != null) {
String selectedSubprotocol = selectSubprotocol(subprotocols); String selectedSubprotocol = selectSubprotocol(subprotocols);
if (selectedSubprotocol == null) { if (selectedSubprotocol == null) {
@ -153,7 +150,7 @@ public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker {
logger.debug("Requested subprotocol(s) not supported: {}", subprotocols); logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
} }
} else { } else {
res.headers().add(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
} }
} }
return res; return res;

View File

@ -15,13 +15,12 @@
*/ */
package io.netty.handler.codec.http.websocketx; package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
@ -36,8 +35,6 @@ import static io.netty.handler.codec.http.HttpVersion.*;
*/ */
public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker { public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
private static final CharSequence WEBSOCKET = new AsciiString(Values.WEBSOCKET.toString().toLowerCase());
public static final String WEBSOCKET_08_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final String WEBSOCKET_08_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private final boolean allowExtensions; private final boolean allowExtensions;
@ -129,7 +126,7 @@ public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
res.headers().add(headers); res.headers().add(headers);
} }
CharSequence key = req.headers().get(Names.SEC_WEBSOCKET_KEY); CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
if (key == null) { if (key == null) {
throw new WebSocketHandshakeException("not a WebSocket request: missing key"); throw new WebSocketHandshakeException("not a WebSocket request: missing key");
} }
@ -141,10 +138,10 @@ public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
logger.debug("WebSocket version 08 server handshake key: {}, response: {}", key, accept); logger.debug("WebSocket version 08 server handshake key: {}, response: {}", key, accept);
} }
res.headers().add(Names.UPGRADE, WEBSOCKET); res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
res.headers().add(Names.CONNECTION, Names.UPGRADE); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
res.headers().add(Names.SEC_WEBSOCKET_ACCEPT, accept); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
String subprotocols = req.headers().getAndConvert(Names.SEC_WEBSOCKET_PROTOCOL); String subprotocols = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
if (subprotocols != null) { if (subprotocols != null) {
String selectedSubprotocol = selectSubprotocol(subprotocols); String selectedSubprotocol = selectSubprotocol(subprotocols);
if (selectedSubprotocol == null) { if (selectedSubprotocol == null) {
@ -152,7 +149,7 @@ public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
logger.debug("Requested subprotocol(s) not supported: {}", subprotocols); logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
} }
} else { } else {
res.headers().add(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
} }
} }
return res; return res;

View File

@ -15,13 +15,12 @@
*/ */
package io.netty.handler.codec.http.websocketx; package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
@ -35,8 +34,6 @@ import static io.netty.handler.codec.http.HttpVersion.*;
*/ */
public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker { public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
private static final CharSequence WEBSOCKET = new AsciiString(Values.WEBSOCKET.toString().toLowerCase());
public static final String WEBSOCKET_13_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public static final String WEBSOCKET_13_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private final boolean allowExtensions; private final boolean allowExtensions;
@ -127,7 +124,7 @@ public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
res.headers().add(headers); res.headers().add(headers);
} }
CharSequence key = req.headers().get(Names.SEC_WEBSOCKET_KEY); CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
if (key == null) { if (key == null) {
throw new WebSocketHandshakeException("not a WebSocket request: missing key"); throw new WebSocketHandshakeException("not a WebSocket request: missing key");
} }
@ -139,10 +136,10 @@ public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept); logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept);
} }
res.headers().add(Names.UPGRADE, WEBSOCKET); res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
res.headers().add(Names.CONNECTION, Names.UPGRADE); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
res.headers().add(Names.SEC_WEBSOCKET_ACCEPT, accept); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
String subprotocols = req.headers().getAndConvert(Names.SEC_WEBSOCKET_PROTOCOL); String subprotocols = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
if (subprotocols != null) { if (subprotocols != null) {
String selectedSubprotocol = selectSubprotocol(subprotocols); String selectedSubprotocol = selectSubprotocol(subprotocols);
if (selectedSubprotocol == null) { if (selectedSubprotocol == null) {
@ -150,7 +147,7 @@ public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
logger.debug("Requested subprotocol(s) not supported: {}", subprotocols); logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
} }
} else { } else {
res.headers().add(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
} }
} }
return res; return res;

View File

@ -19,7 +19,7 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
@ -112,7 +112,7 @@ public class WebSocketServerHandshakerFactory {
*/ */
public WebSocketServerHandshaker newHandshaker(HttpRequest req) { public WebSocketServerHandshaker newHandshaker(HttpRequest req) {
CharSequence version = req.headers().get(Names.SEC_WEBSOCKET_VERSION); CharSequence version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
if (version != null) { if (version != null) {
if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) { if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) {
// Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification). // Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification).
@ -149,7 +149,7 @@ public class WebSocketServerHandshakerFactory {
HttpResponse res = new DefaultHttpResponse( HttpResponse res = new DefaultHttpResponse(
HttpVersion.HTTP_1_1, HttpVersion.HTTP_1_1,
HttpResponseStatus.UPGRADE_REQUIRED); HttpResponseStatus.UPGRADE_REQUIRED);
res.headers().set(Names.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue()); res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue());
return channel.write(res, promise); return channel.write(res, promise);
} }
} }

View File

@ -22,8 +22,8 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandler;
@ -102,7 +102,7 @@ class WebSocketServerProtocolHandshakeHandler extends ChannelHandlerAdapter {
// SSL in use so use Secure WebSockets // SSL in use so use Secure WebSockets
protocol = "wss"; protocol = "wss";
} }
return protocol + "://" + req.headers().get(HttpHeaders.Names.HOST) + path; return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
} }
} }

View File

@ -19,7 +19,7 @@ import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.CodecException; import io.netty.handler.codec.CodecException;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
@ -63,7 +63,7 @@ public class WebSocketClientExtensionHandler extends ChannelHandlerAdapter {
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpRequest && WebSocketExtensionUtil.isWebsocketUpgrade((HttpRequest) msg)) { if (msg instanceof HttpRequest && WebSocketExtensionUtil.isWebsocketUpgrade((HttpRequest) msg)) {
HttpRequest request = (HttpRequest) msg; HttpRequest request = (HttpRequest) msg;
String headerValue = request.headers().getAndConvert(HttpHeaders.Names.SEC_WEBSOCKET_EXTENSIONS); String headerValue = request.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
for (WebSocketClientExtensionHandshaker extentionHandshaker : extensionHandshakers) { for (WebSocketClientExtensionHandshaker extentionHandshaker : extensionHandshakers) {
WebSocketExtensionData extensionData = extentionHandshaker.newRequestData(); WebSocketExtensionData extensionData = extentionHandshaker.newRequestData();
@ -71,7 +71,7 @@ public class WebSocketClientExtensionHandler extends ChannelHandlerAdapter {
extensionData.name(), extensionData.parameters()); extensionData.name(), extensionData.parameters());
} }
request.headers().set(HttpHeaders.Names.SEC_WEBSOCKET_EXTENSIONS, headerValue); request.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, headerValue);
} }
super.write(ctx, msg, promise); super.write(ctx, msg, promise);
@ -84,7 +84,7 @@ public class WebSocketClientExtensionHandler extends ChannelHandlerAdapter {
HttpResponse response = (HttpResponse) msg; HttpResponse response = (HttpResponse) msg;
if (WebSocketExtensionUtil.isWebsocketUpgrade(response)) { if (WebSocketExtensionUtil.isWebsocketUpgrade(response)) {
String extensionsHeader = response.headers().getAndConvert(HttpHeaders.Names.SEC_WEBSOCKET_EXTENSIONS); String extensionsHeader = response.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
if (extensionsHeader != null) { if (extensionsHeader != null) {
List<WebSocketExtensionData> extensions = List<WebSocketExtensionData> extensions =

View File

@ -15,7 +15,8 @@
*/ */
package io.netty.handler.codec.http.websocketx.extensions; package io.netty.handler.codec.http.websocketx.extensions;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.HttpMessage;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
@ -40,8 +41,8 @@ public final class WebSocketExtensionUtil {
if (httpMessage == null) { if (httpMessage == null) {
throw new NullPointerException("httpMessage"); throw new NullPointerException("httpMessage");
} }
return httpMessage.headers().contains(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE, true) && return httpMessage.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true) &&
httpMessage.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true); httpMessage.headers().contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true);
} }
public static List<WebSocketExtensionData> extractExtensions(String extensionHeader) { public static List<WebSocketExtensionData> extractExtensions(String extensionHeader) {
@ -62,7 +63,7 @@ public final class WebSocketExtensionUtil {
} }
} }
} else { } else {
parameters = Collections.<String, String>emptyMap(); parameters = Collections.emptyMap();
} }
extensions.add(new WebSocketExtensionData(name, parameters)); extensions.add(new WebSocketExtensionData(name, parameters));
} }

View File

@ -20,7 +20,7 @@ import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
@ -69,7 +69,7 @@ public class WebSocketServerExtensionHandler extends ChannelHandlerAdapter {
HttpRequest request = (HttpRequest) msg; HttpRequest request = (HttpRequest) msg;
if (WebSocketExtensionUtil.isWebsocketUpgrade(request)) { if (WebSocketExtensionUtil.isWebsocketUpgrade(request)) {
String extensionsHeader = request.headers().getAndConvert(HttpHeaders.Names.SEC_WEBSOCKET_EXTENSIONS); String extensionsHeader = request.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
if (extensionsHeader != null) { if (extensionsHeader != null) {
List<WebSocketExtensionData> extensions = List<WebSocketExtensionData> extensions =
@ -107,7 +107,7 @@ public class WebSocketServerExtensionHandler extends ChannelHandlerAdapter {
if (msg instanceof HttpResponse && if (msg instanceof HttpResponse &&
WebSocketExtensionUtil.isWebsocketUpgrade((HttpResponse) msg) && validExtensions != null) { WebSocketExtensionUtil.isWebsocketUpgrade((HttpResponse) msg) && validExtensions != null) {
HttpResponse response = (HttpResponse) msg; HttpResponse response = (HttpResponse) msg;
String headerValue = response.headers().getAndConvert(HttpHeaders.Names.SEC_WEBSOCKET_EXTENSIONS); String headerValue = response.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
for (WebSocketServerExtension extension : validExtensions) { for (WebSocketServerExtension extension : validExtensions) {
WebSocketExtensionData extensionData = extension.newReponseData(); WebSocketExtensionData extensionData = extension.newReponseData();
@ -132,7 +132,7 @@ public class WebSocketServerExtensionHandler extends ChannelHandlerAdapter {
}); });
if (headerValue != null) { if (headerValue != null) {
response.headers().set(HttpHeaders.Names.SEC_WEBSOCKET_EXTENSIONS, headerValue); response.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, headerValue);
} }
} }

View File

@ -0,0 +1,207 @@
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.rtsp;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.HttpHeaderNames;
/**
* Standard RTSP header names.
* <p>
* These are all defined as lowercase to support HTTP/2 requirements while also not
* violating RTSP/1.x requirements. New header names should always be lowercase.
*/
public final class RtspHeaderNames {
/**
* {@code "accept"}
*/
public static final AsciiString ACCEPT = HttpHeaderNames.ACCEPT;
/**
* {@code "accept-encoding"}
*/
public static final AsciiString ACCEPT_ENCODING = HttpHeaderNames.ACCEPT_ENCODING;
/**
* {@code "accept-lanugage"}
*/
public static final AsciiString ACCEPT_LANGUAGE = HttpHeaderNames.ACCEPT_LANGUAGE;
/**
* {@code "allow"}
*/
public static final AsciiString ALLOW = new AsciiString("allow");
/**
* {@code "authorization"}
*/
public static final AsciiString AUTHORIZATION = HttpHeaderNames.AUTHORIZATION;
/**
* {@code "bandwidth"}
*/
public static final AsciiString BANDWIDTH = new AsciiString("bandwidth");
/**
* {@code "blocksize"}
*/
public static final AsciiString BLOCKSIZE = new AsciiString("blocksize");
/**
* {@code "cache-control"}
*/
public static final AsciiString CACHE_CONTROL = HttpHeaderNames.CACHE_CONTROL;
/**
* {@code "conference"}
*/
public static final AsciiString CONFERENCE = new AsciiString("conference");
/**
* {@code "connection"}
*/
public static final AsciiString CONNECTION = HttpHeaderNames.CONNECTION;
/**
* {@code "content-base"}
*/
public static final AsciiString CONTENT_BASE = HttpHeaderNames.CONTENT_BASE;
/**
* {@code "content-encoding"}
*/
public static final AsciiString CONTENT_ENCODING = HttpHeaderNames.CONTENT_ENCODING;
/**
* {@code "content-language"}
*/
public static final AsciiString CONTENT_LANGUAGE = HttpHeaderNames.CONTENT_LANGUAGE;
/**
* {@code "content-length"}
*/
public static final AsciiString CONTENT_LENGTH = HttpHeaderNames.CONTENT_LENGTH;
/**
* {@code "content-location"}
*/
public static final AsciiString CONTENT_LOCATION = HttpHeaderNames.CONTENT_LOCATION;
/**
* {@code "content-type"}
*/
public static final AsciiString CONTENT_TYPE = HttpHeaderNames.CONTENT_TYPE;
/**
* {@code "cseq"}
*/
public static final AsciiString CSEQ = new AsciiString("cseq");
/**
* {@code "cate"}
*/
public static final AsciiString DATE = HttpHeaderNames.DATE;
/**
* {@code "expires"}
*/
public static final AsciiString EXPIRES = HttpHeaderNames.EXPIRES;
/**
* {@code "from"}
*/
public static final AsciiString FROM = HttpHeaderNames.FROM;
/**
* {@code "host"}
*/
public static final AsciiString HOST = HttpHeaderNames.HOST;
/**
* {@code "if-match"}
*/
public static final AsciiString IF_MATCH = HttpHeaderNames.IF_MATCH;
/**
* {@code "if-modified-since"}
*/
public static final AsciiString IF_MODIFIED_SINCE = HttpHeaderNames.IF_MODIFIED_SINCE;
/**
* {@code "keymgmt"}
*/
public static final AsciiString KEYMGMT = new AsciiString("keymgmt");
/**
* {@code "last-modified"}
*/
public static final AsciiString LAST_MODIFIED = HttpHeaderNames.LAST_MODIFIED;
/**
* {@code "proxy-authenticate"}
*/
public static final AsciiString PROXY_AUTHENTICATE = HttpHeaderNames.PROXY_AUTHENTICATE;
/**
* {@code "proxy-require"}
*/
public static final AsciiString PROXY_REQUIRE = new AsciiString("proxy-require");
/**
* {@code "public"}
*/
public static final AsciiString PUBLIC = new AsciiString("public");
/**
* {@code "range"}
*/
public static final AsciiString RANGE = HttpHeaderNames.RANGE;
/**
* {@code "referer"}
*/
public static final AsciiString REFERER = HttpHeaderNames.REFERER;
/**
* {@code "require"}
*/
public static final AsciiString REQUIRE = new AsciiString("require");
/**
* {@code "retry-after"}
*/
public static final AsciiString RETRT_AFTER = HttpHeaderNames.RETRY_AFTER;
/**
* {@code "rtp-info"}
*/
public static final AsciiString RTP_INFO = new AsciiString("rtp-info");
/**
* {@code "scale"}
*/
public static final AsciiString SCALE = new AsciiString("scale");
/**
* {@code "session"}
*/
public static final AsciiString SESSION = new AsciiString("session");
/**
* {@code "server"}
*/
public static final AsciiString SERVER = HttpHeaderNames.SERVER;
/**
* {@code "speed"}
*/
public static final AsciiString SPEED = new AsciiString("speed");
/**
* {@code "timestamp"}
*/
public static final AsciiString TIMESTAMP = new AsciiString("timestamp");
/**
* {@code "transport"}
*/
public static final AsciiString TRANSPORT = new AsciiString("transport");
/**
* {@code "unsupported"}
*/
public static final AsciiString UNSUPPORTED = new AsciiString("unsupported");
/**
* {@code "user-agent"}
*/
public static final AsciiString USER_AGENT = HttpHeaderNames.USER_AGENT;
/**
* {@code "vary"}
*/
public static final AsciiString VARY = HttpHeaderNames.VARY;
/**
* {@code "via"}
*/
public static final AsciiString VIA = HttpHeaderNames.VIA;
/**
* {@code "www-authenticate"}
*/
public static final AsciiString WWW_AUTHENTICATE = HttpHeaderNames.WWW_AUTHENTICATE;
private RtspHeaderNames() { }
}

View File

@ -0,0 +1,196 @@
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.rtsp;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.HttpHeaderValues;
/**
* Standard RTSP header names.
*/
public final class RtspHeaderValues {
/**
* {@code "append"}
*/
public static final AsciiString APPEND = new AsciiString("append");
/**
* {@code "AVP"}
*/
public static final AsciiString AVP = new AsciiString("AVP");
/**
* {@code "bytes"}
*/
public static final AsciiString BYTES = HttpHeaderValues.BYTES;
/**
* {@code "charset"}
*/
public static final AsciiString CHARSET = HttpHeaderValues.CHARSET;
/**
* {@code "client_port"}
*/
public static final AsciiString CLIENT_PORT = new AsciiString("client_port");
/**
* {@code "clock"}
*/
public static final AsciiString CLOCK = new AsciiString("clock");
/**
* {@code "close"}
*/
public static final AsciiString CLOSE = HttpHeaderValues.CLOSE;
/**
* {@code "compress"}
*/
public static final AsciiString COMPRESS = HttpHeaderValues.COMPRESS;
/**
* {@code "100-continue"}
*/
public static final AsciiString CONTINUE = HttpHeaderValues.CONTINUE;
/**
* {@code "deflate"}
*/
public static final AsciiString DEFLATE = HttpHeaderValues.DEFLATE;
/**
* {@code "destination"}
*/
public static final AsciiString DESTINATION = new AsciiString("destination");
/**
* {@code "gzip"}
*/
public static final AsciiString GZIP = HttpHeaderValues.GZIP;
/**
* {@code "identity"}
*/
public static final AsciiString IDENTITY = HttpHeaderValues.IDENTITY;
/**
* {@code "interleaved"}
*/
public static final AsciiString INTERLEAVED = new AsciiString("interleaved");
/**
* {@code "keep-alive"}
*/
public static final AsciiString KEEP_ALIVE = HttpHeaderValues.KEEP_ALIVE;
/**
* {@code "layers"}
*/
public static final AsciiString LAYERS = new AsciiString("layers");
/**
* {@code "max-age"}
*/
public static final AsciiString MAX_AGE = HttpHeaderValues.MAX_AGE;
/**
* {@code "max-stale"}
*/
public static final AsciiString MAX_STALE = HttpHeaderValues.MAX_STALE;
/**
* {@code "min-fresh"}
*/
public static final AsciiString MIN_FRESH = HttpHeaderValues.MIN_FRESH;
/**
* {@code "mode"}
*/
public static final AsciiString MODE = new AsciiString("mode");
/**
* {@code "multicast"}
*/
public static final AsciiString MULTICAST = new AsciiString("multicast");
/**
* {@code "must-revalidate"}
*/
public static final AsciiString MUST_REVALIDATE = HttpHeaderValues.MUST_REVALIDATE;
/**
* {@code "none"}
*/
public static final AsciiString NONE = HttpHeaderValues.NONE;
/**
* {@code "no-cache"}
*/
public static final AsciiString NO_CACHE = HttpHeaderValues.NO_CACHE;
/**
* {@code "no-transform"}
*/
public static final AsciiString NO_TRANSFORM = HttpHeaderValues.NO_TRANSFORM;
/**
* {@code "only-if-cached"}
*/
public static final AsciiString ONLY_IF_CACHED = HttpHeaderValues.ONLY_IF_CACHED;
/**
* {@code "port"}
*/
public static final AsciiString PORT = new AsciiString("port");
/**
* {@code "private"}
*/
public static final AsciiString PRIVATE = HttpHeaderValues.PRIVATE;
/**
* {@code "proxy-revalidate"}
*/
public static final AsciiString PROXY_REVALIDATE = HttpHeaderValues.PROXY_REVALIDATE;
/**
* {@code "public"}
*/
public static final AsciiString PUBLIC = HttpHeaderValues.PUBLIC;
/**
* {@code "RTP"}
*/
public static final AsciiString RTP = new AsciiString("RTP");
/**
* {@code "rtptime"}
*/
public static final AsciiString RTPTIME = new AsciiString("rtptime");
/**
* {@code "seq"}
*/
public static final AsciiString SEQ = new AsciiString("seq");
/**
* {@code "server_port"}
*/
public static final AsciiString SERVER_PORT = new AsciiString("server_port");
/**
* {@code "ssrc"}
*/
public static final AsciiString SSRC = new AsciiString("ssrc");
/**
* {@code "TCP"}
*/
public static final AsciiString TCP = new AsciiString("TCP");
/**
* {@code "time"}
*/
public static final AsciiString TIME = new AsciiString("time");
/**
* {@code "timeout"}
*/
public static final AsciiString TIMEOUT = new AsciiString("timeout");
/**
* {@code "ttl"}
*/
public static final AsciiString TTL = new AsciiString("ttl");
/**
* {@code "UDP"}
*/
public static final AsciiString UDP = new AsciiString("UDP");
/**
* {@code "unicast"}
*/
public static final AsciiString UNICAST = new AsciiString("unicast");
/**
* {@code "url"}
*/
public static final AsciiString URL = new AsciiString("url");
private RtspHeaderValues() { }
}

View File

@ -1,389 +0,0 @@
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.rtsp;
import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.http.HttpHeaders;
/**
* Standard RTSP header names and values.
*/
public final class RtspHeaders {
/**
* Standard RTSP header names.
*/
public static final class Names {
/**
* {@code "Accept"}
*/
public static final CharSequence ACCEPT = HttpHeaders.Names.ACCEPT;
/**
* {@code "Accept-Encoding"}
*/
public static final CharSequence ACCEPT_ENCODING = HttpHeaders.Names.ACCEPT_ENCODING;
/**
* {@code "Accept-Lanugage"}
*/
public static final CharSequence ACCEPT_LANGUAGE = HttpHeaders.Names.ACCEPT_LANGUAGE;
/**
* {@code "Allow"}
*/
public static final CharSequence ALLOW = new AsciiString("Allow");
/**
* {@code "Authorization"}
*/
public static final CharSequence AUTHORIZATION = HttpHeaders.Names.AUTHORIZATION;
/**
* {@code "Bandwidth"}
*/
public static final CharSequence BANDWIDTH = new AsciiString("Bandwidth");
/**
* {@code "Blocksize"}
*/
public static final CharSequence BLOCKSIZE = new AsciiString("Blocksize");
/**
* {@code "Cache-Control"}
*/
public static final CharSequence CACHE_CONTROL = HttpHeaders.Names.CACHE_CONTROL;
/**
* {@code "Conference"}
*/
public static final CharSequence CONFERENCE = new AsciiString("Conference");
/**
* {@code "Connection"}
*/
public static final CharSequence CONNECTION = HttpHeaders.Names.CONNECTION;
/**
* {@code "Content-Base"}
*/
public static final CharSequence CONTENT_BASE = HttpHeaders.Names.CONTENT_BASE;
/**
* {@code "Content-Encoding"}
*/
public static final CharSequence CONTENT_ENCODING = HttpHeaders.Names.CONTENT_ENCODING;
/**
* {@code "Content-Language"}
*/
public static final CharSequence CONTENT_LANGUAGE = HttpHeaders.Names.CONTENT_LANGUAGE;
/**
* {@code "Content-Length"}
*/
public static final CharSequence CONTENT_LENGTH = HttpHeaders.Names.CONTENT_LENGTH;
/**
* {@code "Content-Location"}
*/
public static final CharSequence CONTENT_LOCATION = HttpHeaders.Names.CONTENT_LOCATION;
/**
* {@code "Content-Type"}
*/
public static final CharSequence CONTENT_TYPE = HttpHeaders.Names.CONTENT_TYPE;
/**
* {@code "CSeq"}
*/
public static final CharSequence CSEQ = new AsciiString("CSeq");
/**
* {@code "Date"}
*/
public static final CharSequence DATE = HttpHeaders.Names.DATE;
/**
* {@code "Expires"}
*/
public static final CharSequence EXPIRES = HttpHeaders.Names.EXPIRES;
/**
* {@code "From"}
*/
public static final CharSequence FROM = HttpHeaders.Names.FROM;
/**
* {@code "Host"}
*/
public static final CharSequence HOST = HttpHeaders.Names.HOST;
/**
* {@code "If-Match"}
*/
public static final CharSequence IF_MATCH = HttpHeaders.Names.IF_MATCH;
/**
* {@code "If-Modified-Since"}
*/
public static final CharSequence IF_MODIFIED_SINCE = HttpHeaders.Names.IF_MODIFIED_SINCE;
/**
* {@code "KeyMgmt"}
*/
public static final CharSequence KEYMGMT = new AsciiString("KeyMgmt");
/**
* {@code "Last-Modified"}
*/
public static final CharSequence LAST_MODIFIED = HttpHeaders.Names.LAST_MODIFIED;
/**
* {@code "Proxy-Authenticate"}
*/
public static final CharSequence PROXY_AUTHENTICATE = HttpHeaders.Names.PROXY_AUTHENTICATE;
/**
* {@code "Proxy-Require"}
*/
public static final CharSequence PROXY_REQUIRE = new AsciiString("Proxy-Require");
/**
* {@code "Public"}
*/
public static final CharSequence PUBLIC = new AsciiString("Public");
/**
* {@code "Range"}
*/
public static final CharSequence RANGE = HttpHeaders.Names.RANGE;
/**
* {@code "Referer"}
*/
public static final CharSequence REFERER = HttpHeaders.Names.REFERER;
/**
* {@code "Require"}
*/
public static final CharSequence REQUIRE = new AsciiString("Require");
/**
* {@code "Retry-After"}
*/
public static final CharSequence RETRT_AFTER = HttpHeaders.Names.RETRY_AFTER;
/**
* {@code "RTP-Info"}
*/
public static final CharSequence RTP_INFO = new AsciiString("RTP-Info");
/**
* {@code "Scale"}
*/
public static final CharSequence SCALE = new AsciiString("Scale");
/**
* {@code "Session"}
*/
public static final CharSequence SESSION = new AsciiString("Session");
/**
* {@code "Server"}
*/
public static final CharSequence SERVER = HttpHeaders.Names.SERVER;
/**
* {@code "Speed"}
*/
public static final CharSequence SPEED = new AsciiString("Speed");
/**
* {@code "Timestamp"}
*/
public static final CharSequence TIMESTAMP = new AsciiString("Timestamp");
/**
* {@code "Transport"}
*/
public static final CharSequence TRANSPORT = new AsciiString("Transport");
/**
* {@code "Unsupported"}
*/
public static final CharSequence UNSUPPORTED = new AsciiString("Unsupported");
/**
* {@code "User-Agent"}
*/
public static final CharSequence USER_AGENT = HttpHeaders.Names.USER_AGENT;
/**
* {@code "Vary"}
*/
public static final CharSequence VARY = HttpHeaders.Names.VARY;
/**
* {@code "Via"}
*/
public static final CharSequence VIA = HttpHeaders.Names.VIA;
/**
* {@code "WWW-Authenticate"}
*/
public static final CharSequence WWW_AUTHENTICATE = HttpHeaders.Names.WWW_AUTHENTICATE;
private Names() {
}
}
/**
* Standard RTSP header values.
*/
public static final class Values {
/**
* {@code "append"}
*/
public static final CharSequence APPEND = new AsciiString("append");
/**
* {@code "AVP"}
*/
public static final CharSequence AVP = new AsciiString("AVP");
/**
* {@code "bytes"}
*/
public static final CharSequence BYTES = HttpHeaders.Values.BYTES;
/**
* {@code "charset"}
*/
public static final CharSequence CHARSET = HttpHeaders.Values.CHARSET;
/**
* {@code "client_port"}
*/
public static final CharSequence CLIENT_PORT = new AsciiString("client_port");
/**
* {@code "clock"}
*/
public static final CharSequence CLOCK = new AsciiString("clock");
/**
* {@code "close"}
*/
public static final CharSequence CLOSE = HttpHeaders.Values.CLOSE;
/**
* {@code "compress"}
*/
public static final CharSequence COMPRESS = HttpHeaders.Values.COMPRESS;
/**
* {@code "100-continue"}
*/
public static final CharSequence CONTINUE = HttpHeaders.Values.CONTINUE;
/**
* {@code "deflate"}
*/
public static final CharSequence DEFLATE = HttpHeaders.Values.DEFLATE;
/**
* {@code "destination"}
*/
public static final CharSequence DESTINATION = new AsciiString("destination");
/**
* {@code "gzip"}
*/
public static final CharSequence GZIP = HttpHeaders.Values.GZIP;
/**
* {@code "identity"}
*/
public static final CharSequence IDENTITY = HttpHeaders.Values.IDENTITY;
/**
* {@code "interleaved"}
*/
public static final CharSequence INTERLEAVED = new AsciiString("interleaved");
/**
* {@code "keep-alive"}
*/
public static final CharSequence KEEP_ALIVE = HttpHeaders.Values.KEEP_ALIVE;
/**
* {@code "layers"}
*/
public static final CharSequence LAYERS = new AsciiString("layers");
/**
* {@code "max-age"}
*/
public static final CharSequence MAX_AGE = HttpHeaders.Values.MAX_AGE;
/**
* {@code "max-stale"}
*/
public static final CharSequence MAX_STALE = HttpHeaders.Values.MAX_STALE;
/**
* {@code "min-fresh"}
*/
public static final CharSequence MIN_FRESH = HttpHeaders.Values.MIN_FRESH;
/**
* {@code "mode"}
*/
public static final CharSequence MODE = new AsciiString("mode");
/**
* {@code "multicast"}
*/
public static final CharSequence MULTICAST = new AsciiString("multicast");
/**
* {@code "must-revalidate"}
*/
public static final CharSequence MUST_REVALIDATE = HttpHeaders.Values.MUST_REVALIDATE;
/**
* {@code "none"}
*/
public static final CharSequence NONE = HttpHeaders.Values.NONE;
/**
* {@code "no-cache"}
*/
public static final CharSequence NO_CACHE = HttpHeaders.Values.NO_CACHE;
/**
* {@code "no-transform"}
*/
public static final CharSequence NO_TRANSFORM = HttpHeaders.Values.NO_TRANSFORM;
/**
* {@code "only-if-cached"}
*/
public static final CharSequence ONLY_IF_CACHED = HttpHeaders.Values.ONLY_IF_CACHED;
/**
* {@code "port"}
*/
public static final CharSequence PORT = new AsciiString("port");
/**
* {@code "private"}
*/
public static final CharSequence PRIVATE = HttpHeaders.Values.PRIVATE;
/**
* {@code "proxy-revalidate"}
*/
public static final CharSequence PROXY_REVALIDATE = HttpHeaders.Values.PROXY_REVALIDATE;
/**
* {@code "public"}
*/
public static final CharSequence PUBLIC = HttpHeaders.Values.PUBLIC;
/**
* {@code "RTP"}
*/
public static final CharSequence RTP = new AsciiString("RTP");
/**
* {@code "rtptime"}
*/
public static final CharSequence RTPTIME = new AsciiString("rtptime");
/**
* {@code "seq"}
*/
public static final CharSequence SEQ = new AsciiString("seq");
/**
* {@code "server_port"}
*/
public static final CharSequence SERVER_PORT = new AsciiString("server_port");
/**
* {@code "ssrc"}
*/
public static final CharSequence SSRC = new AsciiString("ssrc");
/**
* {@code "TCP"}
*/
public static final CharSequence TCP = new AsciiString("TCP");
/**
* {@code "time"}
*/
public static final CharSequence TIME = new AsciiString("time");
/**
* {@code "timeout"}
*/
public static final CharSequence TIMEOUT = new AsciiString("timeout");
/**
* {@code "ttl"}
*/
public static final CharSequence TTL = new AsciiString("ttl");
/**
* {@code "UDP"}
*/
public static final CharSequence UDP = new AsciiString("UDP");
/**
* {@code "unicast"}
*/
public static final CharSequence UNICAST = new AsciiString("unicast");
/**
* {@code "url"}
*/
public static final CharSequence URL = new AsciiString("url");
private Values() { }
}
private RtspHeaders() { }
}

View File

@ -79,7 +79,7 @@ public abstract class RtspObjectDecoder extends HttpObjectDecoder {
if (empty) { if (empty) {
return true; return true;
} }
if (!msg.headers().contains(RtspHeaders.Names.CONTENT_LENGTH)) { if (!msg.headers().contains(RtspHeaderNames.CONTENT_LENGTH)) {
return true; return true;
} }
return empty; return empty;

View File

@ -24,8 +24,8 @@ import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -342,7 +342,7 @@ public class SpdyHttpDecoder extends MessageToMessageDecoder<SpdyFrame> {
// Replace the SPDY host header with the HTTP host header // Replace the SPDY host header with the HTTP host header
CharSequence host = headers.get(HOST); CharSequence host = headers.get(HOST);
headers.remove(HOST); headers.remove(HOST);
req.headers().set(HttpHeaders.Names.HOST, host); req.headers().set(HttpHeaderNames.HOST, host);
for (Map.Entry<CharSequence, CharSequence> e: requestFrame.headers()) { for (Map.Entry<CharSequence, CharSequence> e: requestFrame.headers()) {
req.headers().add(e.getKey(), e.getValue()); req.headers().add(e.getKey(), e.getValue());
@ -352,7 +352,7 @@ public class SpdyHttpDecoder extends MessageToMessageDecoder<SpdyFrame> {
HttpHeaderUtil.setKeepAlive(req, true); HttpHeaderUtil.setKeepAlive(req, true);
// Transfer-Encoding header is not valid // Transfer-Encoding header is not valid
req.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING); req.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
return req; return req;
} }
@ -376,8 +376,8 @@ public class SpdyHttpDecoder extends MessageToMessageDecoder<SpdyFrame> {
HttpHeaderUtil.setKeepAlive(res, true); HttpHeaderUtil.setKeepAlive(res, true);
// Transfer-Encoding header is not valid // Transfer-Encoding header is not valid
res.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING); res.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
res.headers().remove(HttpHeaders.Names.TRAILER); res.headers().remove(HttpHeaderNames.TRAILER);
return res; return res;
} }

View File

@ -21,6 +21,7 @@ import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObject;
@ -222,10 +223,10 @@ public class SpdyHttpEncoder extends MessageToMessageEncoder<HttpObject> {
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent. // headers are not valid and MUST not be sent.
httpHeaders.remove(HttpHeaders.Names.CONNECTION); httpHeaders.remove(HttpHeaderNames.CONNECTION);
httpHeaders.remove(HttpHeaders.Names.KEEP_ALIVE); httpHeaders.remove(HttpHeaderNames.KEEP_ALIVE);
httpHeaders.remove(HttpHeaders.Names.PROXY_CONNECTION); httpHeaders.remove(HttpHeaderNames.PROXY_CONNECTION);
httpHeaders.remove(HttpHeaders.Names.TRANSFER_ENCODING); httpHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
SpdySynStreamFrame spdySynStreamFrame = SpdySynStreamFrame spdySynStreamFrame =
new DefaultSpdySynStreamFrame(streamID, associatedToStreamId, priority); new DefaultSpdySynStreamFrame(streamID, associatedToStreamId, priority);
@ -248,8 +249,8 @@ public class SpdyHttpEncoder extends MessageToMessageEncoder<HttpObject> {
// Replace the HTTP host header with the SPDY host header // Replace the HTTP host header with the SPDY host header
if (spdyVersion >= 3) { if (spdyVersion >= 3) {
CharSequence host = httpHeaders.get(HttpHeaders.Names.HOST); CharSequence host = httpHeaders.get(HttpHeaderNames.HOST);
httpHeaders.remove(HttpHeaders.Names.HOST); httpHeaders.remove(HttpHeaderNames.HOST);
frameHeaders.set(HOST, host); frameHeaders.set(HOST, host);
} }
@ -278,10 +279,10 @@ public class SpdyHttpEncoder extends MessageToMessageEncoder<HttpObject> {
// The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding // The Connection, Keep-Alive, Proxy-Connection, and Transfer-Encoding
// headers are not valid and MUST not be sent. // headers are not valid and MUST not be sent.
httpHeaders.remove(HttpHeaders.Names.CONNECTION); httpHeaders.remove(HttpHeaderNames.CONNECTION);
httpHeaders.remove(HttpHeaders.Names.KEEP_ALIVE); httpHeaders.remove(HttpHeaderNames.KEEP_ALIVE);
httpHeaders.remove(HttpHeaders.Names.PROXY_CONNECTION); httpHeaders.remove(HttpHeaderNames.PROXY_CONNECTION);
httpHeaders.remove(HttpHeaders.Names.TRANSFER_ENCODING); httpHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
SpdySynReplyFrame spdySynReplyFrame = new DefaultSpdySynReplyFrame(streamID); SpdySynReplyFrame spdySynReplyFrame = new DefaultSpdySynReplyFrame(streamID);
SpdyHeaders frameHeaders = spdySynReplyFrame.headers(); SpdyHeaders frameHeaders = spdySynReplyFrame.headers();

View File

@ -19,8 +19,6 @@ import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.Test;
@ -110,7 +108,7 @@ public class HttpContentCompressorTest {
ch.writeInbound(newRequest()); ch.writeInbound(newRequest());
HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
res.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
ch.writeOutbound(res); ch.writeOutbound(res);
assertEncodedResponse(ch); assertEncodedResponse(ch);
@ -151,7 +149,7 @@ public class HttpContentCompressorTest {
ch.writeInbound(newRequest()); ch.writeInbound(newRequest());
HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
res.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
ch.writeOutbound(res); ch.writeOutbound(res);
assertEncodedResponse(ch); assertEncodedResponse(ch);
@ -197,7 +195,7 @@ public class HttpContentCompressorTest {
FullHttpResponse res = new DefaultFullHttpResponse( FullHttpResponse res = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII)); Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII));
res.headers().setInt(Names.CONTENT_LENGTH, res.content().readableBytes()); res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, res.content().readableBytes());
ch.writeOutbound(res); ch.writeOutbound(res);
assertEncodedResponse(ch); assertEncodedResponse(ch);
@ -262,10 +260,10 @@ public class HttpContentCompressorTest {
assertThat(o, is(instanceOf(FullHttpResponse.class))); assertThat(o, is(instanceOf(FullHttpResponse.class)));
res = (FullHttpResponse) o; res = (FullHttpResponse) o;
assertThat(res.headers().get(Names.TRANSFER_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue()));
// Content encoding shouldn't be modified. // Content encoding shouldn't be modified.
assertThat(res.headers().get(Names.CONTENT_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is(nullValue()));
assertThat(res.content().readableBytes(), is(0)); assertThat(res.content().readableBytes(), is(0));
assertThat(res.content().toString(CharsetUtil.US_ASCII), is("")); assertThat(res.content().toString(CharsetUtil.US_ASCII), is(""));
res.release(); res.release();
@ -287,10 +285,10 @@ public class HttpContentCompressorTest {
assertThat(o, is(instanceOf(FullHttpResponse.class))); assertThat(o, is(instanceOf(FullHttpResponse.class)));
res = (FullHttpResponse) o; res = (FullHttpResponse) o;
assertThat(res.headers().get(Names.TRANSFER_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue()));
// Content encoding shouldn't be modified. // Content encoding shouldn't be modified.
assertThat(res.headers().get(Names.CONTENT_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is(nullValue()));
assertThat(res.content().readableBytes(), is(0)); assertThat(res.content().readableBytes(), is(0));
assertThat(res.content().toString(CharsetUtil.US_ASCII), is("")); assertThat(res.content().toString(CharsetUtil.US_ASCII), is(""));
assertEquals("Netty", res.trailingHeaders().get("X-Test")); assertEquals("Netty", res.trailingHeaders().get("X-Test"));
@ -299,7 +297,7 @@ public class HttpContentCompressorTest {
private static FullHttpRequest newRequest() { private static FullHttpRequest newRequest() {
FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
req.headers().set(Names.ACCEPT_ENCODING, "gzip"); req.headers().set(HttpHeaderNames.ACCEPT_ENCODING, "gzip");
return req; return req;
} }
@ -309,8 +307,8 @@ public class HttpContentCompressorTest {
HttpResponse res = (HttpResponse) o; HttpResponse res = (HttpResponse) o;
assertThat(res, is(not(instanceOf(HttpContent.class)))); assertThat(res, is(not(instanceOf(HttpContent.class))));
assertThat(res.headers().getAndConvert(Names.TRANSFER_ENCODING), is("chunked")); assertThat(res.headers().getAndConvert(HttpHeaderNames.TRANSFER_ENCODING), is("chunked"));
assertThat(res.headers().get(Names.CONTENT_LENGTH), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.CONTENT_LENGTH), is(nullValue()));
assertThat(res.headers().getAndConvert(Names.CONTENT_ENCODING), is("gzip")); assertThat(res.headers().getAndConvert(HttpHeaderNames.CONTENT_ENCODING), is("gzip"));
} }
} }

View File

@ -21,8 +21,6 @@ import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.Test;
@ -83,7 +81,7 @@ public class HttpContentEncoderTest {
ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")); ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
res.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
ch.writeOutbound(res); ch.writeOutbound(res);
assertEncodedResponse(ch); assertEncodedResponse(ch);
@ -120,7 +118,7 @@ public class HttpContentEncoderTest {
ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")); ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
res.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
ch.writeOutbound(res); ch.writeOutbound(res);
assertEncodedResponse(ch); assertEncodedResponse(ch);
@ -161,7 +159,7 @@ public class HttpContentEncoderTest {
FullHttpResponse res = new DefaultFullHttpResponse( FullHttpResponse res = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(new byte[42])); HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(new byte[42]));
res.headers().setInt(Names.CONTENT_LENGTH, 42); res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 42);
ch.writeOutbound(res); ch.writeOutbound(res);
assertEncodedResponse(ch); assertEncodedResponse(ch);
@ -219,10 +217,10 @@ public class HttpContentEncoderTest {
assertThat(o, is(instanceOf(FullHttpResponse.class))); assertThat(o, is(instanceOf(FullHttpResponse.class)));
res = (FullHttpResponse) o; res = (FullHttpResponse) o;
assertThat(res.headers().get(Names.TRANSFER_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue()));
// Content encoding shouldn't be modified. // Content encoding shouldn't be modified.
assertThat(res.headers().get(Names.CONTENT_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is(nullValue()));
assertThat(res.content().readableBytes(), is(0)); assertThat(res.content().readableBytes(), is(0));
assertThat(res.content().toString(CharsetUtil.US_ASCII), is("")); assertThat(res.content().toString(CharsetUtil.US_ASCII), is(""));
res.release(); res.release();
@ -244,10 +242,10 @@ public class HttpContentEncoderTest {
assertThat(o, is(instanceOf(FullHttpResponse.class))); assertThat(o, is(instanceOf(FullHttpResponse.class)));
res = (FullHttpResponse) o; res = (FullHttpResponse) o;
assertThat(res.headers().get(Names.TRANSFER_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue()));
// Content encoding shouldn't be modified. // Content encoding shouldn't be modified.
assertThat(res.headers().get(Names.CONTENT_ENCODING), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is(nullValue()));
assertThat(res.content().readableBytes(), is(0)); assertThat(res.content().readableBytes(), is(0));
assertThat(res.content().toString(CharsetUtil.US_ASCII), is("")); assertThat(res.content().toString(CharsetUtil.US_ASCII), is(""));
assertEquals("Netty", res.trailingHeaders().get("X-Test")); assertEquals("Netty", res.trailingHeaders().get("X-Test"));
@ -260,8 +258,8 @@ public class HttpContentEncoderTest {
HttpResponse res = (HttpResponse) o; HttpResponse res = (HttpResponse) o;
assertThat(res, is(not(instanceOf(HttpContent.class)))); assertThat(res, is(not(instanceOf(HttpContent.class))));
assertThat(res.headers().getAndConvert(Names.TRANSFER_ENCODING), is("chunked")); assertThat(res.headers().getAndConvert(HttpHeaderNames.TRANSFER_ENCODING), is("chunked"));
assertThat(res.headers().get(Names.CONTENT_LENGTH), is(nullValue())); assertThat(res.headers().get(HttpHeaderNames.CONTENT_LENGTH), is(nullValue()));
assertThat(res.headers().getAndConvert(Names.CONTENT_ENCODING), is("test")); assertThat(res.headers().getAndConvert(HttpHeaderNames.CONTENT_ENCODING), is("test"));
} }
} }

View File

@ -28,7 +28,7 @@ public class HttpHeaderUtilTest {
@Test @Test
public void testRemoveTransferEncodingIgnoreCase() { public void testRemoveTransferEncodingIgnoreCase() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, "Chunked"); message.headers().set(HttpHeaderNames.TRANSFER_ENCODING, "Chunked");
assertFalse(message.headers().isEmpty()); assertFalse(message.headers().isEmpty());
HttpHeaderUtil.setTransferEncodingChunked(message, false); HttpHeaderUtil.setTransferEncodingChunked(message, false);
assertTrue(message.headers().isEmpty()); assertTrue(message.headers().isEmpty());

View File

@ -22,7 +22,6 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.DecoderResultProvider; import io.netty.handler.codec.DecoderResultProvider;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.junit.Test; import org.junit.Test;
@ -119,7 +118,7 @@ public class HttpObjectAggregatorTest {
FullHttpResponse response = embedder.readOutbound(); FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status()); assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(Names.CONTENT_LENGTH)); assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertFalse(embedder.isOpen()); assertFalse(embedder.isOpen());
try { try {
@ -166,7 +165,7 @@ public class HttpObjectAggregatorTest {
// The agregator should respond with '413 Request Entity Too Large.' // The agregator should respond with '413 Request Entity Too Large.'
FullHttpResponse response = embedder.readOutbound(); FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status()); assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(Names.CONTENT_LENGTH)); assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// An ill-behaving client could continue to send data without a respect, and such data should be discarded. // An ill-behaving client could continue to send data without a respect, and such data should be discarded.
assertFalse(embedder.writeInbound(chunk1)); assertFalse(embedder.writeInbound(chunk1));
@ -206,7 +205,7 @@ public class HttpObjectAggregatorTest {
FullHttpResponse response = embedder.readOutbound(); FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status()); assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(Names.CONTENT_LENGTH)); assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// Keep-alive is on by default in HTTP/1.1, so the connection should be still alive. // Keep-alive is on by default in HTTP/1.1, so the connection should be still alive.
assertTrue(embedder.isOpen()); assertTrue(embedder.isOpen());
@ -242,7 +241,7 @@ public class HttpObjectAggregatorTest {
// The agregator should respond with '413 Request Entity Too Large.' // The agregator should respond with '413 Request Entity Too Large.'
FullHttpResponse response = embedder.readOutbound(); FullHttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status()); assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(Names.CONTENT_LENGTH)); assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
// An ill-behaving client could continue to send data without a respect, and such data should be discarded. // An ill-behaving client could continue to send data without a respect, and such data should be discarded.
assertFalse(embedder.writeInbound(chunk1)); assertFalse(embedder.writeInbound(chunk1));
@ -276,7 +275,7 @@ public class HttpObjectAggregatorTest {
assertFalse(embedder.writeInbound(message)); assertFalse(embedder.writeInbound(message));
HttpResponse response = embedder.readOutbound(); HttpResponse response = embedder.readOutbound();
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status()); assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
assertEquals("0", response.headers().get(Names.CONTENT_LENGTH)); assertEquals("0", response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
if (serverShouldCloseConnection(message)) { if (serverShouldCloseConnection(message)) {
assertFalse(embedder.isOpen()); assertFalse(embedder.isOpen());

View File

@ -17,7 +17,6 @@ package io.netty.handler.codec.http;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.Test;
@ -184,7 +183,7 @@ public class HttpResponseDecoderTest {
HttpResponse res = ch.readInbound(); HttpResponse res = ch.readInbound();
assertThat(res.protocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.protocolVersion(), sameInstance(HttpVersion.HTTP_1_1));
assertThat(res.status(), is(HttpResponseStatus.OK)); assertThat(res.status(), is(HttpResponseStatus.OK));
assertThat(res.headers().getAndConvert(Names.TRANSFER_ENCODING), is("chunked")); assertThat(res.headers().getAndConvert(HttpHeaderNames.TRANSFER_ENCODING), is("chunked"));
assertThat(ch.readInbound(), is(nullValue())); assertThat(ch.readInbound(), is(nullValue()));
// Close the connection without sending anything. // Close the connection without sending anything.
@ -205,7 +204,7 @@ public class HttpResponseDecoderTest {
HttpResponse res = ch.readInbound(); HttpResponse res = ch.readInbound();
assertThat(res.protocolVersion(), sameInstance(HttpVersion.HTTP_1_1)); assertThat(res.protocolVersion(), sameInstance(HttpVersion.HTTP_1_1));
assertThat(res.status(), is(HttpResponseStatus.OK)); assertThat(res.status(), is(HttpResponseStatus.OK));
assertThat(res.headers().getAndConvert(Names.TRANSFER_ENCODING), is("chunked")); assertThat(res.headers().getAndConvert(HttpHeaderNames.TRANSFER_ENCODING), is("chunked"));
// Read the partial content. // Read the partial content.
HttpContent content = ch.readInbound(); HttpContent content = ch.readInbound();

View File

@ -36,13 +36,13 @@ public class HttpResponseEncoderTest {
public void testLargeFileRegionChunked() throws Exception { public void testLargeFileRegionChunked() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
assertTrue(channel.writeOutbound(response)); assertTrue(channel.writeOutbound(response));
ByteBuf buffer = channel.readOutbound(); ByteBuf buffer = channel.readOutbound();
assertEquals("HTTP/1.1 200 OK\r\n" + HttpHeaders.Names.TRANSFER_ENCODING + ": " + assertEquals("HTTP/1.1 200 OK\r\n" + HttpHeaderNames.TRANSFER_ENCODING + ": " +
HttpHeaders.Values.CHUNKED + "\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII)); HttpHeaderValues.CHUNKED + "\r\n\r\n", buffer.toString(CharsetUtil.US_ASCII));
buffer.release(); buffer.release();
assertTrue(channel.writeOutbound(FILE_REGION)); assertTrue(channel.writeOutbound(FILE_REGION));
buffer = channel.readOutbound(); buffer = channel.readOutbound();

View File

@ -21,7 +21,6 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.Test;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -92,7 +91,7 @@ public class HttpServerCodecTest {
// Ensure the aggregator generates a full request. // Ensure the aggregator generates a full request.
FullHttpRequest req = ch.readInbound(); FullHttpRequest req = ch.readInbound();
assertThat(req.headers().getAndConvert(CONTENT_LENGTH), is("1")); assertThat(req.headers().getAndConvert(HttpHeaderNames.CONTENT_LENGTH), is("1"));
assertThat(req.content().readableBytes(), is(1)); assertThat(req.content().readableBytes(), is(1));
assertThat(req.content().readByte(), is((byte) 42)); assertThat(req.content().readByte(), is((byte) 42));
req.release(); req.release();
@ -103,13 +102,13 @@ public class HttpServerCodecTest {
// Send the actual response. // Send the actual response.
FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED); FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED);
res.content().writeBytes("OK".getBytes(CharsetUtil.UTF_8)); res.content().writeBytes("OK".getBytes(CharsetUtil.UTF_8));
res.headers().setInt(CONTENT_LENGTH, 2); res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 2);
ch.writeOutbound(res); ch.writeOutbound(res);
// Ensure the encoder handles the response after handling 100 Continue. // Ensure the encoder handles the response after handling 100 Continue.
ByteBuf encodedRes = ch.readOutbound(); ByteBuf encodedRes = ch.readOutbound();
assertThat(encodedRes.toString(CharsetUtil.UTF_8), is("HTTP/1.1 201 Created\r\n" + assertThat(encodedRes.toString(CharsetUtil.UTF_8),
CONTENT_LENGTH + ": 2\r\n\r\nOK")); is("HTTP/1.1 201 Created\r\n" + HttpHeaderNames.CONTENT_LENGTH + ": 2\r\n\r\nOK"));
encodedRes.release(); encodedRes.release();
ch.finish(); ch.finish();

View File

@ -15,7 +15,7 @@
*/ */
package io.netty.handler.codec.http.cors; package io.netty.handler.codec.http.cors;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import org.junit.Test; import org.junit.Test;
@ -107,8 +107,8 @@ public class CorsConfigTest {
@Test @Test
public void defaultPreflightResponseHeaders() { public void defaultPreflightResponseHeaders() {
final CorsConfig cors = withAnyOrigin().build(); final CorsConfig cors = withAnyOrigin().build();
assertThat(cors.preflightResponseHeaders().get(Names.DATE), is(notNullValue())); assertThat(cors.preflightResponseHeaders().get(HttpHeaderNames.DATE), is(notNullValue()));
assertThat(cors.preflightResponseHeaders().getAndConvert(Names.CONTENT_LENGTH), is("0")); assertThat(cors.preflightResponseHeaders().getAndConvert(HttpHeaderNames.CONTENT_LENGTH), is("0"));
} }
@Test @Test

View File

@ -28,7 +28,7 @@ import org.junit.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpResponseStatus.OK;

View File

@ -24,7 +24,8 @@ import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.LastHttpContent;
@ -62,8 +63,8 @@ public class HttpPostRequestDecoderTest {
"http://localhost"); "http://localhost");
req.setDecoderResult(DecoderResult.SUCCESS); req.setDecoderResult(DecoderResult.SUCCESS);
req.headers().add(HttpHeaders.Names.CONTENT_TYPE, contentTypeValue); req.headers().add(HttpHeaderNames.CONTENT_TYPE, contentTypeValue);
req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
// Force to use memory-based data. // Force to use memory-based data.
final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
@ -106,8 +107,8 @@ public class HttpPostRequestDecoderTest {
"http://localhost"); "http://localhost");
req.setDecoderResult(DecoderResult.SUCCESS); req.setDecoderResult(DecoderResult.SUCCESS);
req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
// Force to use memory-based data. // Force to use memory-based data.
final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
@ -150,8 +151,8 @@ public class HttpPostRequestDecoderTest {
final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"http://localhost"); "http://localhost");
req.setDecoderResult(DecoderResult.SUCCESS); req.setDecoderResult(DecoderResult.SUCCESS);
req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
final String body = final String body =
"--" + boundary + "\r\n" + "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file" + i + "\"\r\n" + "Content-Disposition: form-data; name=\"file" + i + "\"\r\n" +
@ -185,8 +186,8 @@ public class HttpPostRequestDecoderTest {
"http://localhost"); "http://localhost");
req.setDecoderResult(DecoderResult.SUCCESS); req.setDecoderResult(DecoderResult.SUCCESS);
req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=\"" + boundary + '"'); req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=\"" + boundary + '"');
req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
// Force to use memory-based data. // Force to use memory-based data.
final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
@ -218,10 +219,10 @@ public class HttpPostRequestDecoderTest {
DefaultHttpRequest aRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, DefaultHttpRequest aRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, HttpMethod.POST,
"http://localhost"); "http://localhost");
aRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, aRequest.headers().set(HttpHeaderNames.CONTENT_TYPE,
"multipart/form-data; boundary=" + boundary); "multipart/form-data; boundary=" + boundary);
aRequest.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, aRequest.headers().set(HttpHeaderNames.TRANSFER_ENCODING,
HttpHeaders.Values.CHUNKED); HttpHeaderValues.CHUNKED);
HttpPostRequestDecoder aDecoder = new HttpPostRequestDecoder(aMemFactory, aRequest); HttpPostRequestDecoder aDecoder = new HttpPostRequestDecoder(aMemFactory, aRequest);

View File

@ -18,18 +18,17 @@ package io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.EncoderMode; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.EncoderMode;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
import org.junit.Test; import org.junit.Test;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** {@link HttpPostRequestEncoder} test case. */ /** {@link HttpPostRequestEncoder} test case. */

View File

@ -17,13 +17,13 @@ package io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import static io.netty.handler.codec.http.HttpHeaders.Values.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
public class WebSocketRequestBuilder { public class WebSocketRequestBuilder {
@ -48,33 +48,57 @@ public class WebSocketRequestBuilder {
return this; return this;
} }
public WebSocketRequestBuilder uri(String uri) { public WebSocketRequestBuilder uri(CharSequence uri) {
this.uri = uri; if (uri == null) {
this.uri = null;
} else {
this.uri = uri.toString();
}
return this; return this;
} }
public WebSocketRequestBuilder host(String host) { public WebSocketRequestBuilder host(CharSequence host) {
this.host = host; if (host == null) {
this.host = null;
} else {
this.host = host.toString();
}
return this; return this;
} }
public WebSocketRequestBuilder upgrade(String upgrade) { public WebSocketRequestBuilder upgrade(CharSequence upgrade) {
this.upgrade = upgrade; if (upgrade == null) {
this.upgrade = null;
} else {
this.upgrade = upgrade.toString();
}
return this; return this;
} }
public WebSocketRequestBuilder connection(String connection) { public WebSocketRequestBuilder connection(CharSequence connection) {
this.connection = connection; if (connection == null) {
this.connection = null;
} else {
this.connection = connection.toString();
}
return this; return this;
} }
public WebSocketRequestBuilder key(String key) { public WebSocketRequestBuilder key(CharSequence key) {
this.key = key; if (key == null) {
this.key = null;
} else {
this.key = key.toString();
}
return this; return this;
} }
public WebSocketRequestBuilder origin(String origin) { public WebSocketRequestBuilder origin(CharSequence origin) {
this.origin = origin; if (origin == null) {
this.origin = null;
} else {
this.origin = origin.toString();
}
return this; return this;
} }
@ -102,32 +126,33 @@ public class WebSocketRequestBuilder {
HttpHeaders headers = req.headers(); HttpHeaders headers = req.headers();
if (host != null) { if (host != null) {
headers.set(Names.HOST, host); headers.set(HttpHeaderNames.HOST, host);
} }
if (upgrade != null) { if (upgrade != null) {
headers.set(Names.UPGRADE, upgrade); headers.set(HttpHeaderNames.UPGRADE, upgrade);
} }
if (connection != null) { if (connection != null) {
headers.set(Names.CONNECTION, connection); headers.set(HttpHeaderNames.CONNECTION, connection);
} }
if (key != null) { if (key != null) {
headers.set(Names.SEC_WEBSOCKET_KEY, key); headers.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
} }
if (origin != null) { if (origin != null) {
headers.set(Names.SEC_WEBSOCKET_ORIGIN, origin); headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, origin);
} }
if (version != null) { if (version != null) {
headers.set(Names.SEC_WEBSOCKET_VERSION, version.toHttpHeaderValue()); headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version.toHttpHeaderValue());
} }
return req; return req;
} }
public static HttpRequest sucessful() { public static HttpRequest sucessful() {
return new WebSocketRequestBuilder().httpVersion(HTTP_1_1) return new WebSocketRequestBuilder()
.httpVersion(HTTP_1_1)
.method(HttpMethod.GET) .method(HttpMethod.GET)
.uri("/test") .uri("/test")
.host("server.example.com") .host("server.example.com")
.upgrade(WEBSOCKET.toString().toLowerCase()) .upgrade(HttpHeaderValues.WEBSOCKET)
.key("dGhlIHNhbXBsZSBub25jZQ==") .key("dGhlIHNhbXBsZSBub25jZQ==")
.origin("http://example.com") .origin("http://example.com")
.version13() .version13()

View File

@ -19,7 +19,8 @@ import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpRequestDecoder;
@ -32,7 +33,6 @@ import io.netty.util.ReferenceCountUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import static io.netty.handler.codec.http.HttpHeaders.Values.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
public class WebSocketServerHandshaker00Test { public class WebSocketServerHandshaker00Test {
@ -54,13 +54,13 @@ public class WebSocketServerHandshaker00Test {
FullHttpRequest req = ReferenceCountUtil.releaseLater(new DefaultFullHttpRequest( FullHttpRequest req = ReferenceCountUtil.releaseLater(new DefaultFullHttpRequest(
HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII))); HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));
req.headers().set(Names.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(Names.UPGRADE, WEBSOCKET.toString().toLowerCase()); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(Names.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(Names.ORIGIN, "http://example.com"); req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
req.headers().set(Names.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5");
req.headers().set(Names.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1 .P00"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1 .P00");
req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
if (subProtocol) { if (subProtocol) {
new WebSocketServerHandshaker00( new WebSocketServerHandshaker00(
@ -74,12 +74,12 @@ public class WebSocketServerHandshaker00Test {
ch2.writeInbound(ch.readOutbound()); ch2.writeInbound(ch.readOutbound());
HttpResponse res = ch2.readInbound(); HttpResponse res = ch2.readInbound();
Assert.assertEquals("ws://example.com/chat", res.headers().get(Names.SEC_WEBSOCKET_LOCATION)); Assert.assertEquals("ws://example.com/chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_LOCATION));
if (subProtocol) { if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else { } else {
Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} }
LastHttpContent content = ch2.readInbound(); LastHttpContent content = ch2.readInbound();

View File

@ -19,7 +19,8 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpRequestDecoder;
@ -30,7 +31,6 @@ import io.netty.util.ReferenceCountUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import static io.netty.handler.codec.http.HttpHeaders.Values.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
public class WebSocketServerHandshaker08Test { public class WebSocketServerHandshaker08Test {
@ -51,13 +51,13 @@ public class WebSocketServerHandshaker08Test {
FullHttpRequest req = ReferenceCountUtil.releaseLater( FullHttpRequest req = ReferenceCountUtil.releaseLater(
new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat")); new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
req.headers().set(Names.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(Names.UPGRADE, WEBSOCKET.toString().toLowerCase()); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(Names.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ=="); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com");
req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
req.headers().set(Names.SEC_WEBSOCKET_VERSION, "8"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
if (subProtocol) { if (subProtocol) {
new WebSocketServerHandshaker08( new WebSocketServerHandshaker08(
@ -74,11 +74,11 @@ public class WebSocketServerHandshaker08Test {
HttpResponse res = ch2.readInbound(); HttpResponse res = ch2.readInbound();
Assert.assertEquals( Assert.assertEquals(
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT)); "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT));
if (subProtocol) { if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else { } else {
Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} }
ReferenceCountUtil.release(res); ReferenceCountUtil.release(res);
} }

View File

@ -19,7 +19,8 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpRequestDecoder;
@ -30,7 +31,6 @@ import io.netty.util.ReferenceCountUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import static io.netty.handler.codec.http.HttpHeaders.Values.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
public class WebSocketServerHandshaker13Test { public class WebSocketServerHandshaker13Test {
@ -51,13 +51,13 @@ public class WebSocketServerHandshaker13Test {
FullHttpRequest req = ReferenceCountUtil.releaseLater( FullHttpRequest req = ReferenceCountUtil.releaseLater(
new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat")); new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
req.headers().set(Names.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(Names.UPGRADE, WEBSOCKET.toString().toLowerCase()); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(Names.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ=="); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com");
req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
req.headers().set(Names.SEC_WEBSOCKET_VERSION, "13"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
if (subProtocol) { if (subProtocol) {
new WebSocketServerHandshaker13( new WebSocketServerHandshaker13(
@ -74,11 +74,11 @@ public class WebSocketServerHandshaker13Test {
HttpResponse res = ch2.readInbound(); HttpResponse res = ch2.readInbound();
Assert.assertEquals( Assert.assertEquals(
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT)); "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT));
if (subProtocol) { if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else { } else {
Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL)); Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} }
ReferenceCountUtil.release(res); ReferenceCountUtil.release(res);
} }

View File

@ -23,6 +23,7 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpRequestDecoder;
@ -34,7 +35,6 @@ import org.junit.Test;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Queue; import java.util.Queue;
import static io.netty.handler.codec.http.HttpHeaders.Values.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -94,7 +94,7 @@ public class WebSocketServerProtocolHandlerTest {
.uri("/test") .uri("/test")
.key(null) .key(null)
.connection("Upgrade") .connection("Upgrade")
.upgrade(WEBSOCKET.toString().toLowerCase()) .upgrade(HttpHeaderValues.WEBSOCKET)
.version13() .version13()
.build(); .build();

View File

@ -15,21 +15,19 @@
*/ */
package io.netty.handler.codec.http.websocketx.extensions; package io.netty.handler.codec.http.websocketx.extensions;
import static io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionTestUtil.*;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.CodecException; import io.netty.handler.codec.CodecException;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.websocketx.WebSocketFrame; import org.junit.Test;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.Test; import static io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionTestUtil.*;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
public class WebSocketClientExtensionHandlerTest { public class WebSocketClientExtensionHandlerTest {
@ -69,14 +67,14 @@ public class WebSocketClientExtensionHandlerTest {
HttpRequest req2 = ch.readOutbound(); HttpRequest req2 = ch.readOutbound();
List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions(
req2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); req2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
HttpResponse res = newUpgradeResponse("main"); HttpResponse res = newUpgradeResponse("main");
ch.writeInbound(res); ch.writeInbound(res);
HttpResponse res2 = ch.readInbound(); HttpResponse res2 = ch.readInbound();
List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
// test // test
assertEquals(2, reqExts.size()); assertEquals(2, reqExts.size());
@ -86,8 +84,8 @@ public class WebSocketClientExtensionHandlerTest {
assertEquals(1, resExts.size()); assertEquals(1, resExts.size());
assertEquals("main", resExts.get(0).name()); assertEquals("main", resExts.get(0).name());
assertTrue(resExts.get(0).parameters().isEmpty()); assertTrue(resExts.get(0).parameters().isEmpty());
assertTrue(ch.pipeline().get(DummyDecoder.class) != null); assertNotNull(ch.pipeline().get(DummyDecoder.class));
assertTrue(ch.pipeline().get(DummyEncoder.class) != null); assertNotNull(ch.pipeline().get(DummyEncoder.class));
} }
@Test @Test
@ -119,14 +117,14 @@ public class WebSocketClientExtensionHandlerTest {
HttpRequest req2 = ch.readOutbound(); HttpRequest req2 = ch.readOutbound();
List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions(
req2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); req2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
HttpResponse res = newUpgradeResponse("fallback"); HttpResponse res = newUpgradeResponse("fallback");
ch.writeInbound(res); ch.writeInbound(res);
HttpResponse res2 = ch.readInbound(); HttpResponse res2 = ch.readInbound();
List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
// test // test
assertEquals(2, reqExts.size()); assertEquals(2, reqExts.size());
@ -136,8 +134,8 @@ public class WebSocketClientExtensionHandlerTest {
assertEquals(1, resExts.size()); assertEquals(1, resExts.size());
assertEquals("fallback", resExts.get(0).name()); assertEquals("fallback", resExts.get(0).name());
assertTrue(resExts.get(0).parameters().isEmpty()); assertTrue(resExts.get(0).parameters().isEmpty());
assertTrue(ch.pipeline().get(DummyDecoder.class) != null); assertNotNull(ch.pipeline().get(DummyDecoder.class));
assertTrue(ch.pipeline().get(DummyEncoder.class) != null); assertNotNull(ch.pipeline().get(DummyEncoder.class));
} }
@Test @Test
@ -182,14 +180,14 @@ public class WebSocketClientExtensionHandlerTest {
HttpRequest req2 = ch.readOutbound(); HttpRequest req2 = ch.readOutbound();
List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions(
req2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); req2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
HttpResponse res = newUpgradeResponse("main, fallback"); HttpResponse res = newUpgradeResponse("main, fallback");
ch.writeInbound(res); ch.writeInbound(res);
HttpResponse res2 = ch.readInbound(); HttpResponse res2 = ch.readInbound();
List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
// test // test
assertEquals(2, reqExts.size()); assertEquals(2, reqExts.size());
@ -199,10 +197,10 @@ public class WebSocketClientExtensionHandlerTest {
assertEquals(2, resExts.size()); assertEquals(2, resExts.size());
assertEquals("main", resExts.get(0).name()); assertEquals("main", resExts.get(0).name());
assertEquals("fallback", resExts.get(1).name()); assertEquals("fallback", resExts.get(1).name());
assertTrue(ch.pipeline().context(mainEncoder) != null); assertNotNull(ch.pipeline().context(mainEncoder));
assertTrue(ch.pipeline().context(mainDecoder) != null); assertNotNull(ch.pipeline().context(mainDecoder));
assertTrue(ch.pipeline().context(fallbackEncoder) != null); assertNotNull(ch.pipeline().context(fallbackEncoder));
assertTrue(ch.pipeline().context(fallbackDecoder) != null); assertNotNull(ch.pipeline().context(fallbackDecoder));
} }
@Test(expected = CodecException.class) @Test(expected = CodecException.class)
@ -239,7 +237,7 @@ public class WebSocketClientExtensionHandlerTest {
HttpRequest req2 = ch.readOutbound(); HttpRequest req2 = ch.readOutbound();
List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> reqExts = WebSocketExtensionUtil.extractExtensions(
req2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); req2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
HttpResponse res = newUpgradeResponse("main, fallback"); HttpResponse res = newUpgradeResponse("main, fallback");
ch.writeInbound(res); ch.writeInbound(res);

View File

@ -15,23 +15,22 @@
*/ */
package io.netty.handler.codec.http.websocketx.extensions; package io.netty.handler.codec.http.websocketx.extensions;
import java.util.List;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders.Values; import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import java.util.List;
public final class WebSocketExtensionTestUtil { public final class WebSocketExtensionTestUtil {
@ -39,12 +38,12 @@ public final class WebSocketExtensionTestUtil {
HttpRequest req = ReferenceCountUtil.releaseLater(new DefaultHttpRequest( HttpRequest req = ReferenceCountUtil.releaseLater(new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/chat")); HttpVersion.HTTP_1_1, HttpMethod.GET, "/chat"));
req.headers().set(Names.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(Names.UPGRADE, Values.WEBSOCKET.toString().toLowerCase()); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(Names.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(Names.ORIGIN, "http://example.com"); req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
if (ext != null) { if (ext != null) {
req.headers().set(Names.SEC_WEBSOCKET_EXTENSIONS, ext); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, ext);
} }
return req; return req;
@ -54,12 +53,12 @@ public final class WebSocketExtensionTestUtil {
HttpResponse res = ReferenceCountUtil.releaseLater(new DefaultHttpResponse( HttpResponse res = ReferenceCountUtil.releaseLater(new DefaultHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS)); HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS));
res.headers().set(Names.HOST, "server.example.com"); res.headers().set(HttpHeaderNames.HOST, "server.example.com");
res.headers().set(Names.UPGRADE, Values.WEBSOCKET.toString().toLowerCase()); res.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
res.headers().set(Names.CONNECTION, "Upgrade"); res.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
res.headers().set(Names.ORIGIN, "http://example.com"); res.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
if (ext != null) { if (ext != null) {
res.headers().set(Names.SEC_WEBSOCKET_EXTENSIONS, ext); res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, ext);
} }
return res; return res;

View File

@ -15,21 +15,18 @@
*/ */
package io.netty.handler.codec.http.websocketx.extensions; package io.netty.handler.codec.http.websocketx.extensions;
import static io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionTestUtil.*;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.CodecException; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders.Names;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.websocketx.WebSocketFrame; import org.junit.Test;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.Test; import static io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionTestUtil.*;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
public class WebSocketServerExtensionHandlerTest { public class WebSocketServerExtensionHandlerTest {
@ -79,14 +76,14 @@ public class WebSocketServerExtensionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
// test // test
assertEquals(1, resExts.size()); assertEquals(1, resExts.size());
assertEquals("main", resExts.get(0).name()); assertEquals("main", resExts.get(0).name());
assertTrue(resExts.get(0).parameters().isEmpty()); assertTrue(resExts.get(0).parameters().isEmpty());
assertTrue(ch.pipeline().get(DummyDecoder.class) != null); assertNotNull(ch.pipeline().get(DummyDecoder.class));
assertTrue(ch.pipeline().get(DummyEncoder.class) != null); assertNotNull(ch.pipeline().get(DummyEncoder.class));
} }
@Test @Test
@ -130,16 +127,16 @@ public class WebSocketServerExtensionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> resExts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
// test // test
assertEquals(2, resExts.size()); assertEquals(2, resExts.size());
assertEquals("main", resExts.get(0).name()); assertEquals("main", resExts.get(0).name());
assertEquals("fallback", resExts.get(1).name()); assertEquals("fallback", resExts.get(1).name());
assertTrue(ch.pipeline().get(DummyDecoder.class) != null); assertNotNull(ch.pipeline().get(DummyDecoder.class));
assertTrue(ch.pipeline().get(DummyEncoder.class) != null); assertNotNull(ch.pipeline().get(DummyEncoder.class));
assertTrue(ch.pipeline().get(Dummy2Decoder.class) != null); assertNotNull(ch.pipeline().get(Dummy2Decoder.class));
assertTrue(ch.pipeline().get(Dummy2Encoder.class) != null); assertNotNull(ch.pipeline().get(Dummy2Encoder.class));
} }
@Test @Test
@ -170,7 +167,7 @@ public class WebSocketServerExtensionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
// test // test
assertFalse(res2.headers().contains(Names.SEC_WEBSOCKET_EXTENSIONS)); assertFalse(res2.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
} }
} }

View File

@ -15,21 +15,21 @@
*/ */
package io.netty.handler.codec.http.websocketx.extensions.compression; package io.netty.handler.codec.http.websocketx.extensions.compression;
import static io.netty.handler.codec.http.websocketx.extensions.compression.
PerMessageDeflateServerExtensionHandshaker.*;
import static io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionTestUtil.*;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionData; import io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionData;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionUtil; import io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionUtil;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketServerExtensionHandler; import io.netty.handler.codec.http.websocketx.extensions.WebSocketServerExtensionHandler;
import io.netty.handler.codec.http.HttpHeaders.Names; import org.junit.Test;
import java.util.List; import java.util.List;
import org.junit.Assert; import static io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionTestUtil.*;
import org.junit.Test; import static io.netty.handler.codec.http.websocketx.extensions.compression.
PerMessageDeflateServerExtensionHandshaker.*;
import static org.junit.Assert.*;
public class WebSocketServerCompressionHandlerTest { public class WebSocketServerCompressionHandlerTest {
@ -45,12 +45,12 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name()); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertTrue(exts.get(0).parameters().isEmpty()); assertTrue(exts.get(0).parameters().isEmpty());
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -66,12 +66,12 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name()); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertEquals("10", exts.get(0).parameters().get(CLIENT_MAX_WINDOW)); assertEquals("10", exts.get(0).parameters().get(CLIENT_MAX_WINDOW));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -87,12 +87,12 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name()); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertTrue(exts.get(0).parameters().isEmpty()); assertTrue(exts.get(0).parameters().isEmpty());
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -108,12 +108,12 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name()); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertEquals("10", exts.get(0).parameters().get(SERVER_MAX_WINDOW)); assertEquals("10", exts.get(0).parameters().get(SERVER_MAX_WINDOW));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -129,9 +129,9 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
Assert.assertFalse(res2.headers().contains(Names.SEC_WEBSOCKET_EXTENSIONS)); assertFalse(res2.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) == null); assertNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) == null); assertNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -146,9 +146,9 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
Assert.assertFalse(res2.headers().contains(Names.SEC_WEBSOCKET_EXTENSIONS)); assertFalse(res2.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) == null); assertNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) == null); assertNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -163,12 +163,12 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name()); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertTrue(exts.get(0).parameters().isEmpty()); assertTrue(exts.get(0).parameters().isEmpty());
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
@Test @Test
@ -185,12 +185,12 @@ public class WebSocketServerCompressionHandlerTest {
HttpResponse res2 = ch.readOutbound(); HttpResponse res2 = ch.readOutbound();
List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions( List<WebSocketExtensionData> exts = WebSocketExtensionUtil.extractExtensions(
res2.headers().getAndConvert(Names.SEC_WEBSOCKET_EXTENSIONS)); res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
Assert.assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name()); assertEquals(PERMESSAGE_DEFLATE_EXTENSION, exts.get(0).name());
Assert.assertTrue(exts.get(0).parameters().isEmpty()); assertTrue(exts.get(0).parameters().isEmpty());
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateDecoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateDecoder.class));
Assert.assertTrue(ch.pipeline().get(PerMessageDeflateEncoder.class) != null); assertNotNull(ch.pipeline().get(PerMessageDeflateEncoder.class));
} }
} }

View File

@ -14,13 +14,6 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_ENCODING;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Values.DEFLATE;
import static io.netty.handler.codec.http.HttpHeaders.Values.GZIP;
import static io.netty.handler.codec.http.HttpHeaders.Values.IDENTITY;
import static io.netty.handler.codec.http.HttpHeaders.Values.XDEFLATE;
import static io.netty.handler.codec.http.HttpHeaders.Values.XGZIP;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
@ -29,6 +22,8 @@ import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.compression.ZlibCodecFactory; import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
/** /**
* A HTTP2 frame listener that will decompress data frames according to the {@code content-encoding} header for each * A HTTP2 frame listener that will decompress data frames according to the {@code content-encoding} header for each
@ -88,9 +83,9 @@ public class DelegatingDecompressorFrameListener extends Http2FrameListenerDecor
if (nextBuf == null) { if (nextBuf == null) {
listener.onDataRead(ctx, streamId, buf, padding, endOfStream); listener.onDataRead(ctx, streamId, buf, padding, endOfStream);
break; break;
} else {
listener.onDataRead(ctx, streamId, buf, padding, false);
} }
listener.onDataRead(ctx, streamId, buf, padding, false);
buf = nextBuf; buf = nextBuf;
} }
} }
@ -125,10 +120,12 @@ public class DelegatingDecompressorFrameListener extends Http2FrameListenerDecor
* @throws Http2Exception If the specified encoding is not not supported and warrants an exception * @throws Http2Exception If the specified encoding is not not supported and warrants an exception
*/ */
protected EmbeddedChannel newContentDecompressor(AsciiString contentEncoding) throws Http2Exception { protected EmbeddedChannel newContentDecompressor(AsciiString contentEncoding) throws Http2Exception {
if (GZIP.equalsIgnoreCase(contentEncoding) || XGZIP.equalsIgnoreCase(contentEncoding)) { if (HttpHeaderValues.GZIP.equalsIgnoreCase(contentEncoding) ||
HttpHeaderValues.X_GZIP.equalsIgnoreCase(contentEncoding)) {
return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
} }
if (DEFLATE.equalsIgnoreCase(contentEncoding) || XDEFLATE.equalsIgnoreCase(contentEncoding)) { if (HttpHeaderValues.DEFLATE.equalsIgnoreCase(contentEncoding) ||
HttpHeaderValues.X_DEFLATE.equalsIgnoreCase(contentEncoding)) {
final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE; final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE;
// To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly. // To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.
return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(wrapper)); return new EmbeddedChannel(ZlibCodecFactory.newZlibDecoder(wrapper));
@ -147,7 +144,7 @@ public class DelegatingDecompressorFrameListener extends Http2FrameListenerDecor
*/ */
protected AsciiString getTargetContentEncoding(@SuppressWarnings("UnusedParameters") AsciiString contentEncoding) protected AsciiString getTargetContentEncoding(@SuppressWarnings("UnusedParameters") AsciiString contentEncoding)
throws Http2Exception { throws Http2Exception {
return IDENTITY; return HttpHeaderValues.IDENTITY;
} }
/** /**
@ -169,9 +166,9 @@ public class DelegatingDecompressorFrameListener extends Http2FrameListenerDecor
if (decompressor == null) { if (decompressor == null) {
if (!endOfStream) { if (!endOfStream) {
// Determine the content encoding. // Determine the content encoding.
AsciiString contentEncoding = headers.get(CONTENT_ENCODING); AsciiString contentEncoding = headers.get(HttpHeaderNames.CONTENT_ENCODING);
if (contentEncoding == null) { if (contentEncoding == null) {
contentEncoding = IDENTITY; contentEncoding = HttpHeaderValues.IDENTITY;
} }
decompressor = newContentDecompressor(contentEncoding); decompressor = newContentDecompressor(contentEncoding);
if (decompressor != null) { if (decompressor != null) {
@ -179,10 +176,10 @@ public class DelegatingDecompressorFrameListener extends Http2FrameListenerDecor
// Decode the content and remove or replace the existing headers // Decode the content and remove or replace the existing headers
// so that the message looks like a decoded message. // so that the message looks like a decoded message.
AsciiString targetContentEncoding = getTargetContentEncoding(contentEncoding); AsciiString targetContentEncoding = getTargetContentEncoding(contentEncoding);
if (IDENTITY.equalsIgnoreCase(targetContentEncoding)) { if (HttpHeaderValues.IDENTITY.equalsIgnoreCase(targetContentEncoding)) {
headers.remove(CONTENT_ENCODING); headers.remove(HttpHeaderNames.CONTENT_ENCODING);
} else { } else {
headers.set(CONTENT_ENCODING, targetContentEncoding); headers.set(HttpHeaderNames.CONTENT_ENCODING, targetContentEncoding);
} }
} }
} }
@ -193,7 +190,7 @@ public class DelegatingDecompressorFrameListener extends Http2FrameListenerDecor
// The content length will be for the compressed data. Since we will decompress the data // The content length will be for the compressed data. Since we will decompress the data
// this content-length will not be correct. Instead of queuing messages or delaying sending // this content-length will not be correct. Instead of queuing messages or delaying sending
// header frames...just remove the content-length header // header frames...just remove the content-length header
headers.remove(CONTENT_LENGTH); headers.remove(HttpHeaderNames.CONTENT_LENGTH);
} }
} }

View File

@ -22,6 +22,7 @@ import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
@ -49,11 +50,11 @@ public final class HttpUtil {
private static final Set<CharSequence> HTTP_TO_HTTP2_HEADER_BLACKLIST = new HashSet<CharSequence>() { private static final Set<CharSequence> HTTP_TO_HTTP2_HEADER_BLACKLIST = new HashSet<CharSequence>() {
private static final long serialVersionUID = -5678614530214167043L; private static final long serialVersionUID = -5678614530214167043L;
{ {
add(HttpHeaders.Names.CONNECTION); add(HttpHeaderNames.CONNECTION);
add(HttpHeaders.Names.KEEP_ALIVE); add(HttpHeaderNames.KEEP_ALIVE);
add(HttpHeaders.Names.PROXY_CONNECTION); add(HttpHeaderNames.PROXY_CONNECTION);
add(HttpHeaders.Names.TRANSFER_ENCODING); add(HttpHeaderNames.TRANSFER_ENCODING);
add(HttpHeaders.Names.HOST); add(HttpHeaderNames.HOST);
add(ExtensionHeaderNames.STREAM_ID.text()); add(ExtensionHeaderNames.STREAM_ID.text());
add(ExtensionHeaderNames.AUTHORITY.text()); add(ExtensionHeaderNames.AUTHORITY.text());
add(ExtensionHeaderNames.SCHEME.text()); add(ExtensionHeaderNames.SCHEME.text());
@ -139,7 +140,7 @@ public final class HttpUtil {
private final AsciiString text; private final AsciiString text;
private ExtensionHeaderNames(String text) { ExtensionHeaderNames(String text) {
this.text = new AsciiString(text); this.text = new AsciiString(text);
} }
@ -156,7 +157,7 @@ public final class HttpUtil {
* @throws Http2Exception If there is a problem translating from HTTP/2 to HTTP/1.x * @throws Http2Exception If there is a problem translating from HTTP/2 to HTTP/1.x
*/ */
public static HttpResponseStatus parseStatus(AsciiString status) throws Http2Exception { public static HttpResponseStatus parseStatus(AsciiString status) throws Http2Exception {
HttpResponseStatus result = null; HttpResponseStatus result;
try { try {
result = HttpResponseStatus.parseLine(status); result = HttpResponseStatus.parseLine(status);
if (result == HttpResponseStatus.SWITCHING_PROTOCOLS) { if (result == HttpResponseStatus.SWITCHING_PROTOCOLS) {
@ -164,7 +165,7 @@ public final class HttpUtil {
} }
} catch (Http2Exception e) { } catch (Http2Exception e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception ignored) {
throw Http2Exception.protocolError( throw Http2Exception.protocolError(
"Unrecognized HTTP status code '%s' encountered in translation to HTTP/1.x", status); "Unrecognized HTTP status code '%s' encountered in translation to HTTP/1.x", status);
} }
@ -181,7 +182,7 @@ public final class HttpUtil {
* <li>{@code false} not to validate HTTP headers in the http-codec</li> * <li>{@code false} not to validate HTTP headers in the http-codec</li>
* </ul> * </ul>
* @return A new response object which represents headers/data * @return A new response object which represents headers/data
* @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, Map)} * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
*/ */
public static FullHttpResponse toHttpResponse(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders) public static FullHttpResponse toHttpResponse(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders)
throws Http2Exception { throws Http2Exception {
@ -203,7 +204,7 @@ public final class HttpUtil {
* <li>{@code false} not to validate HTTP headers in the http-codec</li> * <li>{@code false} not to validate HTTP headers in the http-codec</li>
* </ul> * </ul>
* @return A new request object which represents headers/data * @return A new request object which represents headers/data
* @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, Map)} * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
*/ */
public static FullHttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders) public static FullHttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders)
throws Http2Exception { throws Http2Exception {
@ -237,8 +238,8 @@ public final class HttpUtil {
PlatformDependent.throwException(ex); PlatformDependent.throwException(ex);
} }
headers.remove(HttpHeaders.Names.TRANSFER_ENCODING); headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
headers.remove(HttpHeaders.Names.TRAILER); headers.remove(HttpHeaderNames.TRAILER);
if (!addToTrailer) { if (!addToTrailer) {
headers.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId); headers.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId);
HttpHeaderUtil.setKeepAlive(destinationMessage, true); HttpHeaderUtil.setKeepAlive(destinationMessage, true);
@ -256,7 +257,7 @@ public final class HttpUtil {
out.path(new AsciiString(request.uri())); out.path(new AsciiString(request.uri()));
out.method(new AsciiString(request.method().toString())); out.method(new AsciiString(request.method().toString()));
String value = inHeaders.getAndConvert(HttpHeaders.Names.HOST); String value = inHeaders.getAndConvert(HttpHeaderNames.HOST);
if (value != null) { if (value != null) {
URI hostUri = URI.create(value); URI hostUri = URI.create(value);
// The authority MUST NOT include the deprecated "userinfo" subcomponent // The authority MUST NOT include the deprecated "userinfo" subcomponent
@ -336,7 +337,7 @@ public final class HttpUtil {
* @param request if {@code true}, translates headers using the request translation map. Otherwise uses the * @param request if {@code true}, translates headers using the request translation map. Otherwise uses the
* response translation map. * response translation map.
*/ */
public Http2ToHttpHeaderTranslator(HttpHeaders output, boolean request) { Http2ToHttpHeaderTranslator(HttpHeaders output, boolean request) {
this.output = output; this.output = output;
translations = request ? REQUEST_HEADER_TRANSLATIONS : RESPONSE_HEADER_TRANSLATIONS; translations = request ? REQUEST_HEADER_TRANSLATIONS : RESPONSE_HEADER_TRANSLATIONS;
} }

View File

@ -14,18 +14,19 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.collection.IntObjectHashMap; import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap; import io.netty.util.collection.IntObjectMap;
import static io.netty.util.internal.ObjectUtil.*;
/** /**
* This adapter provides just header/data events from the HTTP message flow defined * This adapter provides just header/data events from the HTTP message flow defined
* here <a href="http://tools.ietf.org/html/draft-ietf-httpbis-http2-14#section-8.1.">HTTP/2 Spec Message Flow</a> * here <a href="http://tools.ietf.org/html/draft-ietf-httpbis-http2-14#section-8.1.">HTTP/2 Spec Message Flow</a>
@ -36,8 +37,9 @@ public class InboundHttp2ToHttpAdapter extends Http2EventAdapter {
public boolean mustSendImmediately(FullHttpMessage msg) { public boolean mustSendImmediately(FullHttpMessage msg) {
if (msg instanceof FullHttpResponse) { if (msg instanceof FullHttpResponse) {
return ((FullHttpResponse) msg).status().isInformational(); return ((FullHttpResponse) msg).status().isInformational();
} else if (msg instanceof FullHttpRequest) { }
return ((FullHttpRequest) msg).headers().contains(HttpHeaders.Names.EXPECT); if (msg instanceof FullHttpRequest) {
return msg.headers().contains(HttpHeaderNames.EXPECT);
} }
return false; return false;
} }
@ -46,7 +48,7 @@ public class InboundHttp2ToHttpAdapter extends Http2EventAdapter {
public FullHttpMessage copyIfNeeded(FullHttpMessage msg) { public FullHttpMessage copyIfNeeded(FullHttpMessage msg) {
if (msg instanceof FullHttpRequest) { if (msg instanceof FullHttpRequest) {
FullHttpRequest copy = ((FullHttpRequest) msg).copy(null); FullHttpRequest copy = ((FullHttpRequest) msg).copy(null);
copy.headers().remove(HttpHeaders.Names.EXPECT); copy.headers().remove(HttpHeaderNames.EXPECT);
return copy; return copy;
} }
return null; return null;
@ -172,7 +174,6 @@ public class InboundHttp2ToHttpAdapter extends Http2EventAdapter {
* <li>{@code true} to validate HTTP headers in the http-codec</li> * <li>{@code true} to validate HTTP headers in the http-codec</li>
* <li>{@code false} not to validate HTTP headers in the http-codec</li> * <li>{@code false} not to validate HTTP headers in the http-codec</li>
* </ul> * </ul>
* @return
* @throws Http2Exception * @throws Http2Exception
*/ */
protected FullHttpMessage newMessage(int streamId, Http2Headers headers, boolean validateHttpHeaders) protected FullHttpMessage newMessage(int streamId, Http2Headers headers, boolean validateHttpHeaders)
@ -334,7 +335,7 @@ public class InboundHttp2ToHttpAdapter extends Http2EventAdapter {
* with a 'Expect: 100-continue' header. The message will be sent immediately, * with a 'Expect: 100-continue' header. The message will be sent immediately,
* and the data will be queued and sent at the end of the stream. * and the data will be queued and sent at the end of the stream.
* *
* @param msg The message which has just been sent due to {@link #mustSendImmediatley} * @param msg The message which has just been sent due to {@link #mustSendImmediately(FullHttpMessage)}
* @return A modified copy of the {@code msg} or {@code null} if a copy is not needed. * @return A modified copy of the {@code msg} or {@code null} if a copy is not needed.
*/ */
FullHttpMessage copyIfNeeded(FullHttpMessage msg); FullHttpMessage copyIfNeeded(FullHttpMessage msg);

View File

@ -14,18 +14,6 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_ENCODING;
import static io.netty.handler.codec.http.HttpHeaders.Values.DEFLATE;
import static io.netty.handler.codec.http.HttpHeaders.Values.GZIP;
import static io.netty.handler.codec.http2.Http2TestUtil.as;
import static io.netty.handler.codec.http2.Http2TestUtil.runInChannel;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@ -45,15 +33,10 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.AsciiString; import io.netty.handler.codec.AsciiString;
import io.netty.handler.codec.compression.ZlibCodecFactory; import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.util.NetUtil; import io.netty.util.NetUtil;
import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -61,6 +44,15 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static io.netty.handler.codec.http2.Http2TestUtil.*;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** /**
* Test for data decompression in the HTTP/2 codec. * Test for data decompression in the HTTP/2 codec.
*/ */
@ -84,8 +76,8 @@ public class DataCompressionHttp2Test {
private Channel clientChannel; private Channel clientChannel;
private volatile CountDownLatch serverLatch; private volatile CountDownLatch serverLatch;
private volatile CountDownLatch clientLatch; private volatile CountDownLatch clientLatch;
private Http2TestUtil.FrameAdapter serverAdapter; private FrameAdapter serverAdapter;
private Http2TestUtil.FrameAdapter clientAdapter; private FrameAdapter clientAdapter;
private Http2Connection serverConnection; private Http2Connection serverConnection;
@Before @Before
@ -102,9 +94,9 @@ public class DataCompressionHttp2Test {
dataCapture = null; dataCapture = null;
} }
serverChannel.close().sync(); serverChannel.close().sync();
Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, MILLISECONDS);
Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, MILLISECONDS);
Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, MILLISECONDS);
serverGroup.sync(); serverGroup.sync();
serverChildGroup.sync(); serverChildGroup.sync();
clientGroup.sync(); clientGroup.sync();
@ -117,10 +109,11 @@ public class DataCompressionHttp2Test {
public void justHeadersNoData() throws Exception { public void justHeadersNoData() throws Exception {
bootstrapEnv(2, 1); bootstrapEnv(2, 1);
final Http2Headers headers = final Http2Headers headers =
new DefaultHttp2Headers().method(GET).path(PATH).set(CONTENT_ENCODING, GZIP); new DefaultHttp2Headers().method(GET).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
// Required because the decompressor intercepts the onXXXRead events before // Required because the decompressor intercepts the onXXXRead events before
// our {@link Http2TestUtil$FrameAdapter} does. // our {@link Http2TestUtil$FrameAdapter} does.
Http2TestUtil.FrameAdapter.getOrCreateStream(serverConnection, 3, false); FrameAdapter.getOrCreateStream(serverConnection, 3, false);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -141,10 +134,11 @@ public class DataCompressionHttp2Test {
try { try {
final ByteBuf encodedData = encodeData(data, encoder); final ByteBuf encodedData = encodeData(data, encoder);
final Http2Headers headers = final Http2Headers headers =
new DefaultHttp2Headers().method(POST).path(PATH).set(CONTENT_ENCODING.toLowerCase(), GZIP); new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
// Required because the decompressor intercepts the onXXXRead events before // Required because the decompressor intercepts the onXXXRead events before
// our {@link Http2TestUtil$FrameAdapter} does. // our {@link Http2TestUtil$FrameAdapter} does.
Http2TestUtil.FrameAdapter.getOrCreateStream(serverConnection, 3, false); FrameAdapter.getOrCreateStream(serverConnection, 3, false);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -175,10 +169,11 @@ public class DataCompressionHttp2Test {
try { try {
final ByteBuf encodedData = encodeData(data, encoder); final ByteBuf encodedData = encodeData(data, encoder);
final Http2Headers headers = final Http2Headers headers =
new DefaultHttp2Headers().method(POST).path(PATH).set(CONTENT_ENCODING.toLowerCase(), GZIP); new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
// Required because the decompressor intercepts the onXXXRead events before // Required because the decompressor intercepts the onXXXRead events before
// our {@link Http2TestUtil$FrameAdapter} does. // our {@link Http2TestUtil$FrameAdapter} does.
Http2TestUtil.FrameAdapter.getOrCreateStream(serverConnection, 3, false); FrameAdapter.getOrCreateStream(serverConnection, 3, false);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -212,10 +207,11 @@ public class DataCompressionHttp2Test {
final ByteBuf encodedData1 = encodeData(data1, encoder); final ByteBuf encodedData1 = encodeData(data1, encoder);
final ByteBuf encodedData2 = encodeData(data2, encoder); final ByteBuf encodedData2 = encodeData(data2, encoder);
final Http2Headers headers = final Http2Headers headers =
new DefaultHttp2Headers().method(POST).path(PATH).set(CONTENT_ENCODING.toLowerCase(), GZIP); new DefaultHttp2Headers().method(POST).path(PATH)
.set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
// Required because the decompressor intercepts the onXXXRead events before // Required because the decompressor intercepts the onXXXRead events before
// our {@link Http2TestUtil$FrameAdapter} does. // our {@link Http2TestUtil$FrameAdapter} does.
Http2TestUtil.FrameAdapter.getOrCreateStream(serverConnection, 3, false); FrameAdapter.getOrCreateStream(serverConnection, 3, false);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -258,7 +254,7 @@ public class DataCompressionHttp2Test {
final ByteBuf encodedData = encodeData(data, encoder); final ByteBuf encodedData = encodeData(data, encoder);
final Http2Headers headers = final Http2Headers headers =
new DefaultHttp2Headers().method(POST).path(PATH) new DefaultHttp2Headers().method(POST).path(PATH)
.set(CONTENT_ENCODING.toLowerCase(), DEFLATE); .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.DEFLATE);
final Http2Settings settings = new Http2Settings(); final Http2Settings settings = new Http2Settings();
// Assume the compression operation will reduce the size by at least 10 bytes // Assume the compression operation will reduce the size by at least 10 bytes
settings.initialWindowSize(BUFFER_SIZE - 10); settings.initialWindowSize(BUFFER_SIZE - 10);
@ -273,7 +269,7 @@ public class DataCompressionHttp2Test {
// Required because the decompressor intercepts the onXXXRead events before // Required because the decompressor intercepts the onXXXRead events before
// our {@link Http2TestUtil$FrameAdapter} does. // our {@link Http2TestUtil$FrameAdapter} does.
Http2TestUtil.FrameAdapter.getOrCreateStream(serverConnection, 3, false); FrameAdapter.getOrCreateStream(serverConnection, 3, false);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -336,18 +332,20 @@ public class DataCompressionHttp2Test {
frameWriter = new DefaultHttp2FrameWriter(); frameWriter = new DefaultHttp2FrameWriter();
serverConnection = new DefaultHttp2Connection(true); serverConnection = new DefaultHttp2Connection(true);
final CountDownLatch latch = new CountDownLatch(1);
sb.group(new NioEventLoopGroup(), new NioEventLoopGroup()); sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
sb.channel(NioServerSocketChannel.class); sb.channel(NioServerSocketChannel.class);
sb.childHandler(new ChannelInitializer<Channel>() { sb.childHandler(new ChannelInitializer<Channel>() {
@Override @Override
protected void initChannel(Channel ch) throws Exception { protected void initChannel(Channel ch) throws Exception {
ChannelPipeline p = ch.pipeline(); ChannelPipeline p = ch.pipeline();
serverAdapter = new Http2TestUtil.FrameAdapter(serverConnection, serverAdapter = new FrameAdapter(serverConnection,
new DelegatingDecompressorFrameListener(serverConnection, serverListener), new DelegatingDecompressorFrameListener(serverConnection, serverListener),
serverLatch); serverLatch);
p.addLast("reader", serverAdapter); p.addLast("reader", serverAdapter);
p.addLast(Http2CodecUtil.ignoreSettingsHandler()); p.addLast(Http2CodecUtil.ignoreSettingsHandler());
serverConnectedChannel = ch; serverConnectedChannel = ch;
latch.countDown();
} }
}); });
@ -357,7 +355,7 @@ public class DataCompressionHttp2Test {
@Override @Override
protected void initChannel(Channel ch) throws Exception { protected void initChannel(Channel ch) throws Exception {
ChannelPipeline p = ch.pipeline(); ChannelPipeline p = ch.pipeline();
clientAdapter = new Http2TestUtil.FrameAdapter(clientListener, clientLatch); clientAdapter = new FrameAdapter(clientListener, clientLatch);
p.addLast("reader", clientAdapter); p.addLast("reader", clientAdapter);
p.addLast(Http2CodecUtil.ignoreSettingsHandler()); p.addLast(Http2CodecUtil.ignoreSettingsHandler());
} }
@ -369,6 +367,8 @@ public class DataCompressionHttp2Test {
ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port)); ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
assertTrue(ccf.awaitUninterruptibly().isSuccess()); assertTrue(ccf.awaitUninterruptibly().isSuccess());
clientChannel = ccf.channel(); clientChannel = ccf.channel();
assertTrue(latch.await(5, SECONDS));
} }
private void awaitClient() throws Exception { private void awaitClient() throws Exception {

View File

@ -15,19 +15,17 @@
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2TestUtil.as; import com.twitter.hpack.Encoder;
import static io.netty.handler.codec.http2.Http2TestUtil.randomBytes;
import static io.netty.util.CharsetUtil.UTF_8;
import static org.junit.Assert.assertEquals;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import java.io.ByteArrayOutputStream;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.twitter.hpack.Encoder; import java.io.ByteArrayOutputStream;
import static io.netty.handler.codec.http2.Http2TestUtil.*;
import static io.netty.util.CharsetUtil.*;
import static org.junit.Assert.*;
/** /**
* Tests for {@link DefaultHttp2HeadersDecoder}. * Tests for {@link DefaultHttp2HeadersDecoder}.
@ -54,11 +52,11 @@ public class DefaultHttp2HeadersDecoderTest {
} }
} }
private byte[] b(String string) { private static byte[] b(String string) {
return string.getBytes(UTF_8); return string.getBytes(UTF_8);
} }
private ByteBuf encode(byte[]... entries) throws Exception { private static ByteBuf encode(byte[]... entries) throws Exception {
Encoder encoder = new Encoder(); Encoder encoder = new Encoder();
ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
for (int ix = 0; ix < entries.length;) { for (int ix = 0; ix < entries.length;) {

View File

@ -14,23 +14,6 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty.handler.codec.http2.Http2CodecUtil.ignoreSettingsHandler;
import static io.netty.handler.codec.http2.Http2TestUtil.as;
import static io.netty.util.CharsetUtil.UTF_8;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@ -46,18 +29,11 @@ import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.NetUtil; import io.netty.util.NetUtil;
import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -66,6 +42,21 @@ import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpVersion.*;
import static io.netty.handler.codec.http2.Http2CodecUtil.*;
import static io.netty.handler.codec.http2.Http2TestUtil.*;
import static io.netty.util.CharsetUtil.*;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** /**
* Testing the {@link Http2ToHttpConnectionHandler} for {@link FullHttpRequest} objects into HTTP/2 frames * Testing the {@link Http2ToHttpConnectionHandler} for {@link FullHttpRequest} objects into HTTP/2 frames
*/ */
@ -82,7 +73,7 @@ public class DefaultHttp2ToHttpConnectionHandlerTest {
private Channel serverChannel; private Channel serverChannel;
private Channel clientChannel; private Channel clientChannel;
private volatile CountDownLatch requestLatch; private volatile CountDownLatch requestLatch;
private Http2TestUtil.FrameCountDown serverFrameCountDown; private FrameCountDown serverFrameCountDown;
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
@ -92,9 +83,9 @@ public class DefaultHttp2ToHttpConnectionHandlerTest {
@After @After
public void teardown() throws Exception { public void teardown() throws Exception {
serverChannel.close().sync(); serverChannel.close().sync();
Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, MILLISECONDS);
Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, MILLISECONDS);
Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, MILLISECONDS);
serverGroup.sync(); serverGroup.sync();
serverChildGroup.sync(); serverChildGroup.sync();
clientGroup.sync(); clientGroup.sync();
@ -107,7 +98,7 @@ public class DefaultHttp2ToHttpConnectionHandlerTest {
try { try {
final HttpHeaders httpHeaders = request.headers(); final HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders.set(HttpHeaders.Names.HOST, httpHeaders.set(HttpHeaderNames.HOST,
"http://my-user_name@www.example.org:5555/example"); "http://my-user_name@www.example.org:5555/example");
httpHeaders.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "www.example.org:5555"); httpHeaders.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "www.example.org:5555");
httpHeaders.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "http"); httpHeaders.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "http");
@ -153,7 +144,7 @@ public class DefaultHttp2ToHttpConnectionHandlerTest {
try { try {
final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, "/example", data.retain()); final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, "/example", data.retain());
final HttpHeaders httpHeaders = request.headers(); final HttpHeaders httpHeaders = request.headers();
httpHeaders.set(HttpHeaders.Names.HOST, "http://your_user-name123@www.example.org:5555/example"); httpHeaders.set(HttpHeaderNames.HOST, "http://your_user-name123@www.example.org:5555/example");
httpHeaders.add("foo", "goo"); httpHeaders.add("foo", "goo");
httpHeaders.add("foo", "goo2"); httpHeaders.add("foo", "goo2");
httpHeaders.add("foo2", "goo2"); httpHeaders.add("foo2", "goo2");
@ -193,7 +184,7 @@ public class DefaultHttp2ToHttpConnectionHandlerTest {
@Override @Override
protected void initChannel(Channel ch) throws Exception { protected void initChannel(Channel ch) throws Exception {
ChannelPipeline p = ch.pipeline(); ChannelPipeline p = ch.pipeline();
serverFrameCountDown = new Http2TestUtil.FrameCountDown(serverListener, requestLatch); serverFrameCountDown = new FrameCountDown(serverListener, requestLatch);
p.addLast(new Http2ToHttpConnectionHandler(true, serverFrameCountDown)); p.addLast(new Http2ToHttpConnectionHandler(true, serverFrameCountDown));
p.addLast(ignoreSettingsHandler()); p.addLast(ignoreSettingsHandler());
} }

View File

@ -14,14 +14,6 @@
*/ */
package io.netty.handler.codec.http2; package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2TestUtil.as;
import static io.netty.handler.codec.http2.Http2TestUtil.runInChannel;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
@ -40,20 +32,15 @@ import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable;
import io.netty.util.NetUtil; import io.netty.util.NetUtil;
import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -61,6 +48,15 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static io.netty.handler.codec.http2.Http2TestUtil.*;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/** /**
* Testing the {@link InboundHttp2ToHttpPriorityAdapter} and base class {@link InboundHttp2ToHttpAdapter} for HTTP/2 * Testing the {@link InboundHttp2ToHttpPriorityAdapter} and base class {@link InboundHttp2ToHttpAdapter} for HTTP/2
* frames into {@link HttpObject}s * frames into {@link HttpObject}s
@ -148,9 +144,9 @@ public class InboundHttp2ToHttpAdapterTest {
cleanupCapturedRequests(); cleanupCapturedRequests();
cleanupCapturedResponses(); cleanupCapturedResponses();
serverChannel.close().sync(); serverChannel.close().sync();
Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, MILLISECONDS);
Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, MILLISECONDS);
Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, TimeUnit.MILLISECONDS); Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, MILLISECONDS);
serverGroup.sync(); serverGroup.sync();
serverChildGroup.sync(); serverChildGroup.sync();
clientGroup.sync(); clientGroup.sync();
@ -170,7 +166,7 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "https"); httpHeaders.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "https");
httpHeaders.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "example.org"); httpHeaders.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "example.org");
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
final Http2Headers http2Headers = final Http2Headers http2Headers =
new DefaultHttp2Headers().method(as("GET")).scheme(as("https")) new DefaultHttp2Headers().method(as("GET")).scheme(as("https"))
.authority(as("example.org")) .authority(as("example.org"))
@ -201,7 +197,7 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("GET")) final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("GET"))
.path(as("/some/path/resource2")); .path(as("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@ -231,7 +227,7 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("GET")) final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("GET"))
.path(as("/some/path/resource2")); .path(as("/some/path/resource2"));
final int midPoint = text.length() / 2; final int midPoint = text.length() / 2;
@ -265,7 +261,7 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("GET")) final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("GET"))
.path(as("/some/path/resource2")); .path(as("/some/path/resource2"));
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@ -299,7 +295,7 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
HttpHeaders trailingHeaders = request.trailingHeaders(); HttpHeaders trailingHeaders = request.trailingHeaders();
trailingHeaders.set("FoO", "goo"); trailingHeaders.set("FoO", "goo");
trailingHeaders.set("foO2", "goo2"); trailingHeaders.set("foO2", "goo2");
@ -339,7 +335,7 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
HttpHeaders trailingHeaders = request.trailingHeaders(); HttpHeaders trailingHeaders = request.trailingHeaders();
trailingHeaders.set("Foo", "goo"); trailingHeaders.set("Foo", "goo");
trailingHeaders.set("fOo2", "goo2"); trailingHeaders.set("fOo2", "goo2");
@ -384,12 +380,12 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
HttpHeaders httpHeaders2 = request2.headers(); HttpHeaders httpHeaders2 = request2.headers();
httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3); httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3);
httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), 123); httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), 123);
httpHeaders2.setInt(HttpHeaders.Names.CONTENT_LENGTH, text2.length()); httpHeaders2.setInt(HttpHeaderNames.CONTENT_LENGTH, text2.length());
final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("PUT")) final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("PUT"))
.path(as("/some/path/resource")); .path(as("/some/path/resource"));
final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(as("PUT")) final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(as("PUT"))
@ -433,10 +429,10 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
HttpHeaders httpHeaders2 = request2.headers(); HttpHeaders httpHeaders2 = request2.headers();
httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders2.setInt(HttpHeaders.Names.CONTENT_LENGTH, text2.length()); httpHeaders2.setInt(HttpHeaderNames.CONTENT_LENGTH, text2.length());
final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("PUT")) final Http2Headers http2Headers = new DefaultHttp2Headers().method(as("PUT"))
.path(as("/some/path/resource")); .path(as("/some/path/resource"));
final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(as("PUT")) final Http2Headers http2Headers2 = new DefaultHttp2Headers().method(as("PUT"))
@ -445,7 +441,7 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders3.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders3.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders3.setInt(HttpUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3); httpHeaders3.setInt(HttpUtil.ExtensionHeaderNames.STREAM_DEPENDENCY_ID.text(), 3);
httpHeaders3.setInt(HttpUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), 222); httpHeaders3.setInt(HttpUtil.ExtensionHeaderNames.STREAM_WEIGHT.text(), 222);
httpHeaders3.setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); httpHeaders3.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -487,17 +483,17 @@ public class InboundHttp2ToHttpAdapterTest {
try { try {
HttpHeaders httpHeaders = response.headers(); HttpHeaders httpHeaders = response.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
HttpHeaders httpHeaders2 = response2.headers(); HttpHeaders httpHeaders2 = response2.headers();
httpHeaders2.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "https"); httpHeaders2.set(HttpUtil.ExtensionHeaderNames.SCHEME.text(), "https");
httpHeaders2.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "example.org"); httpHeaders2.set(HttpUtil.ExtensionHeaderNames.AUTHORITY.text(), "example.org");
httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5); httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_PROMISE_ID.text(), 3); httpHeaders2.setInt(HttpUtil.ExtensionHeaderNames.STREAM_PROMISE_ID.text(), 3);
httpHeaders2.setInt(HttpHeaders.Names.CONTENT_LENGTH, text2.length()); httpHeaders2.setInt(HttpHeaderNames.CONTENT_LENGTH, text2.length());
httpHeaders = request.headers(); httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
final Http2Headers http2Headers3 = new DefaultHttp2Headers().method(as("GET")) final Http2Headers http2Headers3 = new DefaultHttp2Headers().method(as("GET"))
.path(as("/push/test")); .path(as("/push/test"));
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@ -546,14 +542,13 @@ public class InboundHttp2ToHttpAdapterTest {
true); true);
HttpHeaders httpHeaders = request.headers(); HttpHeaders httpHeaders = request.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.set(HttpHeaders.Names.EXPECT, HttpHeaders.Values.CONTINUE); httpHeaders.set(HttpHeaderNames.EXPECT, HttpHeaderValues.CONTINUE);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
final Http2Headers http2Headers = final Http2Headers http2Headers =
new DefaultHttp2Headers() new DefaultHttp2Headers()
.method(as("PUT")) .method(as("PUT"))
.path(as("/info/test")) .path(as("/info/test"))
.set(as(HttpHeaders.Names.EXPECT.toString()), .set(as(HttpHeaderNames.EXPECT.toString()), as(HttpHeaderValues.CONTINUE.toString()));
as(HttpHeaders.Values.CONTINUE.toString()));
final FullHttpMessage response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE); final FullHttpMessage response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
final String text = "a big payload"; final String text = "a big payload";
final ByteBuf payload = Unpooled.copiedBuffer(text.getBytes()); final ByteBuf payload = Unpooled.copiedBuffer(text.getBytes());
@ -578,7 +573,7 @@ public class InboundHttp2ToHttpAdapterTest {
httpHeaders = response.headers(); httpHeaders = response.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
final Http2Headers http2HeadersResponse = new DefaultHttp2Headers().status(as("100")); final Http2Headers http2HeadersResponse = new DefaultHttp2Headers().status(as("100"));
runInChannel(serverConnectedChannel, new Http2Runnable() { runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override @Override
@ -597,8 +592,8 @@ public class InboundHttp2ToHttpAdapterTest {
setServerLatch(1); setServerLatch(1);
httpHeaders = request2.headers(); httpHeaders = request2.headers();
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, text.length()); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, text.length());
httpHeaders.remove(HttpHeaders.Names.EXPECT); httpHeaders.remove(HttpHeaderNames.EXPECT);
runInChannel(clientChannel, new Http2Runnable() { runInChannel(clientChannel, new Http2Runnable() {
@Override @Override
public void run() { public void run() {
@ -615,7 +610,7 @@ public class InboundHttp2ToHttpAdapterTest {
setClientLatch(1); setClientLatch(1);
httpHeaders = response2.headers(); httpHeaders = response2.headers();
httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3); httpHeaders.setInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
httpHeaders.setInt(HttpHeaders.Names.CONTENT_LENGTH, 0); httpHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
final Http2Headers http2HeadersResponse2 = new DefaultHttp2Headers().status(as("200")); final Http2Headers http2HeadersResponse2 = new DefaultHttp2Headers().status(as("200"));
runInChannel(serverConnectedChannel, new Http2Runnable() { runInChannel(serverConnectedChannel, new Http2Runnable() {
@Override @Override
@ -697,11 +692,11 @@ public class InboundHttp2ToHttpAdapterTest {
void messageReceived(HttpObject obj); void messageReceived(HttpObject obj);
} }
private final class HttpResponseDelegator extends SimpleChannelInboundHandler<HttpObject> { private static final class HttpResponseDelegator extends SimpleChannelInboundHandler<HttpObject> {
private final HttpResponseListener listener; private final HttpResponseListener listener;
private volatile CountDownLatch latch; private volatile CountDownLatch latch;
public HttpResponseDelegator(HttpResponseListener listener, CountDownLatch latch) { HttpResponseDelegator(HttpResponseListener listener, CountDownLatch latch) {
super(false); super(false);
this.listener = listener; this.listener = listener;
this.latch = latch; this.latch = latch;
@ -709,8 +704,8 @@ public class InboundHttp2ToHttpAdapterTest {
@Override @Override
protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception { protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
this.listener.messageReceived(msg); listener.messageReceived(msg);
this.latch.countDown(); latch.countDown();
} }
public void latch(CountDownLatch latch) { public void latch(CountDownLatch latch) {
@ -718,7 +713,7 @@ public class InboundHttp2ToHttpAdapterTest {
} }
} }
private final class HttpAdapterFrameAdapter extends Http2TestUtil.FrameAdapter { private static final class HttpAdapterFrameAdapter extends FrameAdapter {
HttpAdapterFrameAdapter(Http2Connection connection, Http2FrameListener listener, CountDownLatch latch) { HttpAdapterFrameAdapter(Http2Connection connection, Http2FrameListener listener, CountDownLatch latch) {
super(connection, listener, latch); super(connection, listener, latch);
} }

View File

@ -28,9 +28,9 @@ import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpChunkedInput; import io.netty.handler.codec.http.HttpChunkedInput;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.LastHttpContent;
@ -53,7 +53,7 @@ import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
@ -179,7 +179,7 @@ public class HttpStaticFileServerHandler extends SimpleChannelInboundHandler<Ful
setContentTypeHeader(response, file); setContentTypeHeader(response, file);
setDateAndCacheHeaders(response, file); setDateAndCacheHeaders(response, file);
if (HttpHeaderUtil.isKeepAlive(request)) { if (HttpHeaderUtil.isKeepAlive(request)) {
response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
} }
// Write the initial line and the header. // Write the initial line and the header.

View File

@ -22,10 +22,10 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders.Values; import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
@ -54,7 +54,7 @@ public class HttpHelloWorldServerHandler extends ChannelHandlerAdapter {
if (!keepAlive) { if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE); ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else { } else {
response.headers().set(CONNECTION, Values.KEEP_ALIVE); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.write(response); ctx.write(response);
} }
} }

View File

@ -23,7 +23,8 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.ClientCookieEncoder; import io.netty.handler.codec.http.ClientCookieEncoder;
import io.netty.handler.codec.http.DefaultCookie; import io.netty.handler.codec.http.DefaultCookie;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -81,13 +82,13 @@ public final class HttpSnoopClient {
// Prepare the HTTP request. // Prepare the HTTP request.
HttpRequest request = new DefaultFullHttpRequest( HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// Set some example cookies. // Set some example cookies.
request.headers().set( request.headers().set(
HttpHeaders.Names.COOKIE, HttpHeaderNames.COOKIE,
ClientCookieEncoder.encode( ClientCookieEncoder.encode(
new DefaultCookie("my-cookie", "foo"), new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar"))); new DefaultCookie("another-cookie", "bar")));

View File

@ -27,6 +27,7 @@ import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
@ -40,7 +41,7 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
@ -158,7 +159,7 @@ public class HttpSnoopServerHandler extends SimpleChannelInboundHandler<Object>
response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
// Add keep alive header as per: // Add keep alive header as per:
// - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
} }
// Encode the cookie. // Encode the cookie.

View File

@ -24,6 +24,8 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.ClientCookieEncoder; import io.netty.handler.codec.http.ClientCookieEncoder;
import io.netty.handler.codec.http.DefaultCookie; import io.netty.handler.codec.http.DefaultCookie;
import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
@ -162,21 +164,21 @@ public final class HttpUploadClient {
URI uriGet = new URI(encoder.toString()); URI uriGet = new URI(encoder.toString());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString()); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
HttpHeaders headers = request.headers(); HttpHeaders headers = request.headers();
headers.set(HttpHeaders.Names.HOST, host); headers.set(HttpHeaderNames.HOST, host);
headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + "," + HttpHeaders.Values.DEFLATE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP + "," + HttpHeaderValues.DEFLATE);
headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set(HttpHeaderNames.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr"); headers.set(HttpHeaderNames.ACCEPT_LANGUAGE, "fr");
headers.set(HttpHeaders.Names.REFERER, uriSimple.toString()); headers.set(HttpHeaderNames.REFERER, uriSimple.toString());
headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side"); headers.set(HttpHeaderNames.USER_AGENT, "Netty Simple Http Client side");
headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); headers.set(HttpHeaderNames.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
//connection will not close but needed //connection will not close but needed
// headers.set("Connection","keep-alive"); // headers.set("Connection","keep-alive");
headers.set( headers.set(
HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode( HttpHeaderNames.COOKIE, ClientCookieEncoder.encode(
new DefaultCookie("my-cookie", "foo"), new DefaultCookie("my-cookie", "foo"),
new DefaultCookie("another-cookie", "bar")) new DefaultCookie("another-cookie", "bar"))
); );

View File

@ -26,8 +26,9 @@ import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
@ -60,7 +61,6 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static io.netty.buffer.Unpooled.*; import static io.netty.buffer.Unpooled.*;
import static io.netty.handler.codec.http.HttpHeaders.Names.*;
public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObject> { public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObject> {
@ -120,7 +120,7 @@ public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObj
// new getMethod // new getMethod
Set<Cookie> cookies; Set<Cookie> cookies;
String value = request.headers().getAndConvert(COOKIE); String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
if (value == null) { if (value == null) {
cookies = Collections.emptySet(); cookies = Collections.emptySet();
} else { } else {
@ -287,23 +287,23 @@ public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObj
responseContent.setLength(0); responseContent.setLength(0);
// Decide whether to close the connection or not. // Decide whether to close the connection or not.
boolean close = request.headers().contains(CONNECTION, HttpHeaders.Values.CLOSE, true) boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
|| request.protocolVersion().equals(HttpVersion.HTTP_1_0) || request.protocolVersion().equals(HttpVersion.HTTP_1_0)
&& !request.headers().contains(CONNECTION, HttpHeaders.Values.KEEP_ALIVE, true); && !request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);
// Build the response object. // Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse( FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
if (!close) { if (!close) {
// There's no need to add 'Content-Length' header // There's no need to add 'Content-Length' header
// if this is the last response. // if this is the last response.
response.headers().setInt(CONTENT_LENGTH, buf.readableBytes()); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
} }
Set<Cookie> cookies; Set<Cookie> cookies;
String value = request.headers().getAndConvert(COOKIE); String value = request.headers().getAndConvert(HttpHeaderNames.COOKIE);
if (value == null) { if (value == null) {
cookies = Collections.emptySet(); cookies = Collections.emptySet();
} else { } else {
@ -312,7 +312,7 @@ public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObj
if (!cookies.isEmpty()) { if (!cookies.isEmpty()) {
// Reset the cookies if necessary. // Reset the cookies if necessary.
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode(cookie));
} }
} }
// Write the response. // Write the response.
@ -400,8 +400,8 @@ public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObj
FullHttpResponse response = new DefaultFullHttpResponse( FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
response.headers().setInt(CONTENT_LENGTH, buf.readableBytes()); response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
// Write the response. // Write the response.
ctx.channel().writeAndFlush(response); ctx.channel().writeAndFlush(response);

View File

@ -35,7 +35,7 @@ import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;

View File

@ -34,7 +34,7 @@ import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;

View File

@ -14,9 +14,6 @@
*/ */
package io.netty.example.http2.client; package io.netty.example.http2.client;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.Channel; import io.netty.channel.Channel;
@ -26,7 +23,8 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http2.Http2OrHttpChooser.SelectedProtocol; import io.netty.handler.codec.http2.Http2OrHttpChooser.SelectedProtocol;
import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.ApplicationProtocolConfig;
@ -41,6 +39,9 @@ import io.netty.util.CharsetUtil;
import java.net.URI; import java.net.URI;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpVersion.*;
/** /**
* An HTTP2 client that allows you to send HTTP2 frames to a server. Inbound and outbound frames are * An HTTP2 client that allows you to send HTTP2 frames to a server. Inbound and outbound frames are
* logged. When run from the command-line, sends a single HEADERS frame to the server and gets back * logged. When run from the command-line, sends a single HEADERS frame to the server and gets back
@ -103,9 +104,9 @@ public final class Http2Client {
if (URL != null) { if (URL != null) {
// Create a simple GET request. // Create a simple GET request.
FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
request.headers().addObject(HttpHeaders.Names.HOST, hostName); request.headers().addObject(HttpHeaderNames.HOST, hostName);
request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.DEFLATE); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
channel.writeAndFlush(request); channel.writeAndFlush(request);
responseHandler.put(streamId, channel.newPromise()); responseHandler.put(streamId, channel.newPromise());
streamId += 2; streamId += 2;
@ -114,9 +115,9 @@ public final class Http2Client {
// Create a simple POST request with a body. // Create a simple POST request with a body.
FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
request.headers().addObject(HttpHeaders.Names.HOST, hostName); request.headers().addObject(HttpHeaderNames.HOST, hostName);
request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.DEFLATE); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
channel.writeAndFlush(request); channel.writeAndFlush(request);
responseHandler.put(streamId, channel.newPromise()); responseHandler.put(streamId, channel.newPromise());
streamId += 2; streamId += 2;

View File

@ -22,10 +22,10 @@ import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
@ -51,7 +51,7 @@ public class HelloWorldHttp1Handler extends SimpleChannelInboundHandler<HttpRequ
if (!keepAlive) { if (!keepAlive) {
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} else { } else {
response.headers().set(CONNECTION, Values.KEEP_ALIVE); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.writeAndFlush(response); ctx.writeAndFlush(response);
} }
} }

View File

@ -22,7 +22,8 @@ import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpVersion;
@ -83,8 +84,8 @@ public final class SpdyClient {
// Create a GET request. // Create a GET request.
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
request.headers().set(HttpHeaders.Names.HOST, HOST); request.headers().set(HttpHeaderNames.HOST, HOST);
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
// Send the GET request. // Send the GET request.
channel.writeAndFlush(request).sync(); channel.writeAndFlush(request).sync();

View File

@ -23,13 +23,13 @@ import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import java.util.Date; import java.util.Date;
import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
@ -57,7 +57,7 @@ public class SpdyServerHandler extends SimpleChannelInboundHandler<Object> {
if (!keepAlive) { if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE); ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else { } else {
response.headers().set(CONNECTION, Values.KEEP_ALIVE); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.write(response); ctx.write(response);
} }
} }

View File

@ -25,7 +25,7 @@ import io.netty.handler.codec.base64.Base64;
import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpResponseStatus;
@ -127,11 +127,11 @@ public final class HttpProxyHandler extends ProxyHandler {
SocketAddress proxyAddress = proxyAddress(); SocketAddress proxyAddress = proxyAddress();
if (proxyAddress instanceof InetSocketAddress) { if (proxyAddress instanceof InetSocketAddress) {
InetSocketAddress hostAddr = (InetSocketAddress) proxyAddress; InetSocketAddress hostAddr = (InetSocketAddress) proxyAddress;
req.headers().set(Names.HOST, hostAddr.getHostString() + ':' + hostAddr.getPort()); req.headers().set(HttpHeaderNames.HOST, hostAddr.getHostString() + ':' + hostAddr.getPort());
} }
if (authorization != null) { if (authorization != null) {
req.headers().set(Names.AUTHORIZATION, authorization); req.headers().set(HttpHeaderNames.AUTHORIZATION, authorization);
} }
return req; return req;

View File

@ -26,7 +26,7 @@ import io.netty.handler.codec.base64.Base64;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpRequestDecoder;
@ -86,7 +86,7 @@ final class HttpProxyServer extends ProxyServer {
boolean authzSuccess = false; boolean authzSuccess = false;
if (username != null) { if (username != null) {
CharSequence authz = req.headers().get(Names.AUTHORIZATION); CharSequence authz = req.headers().get(HttpHeaderNames.AUTHORIZATION);
if (authz != null) { if (authz != null) {
ByteBuf authzBuf64 = Unpooled.copiedBuffer(authz, CharsetUtil.US_ASCII); ByteBuf authzBuf64 = Unpooled.copiedBuffer(authz, CharsetUtil.US_ASCII);
ByteBuf authzBuf = Base64.decode(authzBuf64); ByteBuf authzBuf = Base64.decode(authzBuf64);
@ -113,7 +113,7 @@ final class HttpProxyServer extends ProxyServer {
FullHttpResponse res; FullHttpResponse res;
if (!authenticate(ctx, req)) { if (!authenticate(ctx, req)) {
res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
res.headers().setInt(Names.CONTENT_LENGTH, 0); res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
} else { } else {
res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
String uri = req.uri(); String uri = req.uri();
@ -144,10 +144,10 @@ final class HttpProxyServer extends ProxyServer {
if (!authenticate(ctx, req)) { if (!authenticate(ctx, req)) {
res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
res.headers().setInt(Names.CONTENT_LENGTH, 0); res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
} else if (!req.uri().equals(destination.getHostString() + ':' + destination.getPort())) { } else if (!req.uri().equals(destination.getHostString() + ':' + destination.getPort())) {
res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
res.headers().setInt(Names.CONTENT_LENGTH, 0); res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
} else { } else {
res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
sendGreeting = true; sendGreeting = true;

View File

@ -24,6 +24,7 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderUtil; import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
@ -40,7 +41,6 @@ import io.netty.util.internal.StringUtil;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*; import static io.netty.handler.codec.http.HttpVersion.*;
@ -143,6 +143,6 @@ public class AutobahnServerHandler extends ChannelHandlerAdapter {
} }
private static String getWebSocketLocation(FullHttpRequest req) { private static String getWebSocketLocation(FullHttpRequest req) {
return "ws://" + req.headers().get(Names.HOST); return "ws://" + req.headers().get(HttpHeaderNames.HOST);
} }
} }