下面列出了怎么用 io.netty.handler.codec.http.EmptyHttpHeaders 的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void setUp() throws Exception {
executeFuture = new CompletableFuture<>();
fullHttpResponse = mock(DefaultHttpContent.class);
when(fullHttpResponse.content()).thenReturn(new EmptyByteBuf(ByteBufAllocator.DEFAULT));
requestContext = new RequestContext(channelPool,
eventLoopGroup,
AsyncExecuteRequest.builder().responseHandler(responseHandler).build(),
null);
channel = new MockChannel();
channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1));
channel.attr(REQUEST_CONTEXT_KEY).set(requestContext);
channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture);
when(ctx.channel()).thenReturn(channel);
nettyResponseHandler = ResponseHandler.getInstance();
DefaultHttpResponse defaultFullHttpResponse = mock(DefaultHttpResponse.class);
when(defaultFullHttpResponse.headers()).thenReturn(EmptyHttpHeaders.INSTANCE);
when(defaultFullHttpResponse.status()).thenReturn(HttpResponseStatus.CREATED);
when(defaultFullHttpResponse.protocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
nettyResponseHandler.channelRead0(ctx, defaultFullHttpResponse);
}
@Override
public void configure(final ChannelPipeline pipeline) {
final String scheme = connection.getUri().getScheme();
if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme))
throw new IllegalStateException("Unsupported scheme (only ws: or wss: supported): " + scheme);
if (!supportsSsl() && "wss".equalsIgnoreCase(scheme))
throw new IllegalStateException("To use wss scheme ensure that enableSsl is set to true in configuration");
final int maxContentLength = cluster.connectionPoolSettings().maxContentLength;
handler = new WebSocketClientHandler(
WebSocketClientHandshakerFactory.newHandshaker(
connection.getUri(), WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, maxContentLength));
pipeline.addLast("http-codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
pipeline.addLast("ws-handler", handler);
pipeline.addLast("gremlin-encoder", webSocketGremlinRequestEncoder);
pipeline.addLast("gremlin-decoder", webSocketGremlinResponseDecoder);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
List<ByteBuf> payload;
HttpHeaders headers = new CombinedHttpHeaders(true);
headers.add(HttpHeaderNames.UPGRADE, "TLS/1.2");
headers.add(HttpHeaderNames.UPGRADE, HTTP_1_1);
headers.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
headers.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
headers.add(HttpHeaderNames.CONTENT_LENGTH, "0");
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(
HTTP_1_1, UPGRADE_REQUIRED, Unpooled.EMPTY_BUFFER, headers, EmptyHttpHeaders.INSTANCE);
payload = Recipes.encodeResponse(response);
for (ByteBuf buffer : payload) {
ctx.write(buffer.copy());
}
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
@Setup(Level.Trial)
public void setup() {
byte[] bytes = new byte[256];
content = Unpooled.buffer(bytes.length);
content.writeBytes(bytes);
ByteBuf testContent = Unpooled.unreleasableBuffer(content.asReadOnly());
HttpHeaders headersWithChunked = new DefaultHttpHeaders(false);
headersWithChunked.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
HttpHeaders headersWithContentLength = new DefaultHttpHeaders(false);
headersWithContentLength.add(HttpHeaderNames.CONTENT_LENGTH, testContent.readableBytes());
fullRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", testContent,
headersWithContentLength, EmptyHttpHeaders.INSTANCE);
contentLengthRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index",
headersWithContentLength);
chunkedRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/index", headersWithChunked);
lastContent = new DefaultLastHttpContent(testContent, false);
encoder = new HttpRequestEncoder();
context = new EmbeddedChannelWriteReleaseHandlerContext(pooledAllocator ? PooledByteBufAllocator.DEFAULT :
UnpooledByteBufAllocator.DEFAULT, encoder) {
@Override
protected void handleException(Throwable t) {
handleUnexpectedException(t);
}
};
}
@Override
public HttpHeaders trailingHeaders() {
if (content instanceof LastHttpContent) {
return ((LastHttpContent) content).trailingHeaders();
} else {
return EmptyHttpHeaders.INSTANCE;
}
}
public void open() throws Exception {
//System.out.println("WebSocket Client connecting");
webSocketClientHandler =
new WebSocketClientHandler(
WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, 12800000), this);
ch = bootstrap.connect(uri.getHost(), port).sync().channel();
webSocketClientHandler.handshakeFuture().sync();
}
public void openAsync(Runnable onConnect) {
//System.out.println("WebSocket Client connecting");
webSocketClientHandler =
new WebSocketClientHandler(
WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, 12800000), this);
ChannelFuture future = bootstrap.connect(uri.getHost(), port);
future.addListener((e) -> {
ch = future.channel();
webSocketClientHandler.handshakeFuture().addListener((e1) -> onConnect.run());
});
}
/**
* Creates an instance of {@link WebSocketClientHandler} with {@link AwsSigV4ClientHandshaker} as the handshaker
* for SigV4 auth.
* @return the instance of clientHandler.
*/
private WebSocketClientHandler createHandler() {
HandshakeRequestConfig handshakeRequestConfig =
HandshakeRequestConfig.parse(cluster.authProperties().get(AuthProperties.Property.JAAS_ENTRY));
WebSocketClientHandshaker handshaker = new LBAwareAwsSigV4ClientHandshaker(
connection.getUri(),
WebSocketVersion.V13,
null,
false,
EmptyHttpHeaders.INSTANCE,
cluster.getMaxContentLength(),
new ChainedSigV4PropertiesProvider(),
handshakeRequestConfig);
return new WebSocketClientHandler(handshaker);
}
@Test(groups = "unit")
public void validateDefaultHeaders() {
HttpClientResponse<ByteBuf> mockedResponse = new HttpClientMockWrapper.HttpClientBehaviourBuilder()
.withContent("").withStatus(200)
.withHeaders(EmptyHttpHeaders.INSTANCE)
.asHttpClientResponse();
HttpClientMockWrapper httpClientMockWrapper = new HttpClientMockWrapper(mockedResponse);
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix("i am suffix");
HttpTransportClient transportClient = getHttpTransportClientUnderTest(100,
userAgentContainer,
httpClientMockWrapper.getClient());
RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName(
OperationType.Create, "dbs/db/colls/col", ResourceType.Document);
request.setContentBytes(new byte[0]);
transportClient.invokeStoreAsync(Uri.create(physicalAddress),
new ResourceOperation(OperationType.Create, ResourceType.Document),
request).toBlocking().value();
assertThat(httpClientMockWrapper.getCapturedInvocation()).asList().hasSize(1);
ImmutablePair<HttpClientRequest<ByteBuf>, RxClient.ServerInfo> httpClientInvocation = httpClientMockWrapper.getCapturedInvocation().get(0);
assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.USER_AGENT)).endsWith("i am suffix");
assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.CACHE_CONTROL)).isEqualTo("no-cache");
assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.ACCEPT)).isEqualTo("application/json");
assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.VERSION)).isEqualTo(HttpConstants.Versions.CURRENT_VERSION);
}
public WebSocketClient(final URI uri) {
super("ws-client-%d");
final Bootstrap b = new Bootstrap().group(group);
b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
final String protocol = uri.getScheme();
if (!"ws".equals(protocol))
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
try {
final WebSocketClientHandler wsHandler =
new WebSocketClientHandler(
WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, 65536));
final MessageSerializer serializer = new GraphBinaryMessageSerializerV1();
b.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
final ChannelPipeline p = ch.pipeline();
p.addLast(
new HttpClientCodec(),
new HttpObjectAggregator(65536),
wsHandler,
new WebSocketGremlinRequestEncoder(true, serializer),
new WebSocketGremlinResponseDecoder(serializer),
callbackResponseHandler);
}
});
channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
wsHandler.handshakeFuture().get(10000, TimeUnit.MILLISECONDS);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
HttpRequest buildRequest(Request request) {
if (!request.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {
request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
}
if (request.keepAlive()) {
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
if (request instanceof FullRequest) {
FullRequest full = (FullRequest) request;
ByteBuf content = full.body();
if (content == null) {
content = Unpooled.EMPTY_BUFFER;
}
if (!full.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) {
full.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
}
// Request request = getChannelRequest(ctx);
// setChannelResponse(ctx, null);
return new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1,
full.method(),
full.path(),
content,
full.headers().http1Headers(false, true),
EmptyHttpHeaders.INSTANCE);
} else {
// TODO(CK): TransferEncoding
return new DefaultHttpRequest(
HttpVersion.HTTP_1_1,
request.method(),
request.path(),
request.headers().http1Headers(false, true));
}
}
private static FullHttpResponse createRejectionResponse(
HttpResponseStatus status, String plaintextMessage, boolean closeConnection,
Map<String, String> rejectionHeaders) {
ByteBuf body = Unpooled.wrappedBuffer(plaintextMessage.getBytes(StandardCharsets.UTF_8));
int length = body.readableBytes();
DefaultHttpHeaders headers = new DefaultHttpHeaders();
headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8");
headers.set(HttpHeaderNames.CONTENT_LENGTH, length);
if (closeConnection) {
headers.set(HttpHeaderNames.CONNECTION, "close");
}
rejectionHeaders.forEach(headers::add);
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, body, headers, EmptyHttpHeaders.INSTANCE);
}
private void testHttpResponseAndFrameInSameBuffer(boolean codec) {
String url = "ws://localhost:9999/ws";
final WebSocketClientHandshaker shaker = newHandshaker(URI.create(url));
final WebSocketClientHandshaker handshaker = new WebSocketClientHandshaker(
shaker.uri(), shaker.version(), null, EmptyHttpHeaders.INSTANCE, Integer.MAX_VALUE) {
@Override
protected FullHttpRequest newHandshakeRequest() {
return shaker.newHandshakeRequest();
}
@Override
protected void verify(FullHttpResponse response) {
// Not do any verification, so we not need to care sending the correct headers etc in the test,
// which would just make things more complicated.
}
@Override
protected WebSocketFrameDecoder newWebsocketDecoder() {
return shaker.newWebsocketDecoder();
}
@Override
protected WebSocketFrameEncoder newWebSocketEncoder() {
return shaker.newWebSocketEncoder();
}
};
byte[] data = new byte[24];
PlatformDependent.threadLocalRandom().nextBytes(data);
// Create a EmbeddedChannel which we will use to encode a BinaryWebsocketFrame to bytes and so use these
// to test the actual handshaker.
WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(url, null, false);
WebSocketServerHandshaker socketServerHandshaker = factory.newHandshaker(shaker.newHandshakeRequest());
EmbeddedChannel websocketChannel = new EmbeddedChannel(socketServerHandshaker.newWebSocketEncoder(),
socketServerHandshaker.newWebsocketDecoder());
assertTrue(websocketChannel.writeOutbound(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(data))));
byte[] bytes = "HTTP/1.1 101 Switching Protocols\r\nContent-Length: 0\r\n\r\n".getBytes(CharsetUtil.US_ASCII);
CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer();
compositeByteBuf.addComponent(true, Unpooled.wrappedBuffer(bytes));
for (;;) {
ByteBuf frameBytes = websocketChannel.readOutbound();
if (frameBytes == null) {
break;
}
compositeByteBuf.addComponent(true, frameBytes);
}
EmbeddedChannel ch = new EmbeddedChannel(new HttpObjectAggregator(Integer.MAX_VALUE),
new SimpleChannelInboundHandler<FullHttpResponse>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
handshaker.finishHandshake(ctx.channel(), msg);
ctx.pipeline().remove(this);
}
});
if (codec) {
ch.pipeline().addFirst(new HttpClientCodec());
} else {
ch.pipeline().addFirst(new HttpRequestEncoder(), new HttpResponseDecoder());
}
// We need to first write the request as HttpClientCodec will fail if we receive a response before a request
// was written.
shaker.handshake(ch).syncUninterruptibly();
for (;;) {
// Just consume the bytes, we are not interested in these.
ByteBuf buf = ch.readOutbound();
if (buf == null) {
break;
}
buf.release();
}
assertTrue(ch.writeInbound(compositeByteBuf));
assertTrue(ch.finish());
BinaryWebSocketFrame frame = ch.readInbound();
ByteBuf expect = Unpooled.wrappedBuffer(data);
try {
assertEquals(expect, frame.content());
assertTrue(frame.isFinalFragment());
assertEquals(0, frame.rsv());
} finally {
expect.release();
frame.release();
}
}
@Test
public void emptyPreflightResponseHeaders() {
final CorsConfig cors = forAnyOrigin().noPreflightResponseHeaders().build();
assertThat(cors.preflightResponseHeaders(), equalTo((HttpHeaders) EmptyHttpHeaders.INSTANCE));
}