io.netty.handler.codec.http.EmptyHttpHeaders Java Examples

The following examples show how to use io.netty.handler.codec.http.EmptyHttpHeaders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PublisherAdapterTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: Channelizer.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: HttpsUpgradeHandler.java    From xio with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: HttpObjectEncoderBenchmark.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@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);
        }
    };
}
 
Example #5
Source File: HttpPostRequestEncoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHeaders trailingHeaders() {
    if (content instanceof LastHttpContent) {
        return ((LastHttpContent) content).trailingHeaders();
    } else {
        return EmptyHttpHeaders.INSTANCE;
    }
}
 
Example #6
Source File: ClientJSONPoint.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example #7
Source File: ClientJSONPoint.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
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());
    });
}
 
Example #8
Source File: LBAwareSigV4WebSocketChannelizer.java    From amazon-neptune-tools with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: HttpTransportClientTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@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);

}
 
Example #10
Source File: WebSocketClient.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #11
Source File: Http1ClientCodec.java    From xio with Apache License 2.0 5 votes vote down vote up
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));
  }
}
 
Example #12
Source File: RejectionUtils.java    From zuul with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: WebSocketClientHandshakerTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
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();
    }
}
 
Example #14
Source File: CorsConfigTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test
public void emptyPreflightResponseHeaders() {
    final CorsConfig cors = forAnyOrigin().noPreflightResponseHeaders().build();
    assertThat(cors.preflightResponseHeaders(), equalTo((HttpHeaders) EmptyHttpHeaders.INSTANCE));
}