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

The following examples show how to use io.netty.handler.codec.http.HttpHeaderValues. 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: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testPredictions(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");
    req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers()
            .set(
                    HttpHeaderNames.CONTENT_TYPE,
                    HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    channel.writeAndFlush(req);

    latch.await();
    Assert.assertEquals(result, "OK");
}
 
Example #2
Source File: HelloWorldHttp1Handler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}
 
Example #3
Source File: DataCompressionHttp2Test.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void deflateEncodingWriteLargeMessage() throws Exception {
    final int BUFFER_SIZE = 1 << 12;
    final byte[] bytes = new byte[BUFFER_SIZE];
    new Random().nextBytes(bytes);
    bootstrapEnv(BUFFER_SIZE);
    final ByteBuf data = Unpooled.wrappedBuffer(bytes);
    try {
        final Http2Headers headers = new DefaultHttp2Headers().method(POST).path(PATH)
                .set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.DEFLATE);

        runInChannel(clientChannel, new Http2Runnable() {
            @Override
            public void run() throws Http2Exception {
                clientEncoder.writeHeaders(ctxClient(), 3, headers, 0, false, newPromiseClient());
                clientEncoder.writeData(ctxClient(), 3, data.retain(), 0, true, newPromiseClient());
                clientHandler.flush(ctxClient());
            }
        });
        awaitServer();
        assertEquals(data.resetReaderIndex().toString(CharsetUtil.UTF_8),
                serverOut.toString(CharsetUtil.UTF_8.name()));
    } finally {
        data.release();
    }
}
 
Example #4
Source File: AuctionHandler.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
private void respondWith(PreBidResponse response, RoutingContext context, long startTime) {
    // don't send the response if client has gone
    if (context.response().closed()) {
        logger.warn("The client already closed connection, response will be skipped");
        metrics.updateRequestTypeMetric(REQUEST_TYPE_METRIC, MetricName.networkerr);
        return;
    }

    context.response()
            .exceptionHandler(this::handleResponseException)
            .putHeader(HttpUtil.DATE_HEADER, date())
            .putHeader(HttpUtil.CONTENT_TYPE_HEADER, HttpHeaderValues.APPLICATION_JSON)
            .end(mapper.encode(response));

    metrics.updateRequestTimeMetric(clock.millis() - startTime);
}
 
Example #5
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testPredictionsValidRequestSize(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");

    req.content().writeZero(10385760);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_OCTET_STREAM);
    channel.writeAndFlush(req);

    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
}
 
Example #6
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue632() throws Exception {
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .wiretap(true)
			          .handle((req, res) ->
			              res.header(HttpHeaderNames.CONNECTION,
			                         HttpHeaderValues.UPGRADE + ", " + HttpHeaderValues.CLOSE))
			          .bindNow();
	assertThat(disposableServer).isNotNull();

	CountDownLatch latch = new CountDownLatch(1);
	createHttpClientForContextWithPort()
	        .doOnConnected(conn ->
	                conn.channel()
	                    .closeFuture()
	                    .addListener(future -> latch.countDown()))
	        .get()
	        .uri("/")
	        .responseContent()
	        .blockLast(Duration.ofSeconds(30));

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
}
 
Example #7
Source File: SnapshotTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testLoadModelWithInitialWorkersSnapshot"})
public void testNoSnapshotOnPrediction() throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    String requestURL = "/predictions/noop_v1.0";
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestURL);
    req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers()
            .set(
                    HttpHeaderNames.CONTENT_TYPE,
                    HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    channel.writeAndFlush(req);
}
 
Example #8
Source File: HttpClientWithTomcatTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void disableChunkForced() {
	AtomicReference<HttpHeaders> headers = new AtomicReference<>();
	Tuple2<HttpResponseStatus, String> r =
			HttpClient.newConnection()
			          .host("localhost")
			          .port(getPort())
			          .headers(h -> h.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED))
			          .wiretap(true)
			          .doAfterRequest((req, connection) -> headers.set(req.requestHeaders()))
			          .request(HttpMethod.GET)
			          .uri("/status/400")
			          .send(ByteBufFlux.fromString(Flux.just("hello")))
			          .responseSingle((res, conn) -> Mono.just(res.status())
			                                             .zipWith(conn.asString()))
			          .block(Duration.ofSeconds(30));

	assertThat(r).isNotNull();

	assertThat(r.getT1()).isEqualTo(HttpResponseStatus.BAD_REQUEST);
	assertThat(headers.get().get("Content-Length")).isEqualTo("5");
	assertThat(headers.get().get("Transfer-Encoding")).isNull();
}
 
Example #9
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testPredictionsJson"})
public void testInvocationsJson() throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/invocations?model_name=noop");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    channel.writeAndFlush(req);
    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getResult(), "OK");
}
 
Example #10
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testInvocationsMultipart"})
public void testModelsInvokeJson() throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/models/noop/invoke");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    channel.writeAndFlush(req);
    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getResult(), "OK");
}
 
Example #11
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testLegacyPredict"})
public void testPredictionsInvalidRequestSize() throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");

    req.content().writeZero(11485760);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_OCTET_STREAM);
    channel.writeAndFlush(req);

    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getHttpStatus(), HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
}
 
Example #12
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testPredictionsDecodeRequest(Channel inferChannel, Channel mgmtChannel)
        throws InterruptedException, NoSuchFieldException, IllegalAccessException {
    setConfiguration("decode_input_request", "true");
    loadTests(mgmtChannel, "noop-v1.0-config-tests", "noop-config");

    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop-config");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    inferChannel.writeAndFlush(req);

    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
    Assert.assertFalse(result.contains("bytearray"));
    unloadTests(mgmtChannel, "noop-config");
}
 
Example #13
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
private void testPredictions(String modelName, String expectedOutput, String version)
        throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    String requestURL = "/predictions/" + modelName;
    if (version != null) {
        requestURL += "/" + version;
    }
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestURL);
    req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers()
            .set(
                    HttpHeaderNames.CONTENT_TYPE,
                    HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    channel.writeAndFlush(req);

    TestUtils.getLatch().await();
    Assert.assertEquals(TestUtils.getResult(), expectedOutput);
}
 
Example #14
Source File: HelloWorldHttp1Handler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}
 
Example #15
Source File: Http1RequestHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency,
        final FullHttpResponse response, final FullHttpRequest request) {
    HttpUtil.setContentLength(response, response.content().readableBytes());
    ctx.executor().schedule(new Runnable() {
        @Override
        public void run() {
            if (isKeepAlive(request)) {
                response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                ctx.writeAndFlush(response);
            } else {
                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }, latency, TimeUnit.MILLISECONDS);
}
 
Example #16
Source File: HttpDownloadHandlerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND). */
@Test
public void httpErrorsAreSupported() throws IOException {
  EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null, ImmutableList.of()));
  ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream());
  DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, DIGEST, out);
  ChannelPromise writePromise = ch.newPromise();
  ch.writeOneOutbound(cmd, writePromise);

  HttpResponse response =
      new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
  response.headers().set(HttpHeaders.HOST, "localhost");
  response.headers().set(HttpHeaders.CONTENT_LENGTH, 0);
  response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  ch.writeInbound(response);
  ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
  assertThat(writePromise.isDone()).isTrue();
  assertThat(writePromise.cause()).isInstanceOf(HttpException.class);
  assertThat(((HttpException) writePromise.cause()).response().status())
      .isEqualTo(HttpResponseStatus.NOT_FOUND);
  // No data should have been written to the OutputStream and it should have been closed.
  assertThat(out.size()).isEqualTo(0);
  // The caller is responsible for closing the stream.
  verify(out, never()).close();
  assertThat(ch.isOpen()).isTrue();
}
 
Example #17
Source File: StreamServerGroupHandler.java    From IpCamera with Eclipse Public License 2.0 6 votes vote down vote up
private void sendFile(ChannelHandlerContext ctx, String fileUri, String contentType) throws IOException {
    logger.debug("file is :{}", fileUri);
    File file = new File(fileUri);
    ChunkedFile chunkedFile = new ChunkedFile(file);
    ByteBuf footerBbuf = Unpooled.copiedBuffer("\r\n", 0, 2, StandardCharsets.UTF_8);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, HttpHeaderValues.NO_CACHE);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    response.headers().add(HttpHeaderNames.CONTENT_LENGTH, chunkedFile.length());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Expose-Headers", "*");
    ctx.channel().write(response);
    ctx.channel().write(chunkedFile);
    ctx.channel().writeAndFlush(footerBbuf);
}
 
Example #18
Source File: PipelineUtils.java    From socketio with Apache License 2.0 6 votes vote down vote up
public static HttpResponse createHttpResponse(final String origin, ByteBuf content, boolean json) {
  FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
  if (json) {
    res.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/javascript; charset=UTF-8");
  } else {
    res.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
  }
  res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  if (origin != null) {
    res.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    res.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
  }
  HttpUtil.setContentLength(res, content.readableBytes());

  return res;
}
 
Example #19
Source File: WebSocketClientHandshaker07.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example #20
Source File: Http1ServerTask.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected void sendHttp1Response0(HttpResponseStatus status, boolean error, ByteBuf content) {
    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    HttpHeaders headers = httpResponse.headers();

    headers.setInt(CONTENT_LENGTH, httpResponse.content().readableBytes());
    if (request.getSerializeType() > 0) {
        String serialization = SerializerFactory.getAliasByCode(request.getSerializeType());
        headers.set(RemotingConstants.HEAD_SERIALIZE_TYPE, serialization);
    } else {
        headers.set(CONTENT_TYPE, "text/plain; charset=" + RpcConstants.DEFAULT_CHARSET.displayName());
    }
    if (error) {
        headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    }
    if (!keepAlive) {
        ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE);
    } else {
        httpResponse.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(httpResponse);
    }
}
 
Example #21
Source File: WebSocketClientHandshaker13.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Process server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 *
 * @param response
 *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
 * @throws WebSocketHandshakeException
 */
@Override
protected void verify(FullHttpResponse response) {
    final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    final HttpHeaders headers = response.headers();

    if (!response.status().equals(status)) {
        throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
    }

    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
    }

    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketHandshakeException("Invalid handshake response connection: "
                + headers.get(HttpHeaderNames.CONNECTION));
    }

    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
    }
}
 
Example #22
Source File: ResponseTextIntercept.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
    HttpProxyInterceptPipeline pipeline) throws Exception {
  if (match(httpResponse, pipeline)) {
    isMatch = true;
    //解压gzip响应
    if ("gzip".equalsIgnoreCase(httpResponse.headers().get(HttpHeaderNames.CONTENT_ENCODING))) {
      isGzip = true;
      pipeline.reset3();
      proxyChannel.pipeline().addAfter("httpCodec", "decompress", new HttpContentDecompressor());
      proxyChannel.pipeline().fireChannelRead(httpResponse);
    } else {
      if (isGzip) {
        httpResponse.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
      }
      contentBuf = PooledByteBufAllocator.DEFAULT.buffer();
    }
    //直接调用默认拦截器,跳过下载拦截器
    pipeline.getDefault()
        .afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
  } else {
    isMatch = false;
    pipeline.afterResponse(clientChannel, proxyChannel, httpResponse);
  }
}
 
Example #23
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testPredictionsValidRequestSize"})
public void testPredictionsDecodeRequest()
        throws InterruptedException, NoSuchFieldException, IllegalAccessException {
    Channel inferChannel = TestUtils.getInferenceChannel(configManager);
    Channel mgmtChannel = TestUtils.getManagementChannel(configManager);
    setConfiguration("decode_input_request", "true");
    loadTests(mgmtChannel, "noop-v1.0-config-tests.mar", "noop-config");
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop-config");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    inferChannel.writeAndFlush(req);

    TestUtils.getLatch().await();

    Assert.assertEquals(TestUtils.getHttpStatus(), HttpResponseStatus.OK);
    Assert.assertFalse(TestUtils.getResult().contains("bytearray"));
    unloadTests(mgmtChannel, "noop-config");
}
 
Example #24
Source File: WebSocketServerHandshaker08.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Handle the web socket handshake for the web socket specification <a href=
 * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08">HyBi version 8 to 10</a>. Version 8, 9 and
 * 10 share the same wire protocol.
 * </p>
 *
 * <p>
 * Browser request to the server:
 * </p>
 *
 * <pre>
 * GET /chat HTTP/1.1
 * Host: server.example.com
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Protocol: chat, superchat
 * Sec-WebSocket-Version: 8
 * </pre>
 *
 * <p>
 * Server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 Switching Protocols
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
 * Sec-WebSocket-Protocol: chat
 * </pre>
 */
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);

    if (headers != null) {
        res.headers().add(headers);
    }

    CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
    if (key == null) {
        throw new WebSocketHandshakeException("not a WebSocket request: missing key");
    }
    String acceptSeed = key + WEBSOCKET_08_ACCEPT_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    String accept = WebSocketUtil.base64(sha1);

    if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 08 server handshake key: {}, response: {}", key, accept);
    }

    res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
    res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
    res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);

    String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    if (subprotocols != null) {
        String selectedSubprotocol = selectSubprotocol(subprotocols);
        if (selectedSubprotocol == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
            }
        } else {
            res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
        }
    }
    return res;
}
 
Example #25
Source File: KidozBidderTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void makeHttpRequestsShouldSetDefaultHeaders() {
    // given
    final BidRequest bidRequest = givenBidRequest(identity());

    // when
    final Result<List<HttpRequest<BidRequest>>> result = kidozBidder.makeHttpRequests(bidRequest);

    // then
    assertThat(result.getValue().get(0).getHeaders()).isNotNull()
            .extracting(Map.Entry::getKey, Map.Entry::getValue)
            .containsOnly(tuple("x-openrtb-version", "2.5"),
                    tuple(HttpUtil.CONTENT_TYPE_HEADER.toString(), HttpUtil.APPLICATION_JSON_CONTENT_TYPE),
                    tuple(HttpUtil.ACCEPT_HEADER.toString(), HttpHeaderValues.APPLICATION_JSON.toString()));
}
 
Example #26
Source File: OpenApiUtils.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private static MediaType getErrorResponse() {
    Schema schema = new Schema("object");
    schema.addProperty("code", new Schema("integer", "Error code."), true);
    schema.addProperty("type", new Schema("string", "Error type."), true);
    schema.addProperty("message", new Schema("string", "Error message."), true);

    return new MediaType(HttpHeaderValues.APPLICATION_JSON.toString(), schema);
}
 
Example #27
Source File: WhoisServiceHandler.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
protected FullHttpRequest decodeFullHttpRequest(ByteBuf byteBuf) {
  FullHttpRequest request = super.decodeFullHttpRequest(byteBuf);
  request
      .headers()
      .set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN)
      .set(HttpHeaderNames.ACCEPT, HttpHeaderValues.TEXT_PLAIN);
  return request;
}
 
Example #28
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void stripTEHeadersAccountsForValueSimilarToTrailers() {
    final io.netty.handler.codec.http.HttpHeaders in = new DefaultHttpHeaders();
    in.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS + "foo");
    final HttpHeadersBuilder out = HttpHeaders.builder();
    toArmeria(in, out);
    assertThat(out.contains(HttpHeaderNames.TE)).isFalse();
}
 
Example #29
Source File: H2ToStH1ServerDuplexHandler.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private NettyH2HeadersToHttpHeaders h2HeadersToH1HeadersServer(Http2Headers h2Headers,
                                                               @Nullable HttpRequestMethod httpMethod) {
    CharSequence value = h2Headers.getAndRemove(AUTHORITY.value());
    if (value != null) {
        h2Headers.set(HOST, value);
    }
    h2Headers.remove(Http2Headers.PseudoHeaderName.SCHEME.value());
    h2HeadersSanitizeForH1(h2Headers);
    if (httpMethod != null && !h2Headers.contains(HttpHeaderNames.CONTENT_LENGTH) &&
            clientMaySendPayloadBodyFor(httpMethod)) {
        h2Headers.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    }
    return new NettyH2HeadersToHttpHeaders(h2Headers, headersFactory.validateCookies());
}
 
Example #30
Source File: Http2Util.java    From tutorials with MIT License 5 votes vote down vote up
public static FullHttpRequest createGetRequest(String host, int port) {
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.valueOf("HTTP/2.0"), HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER);
    request.headers()
        .add(HttpHeaderNames.HOST, new String(host + ":" + port));
    request.headers()
        .add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS);
    request.headers()
        .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
    request.headers()
        .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
    return request;
}