Java Code Examples for io.netty.handler.codec.http.HttpUtil#setKeepAlive()

The following examples show how to use io.netty.handler.codec.http.HttpUtil#setKeepAlive() . 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: NettyResponseChannelTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Tests setting of different available {@link ResponseStatus} codes and sees that they are recognized and converted
 * in {@link NettyResponseChannel}.
 * <p/>
 * If this test fails, a case for conversion probably needs to be added in {@link NettyResponseChannel}.
 */
@Test
public void setStatusTest() {
  // ask for every status to be set
  for (ResponseStatus expectedResponseStatus : ResponseStatus.values()) {
    HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetStatus.toString());
    request.headers().set(MockNettyMessageProcessor.STATUS_HEADER_NAME, expectedResponseStatus);
    HttpUtil.setKeepAlive(request, false);
    EmbeddedChannel channel = createEmbeddedChannel();
    channel.writeInbound(request);

    // pull but discard response
    channel.readOutbound();
    assertFalse("Channel not closed on the server", channel.isActive());
  }
  // check if all the ResponseStatus codes were recognized.
  String metricName = MetricRegistry.name(NettyResponseChannel.class, "UnknownResponseStatusCount");
  long metricCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(metricName).getCount();
  assertEquals("Some of the ResponseStatus codes were not recognized", 0, metricCount);
}
 
Example 2
Source File: HttpConversionUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Translate and add HTTP/2 headers to HTTP/1.x headers.
 *
 * @param streamId The stream associated with {@code sourceHeaders}.
 * @param inputHeaders The HTTP/2 headers to convert.
 * @param outputHeaders The object which will contain the resulting HTTP/1.x headers..
 * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as when doing the conversion.
 * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailing headers.
 * {@code false} otherwise.
 * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message.
 * {@code false} for response message.
 * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
 */
public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders, HttpHeaders outputHeaders,
        HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception {
    Http2ToHttpHeaderTranslator translator = new Http2ToHttpHeaderTranslator(streamId, outputHeaders, isRequest);
    try {
        for (Entry<CharSequence, CharSequence> entry : inputHeaders) {
            translator.translate(entry);
        }
    } catch (Http2Exception ex) {
        throw ex;
    } catch (Throwable t) {
        throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
    }

    outputHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
    outputHeaders.remove(HttpHeaderNames.TRAILER);
    if (!isTrailer) {
        outputHeaders.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId);
        HttpUtil.setKeepAlive(outputHeaders, httpVersion, true);
    }
}
 
Example 3
Source File: NettyMessageProcessorTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Does the post test by sending the request and content to {@link NettyMessageProcessor} through an
 * {@link EmbeddedChannel} and returns the data stored in the {@link InMemoryRouter} as a result of the post.
 * @param postRequest the POST request as a {@link HttpRequest}.
 * @param contentToSend the content to be sent as a part of the POST.
 * @return the data stored in the {@link InMemoryRouter} as a result of the POST.
 * @throws InterruptedException
 */
private ByteBuffer doPostTest(HttpRequest postRequest, List<ByteBuffer> contentToSend) throws InterruptedException {
  EmbeddedChannel channel = createChannel();

  // POST
  notificationSystem.reset();
  postRequest.headers().set(RestUtils.Headers.AMBRY_CONTENT_TYPE, "application/octet-stream");
  HttpUtil.setKeepAlive(postRequest, false);
  channel.writeInbound(postRequest);
  if (contentToSend != null) {
    for (ByteBuffer content : contentToSend) {
      channel.writeInbound(new DefaultHttpContent(Unpooled.wrappedBuffer(content)));
    }
    channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
  }
  if (!notificationSystem.operationCompleted.await(1000, TimeUnit.MILLISECONDS)) {
    fail("Post did not succeed after 1000ms. There is an error or timeout needs to increase");
  }
  assertNotNull("Blob id operated on cannot be null", notificationSystem.blobIdOperatedOn);
  return router.getActiveBlobs().get(notificationSystem.blobIdOperatedOn).getBlob();
}
 
Example 4
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Does a test to see that request handling results in expected entries in public access log
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param uri Uri to be used during the request
 * @param testErrorCase true if error case has to be tested, false otherwise
 * @param useSSL {@code true} to test SSL logging.
 * @throws Exception
 */
private void doRequestHandleTest(HttpMethod httpMethod, String uri, boolean testErrorCase, boolean useSSL)
    throws Exception {
  EmbeddedChannel channel = createChannel(useSSL);
  List<HttpHeaders> httpHeadersList = getHeadersList();
  for (HttpHeaders headers : httpHeadersList) {
    HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, headers);
    HttpUtil.setKeepAlive(request, true);
    sendRequestCheckResponse(channel, request, uri, headers, testErrorCase, false, useSSL);
    if (!testErrorCase) {
      Assert.assertTrue("Channel should not be closed ", channel.isOpen());
    } else {
      Assert.assertFalse("Channel should have been closed ", channel.isOpen());
      channel = createChannel(useSSL);
    }
  }
  channel.close();
}
 
Example 5
Source File: HealthCheckHandlerTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Does a test to see that a health check request results in expected response from the health check handler
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param keepAlive true if keep alive has to be set in the request, false otherwise
 * @throws IOException
 */
private void testHealthCheckRequest(HttpMethod httpMethod, boolean isServiceUp, boolean keepAlive)
    throws IOException {
  EmbeddedChannel channel = createChannel();
  for (int i = 0; i < 2; i++) {
    if (isServiceUp) {
      restServerState.markServiceUp();
    }
    HttpRequest request = RestTestUtils.createRequest(httpMethod, healthCheckUri, null);
    HttpUtil.setKeepAlive(request, keepAlive);
    FullHttpResponse response = sendRequestAndGetResponse(channel, request);
    HttpResponseStatus httpResponseStatus =
        (isServiceUp) ? HttpResponseStatus.OK : HttpResponseStatus.SERVICE_UNAVAILABLE;
    assertEquals("Unexpected response status", httpResponseStatus, response.status());
    String expectedStr = (isServiceUp) ? goodStr : badStr;
    assertEquals("Unexpected content", expectedStr, RestTestUtils.getContentString(response));
    restServerState.markServiceDown();
    if (keepAlive && isServiceUp) {
      Assert.assertTrue("Channel should not be closed ", channel.isOpen());
    } else {
      Assert.assertFalse("Channel should have been closed by now ", channel.isOpen());
      channel = createChannel();
    }
  }
  channel.close();
}
 
Example 6
Source File: PassthroughHandler.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
        final FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER);
        HttpUtil.setKeepAlive(response, true);
        HttpUtil.setContentLength(response, 0);
        if (api.getSslContext() != null) {
            final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
            sslEngine.setUseClientMode(false);
            ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));

            final String uri = request.uri();
            final String[] parts = uri.split(":");
            ctx
                    .channel()
                    .attr(BASE)
                    .set("https://" + parts[0]
                            + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
        }
        ctx.writeAndFlush(response);
        return;
    }
    final FullHttpRequest req = request.copy(); // copy to use in a separated thread
    api.getExecutor().execute(() -> doHttpRequest(req, ctx));
}
 
Example 7
Source File: CorsHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void respond(
        final ChannelHandlerContext ctx,
        final HttpRequest request,
        final HttpResponse response) {

    final boolean keepAlive = HttpUtil.isKeepAlive(request);

    HttpUtil.setKeepAlive(response, keepAlive);

    final ChannelFuture future = ctx.writeAndFlush(response);
    if (!keepAlive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 8
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Tries different exception scenarios for {@link NettyResponseChannel#setRequest(NettyRequest)}.
 */
@Test
public void setRequestTest() {
  HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetRequest.toString());
  HttpUtil.setKeepAlive(request, false);
  EmbeddedChannel channel = createEmbeddedChannel();
  channel.writeInbound(request);

  HttpResponse response = channel.readOutbound();
  assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.status());
  assertFalse("Channel not closed on the server", channel.isActive());
}
 
Example 9
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Sends null input to {@link NettyResponseChannel#setHeader(String, Object)} (through
 * {@link MockNettyMessageProcessor}) and tests for reaction.
 */
@Test
public void nullHeadersSetTest() {
  HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.SetNullHeader.toString());
  HttpUtil.setKeepAlive(request, false);
  EmbeddedChannel channel = createEmbeddedChannel();
  channel.writeInbound(request);

  HttpResponse response = channel.readOutbound();
  assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.status());
  assertFalse("Channel not closed on the server", channel.isActive());
}
 
Example 10
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a request with certain headers that will copied into the response. Checks the response for those headers to
 * see that values match.
 * @throws ParseException
 */
@Test
public void headersPresenceTest() throws ParseException {
  HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.CopyHeaders.toString());
  HttpUtil.setKeepAlive(request, false);
  EmbeddedChannel channel = createEmbeddedChannel();
  channel.writeInbound(request);

  HttpResponse response = channel.readOutbound();
  assertFalse("Channel not closed on the server", channel.isActive());

  checkHeaders(request, response);
}
 
Example 11
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the case where no body needs to be returned but just a
 * {@link RestResponseChannel#onResponseComplete(Exception)} is called on the server. This should return just
 * response metadata.
 */
@Test
public void noResponseBodyTest() {
  EmbeddedChannel channel = createEmbeddedChannel();

  // with Transfer-Encoding:Chunked
  HttpRequest httpRequest =
      RestTestUtils.createRequest(HttpMethod.GET, TestingUri.ImmediateResponseComplete.toString(), null);
  channel.writeInbound(httpRequest);
  // There should be a response.
  HttpResponse response = channel.readOutbound();
  assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
  assertTrue("Response must say 'Transfer-Encoding : chunked'", HttpUtil.isTransferEncodingChunked(response));
  // since this is Transfer-Encoding:chunked, there should be a LastHttpContent
  assertTrue("Did not receive end marker", channel.readOutbound() instanceof LastHttpContent);
  assertTrue("Channel should be alive", channel.isActive());

  // with Content-Length set
  HttpHeaders headers = new DefaultHttpHeaders();
  headers.set(MockNettyMessageProcessor.CHUNK_COUNT_HEADER_NAME, 0);
  httpRequest = RestTestUtils.createRequest(HttpMethod.GET, TestingUri.ImmediateResponseComplete.toString(), headers);
  HttpUtil.setKeepAlive(httpRequest, false);
  channel.writeInbound(httpRequest);
  // There should be a response.
  response = channel.readOutbound();
  assertEquals("Response must have Content-Length set to 0", 0, HttpUtil.getContentLength(response, -1));
  assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
  // since Content-Length is set, the response should be an instance of FullHttpResponse.
  assertTrue("Response not instance of FullHttpResponse", response instanceof FullHttpResponse);
  assertFalse("Channel should not be alive", channel.isActive());
}
 
Example 12
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the request whose response is being served through this instance of NettyResponseChannel.
 * @param request the {@link NettyRequest} whose response is being served through this instance of
 *                NettyResponseChannel.
 */
void setRequest(NettyRequest request) {
  if (request != null) {
    if (this.request == null) {
      this.request = request;
      HttpUtil.setKeepAlive(responseMetadata, request.isKeepAlive());
    } else {
      throw new IllegalStateException(
          "Request has already been set inside NettyResponseChannel for channel {} " + ctx.channel());
    }
  } else {
    throw new IllegalArgumentException("RestRequest provided is null");
  }
}
 
Example 13
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that client initiated terminations don't count towards {@link HttpResponseStatus#INTERNAL_SERVER_ERROR}.
 */
@Test
public void clientEarlyTerminationTest() throws Exception {
  EmbeddedChannel channel = createEmbeddedChannel();
  TestingUri uri = TestingUri.OnResponseCompleteWithEarlyClientTermination;
  HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, uri.toString(), null);
  HttpUtil.setKeepAlive(httpRequest, false);

  String iseMetricName = MetricRegistry.name(NettyResponseChannel.class, "InternalServerErrorCount");
  long iseBeforeCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(iseMetricName).getCount();
  String cetMetricName = MetricRegistry.name(NettyResponseChannel.class, "ClientEarlyTerminationCount");
  long cetBeforeCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(cetMetricName).getCount();

  channel.writeInbound(httpRequest);
  // first outbound has to be response.
  HttpResponse response = channel.readOutbound();
  assertEquals("Unexpected response status", HttpResponseStatus.INTERNAL_SERVER_ERROR, response.status());
  if (!(response instanceof FullHttpResponse)) {
    // empty the channel
    while (channel.readOutbound() != null) {
    }
  }

  assertEquals("Client terminations should not count towards InternalServerError count", iseBeforeCount,
      MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(iseMetricName).getCount());
  assertEquals("Client terminations should have been tracked", cetBeforeCount + 1,
      MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(cetMetricName).getCount());
}
 
Example 14
Source File: ProxyToServerConnection.java    From PowerTunnel with MIT License 5 votes vote down vote up
@Override
protected ConnectionState readHTTPInitial(HttpResponse httpResponse) {
    LOG.debug("Received raw response: {}", httpResponse);

    if (httpResponse.decoderResult().isFailure()) {
        LOG.debug("Could not parse response from server. Decoder result: {}", httpResponse.decoderResult().toString());

        // create a "substitute" Bad Gateway response from the server, since we couldn't understand what the actual
        // response from the server was. set the keep-alive on the substitute response to false so the proxy closes
        // the connection to the server, since we don't know what state the server thinks the connection is in.
        FullHttpResponse substituteResponse = ProxyUtils.createFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.BAD_GATEWAY,
                "Unable to parse response from server");
        HttpUtil.setKeepAlive(substituteResponse, false);
        httpResponse = substituteResponse;
    }

    currentFilters.serverToProxyResponseReceiving();

    rememberCurrentResponse(httpResponse);
    respondWith(httpResponse);

    if (ProxyUtils.isChunked(httpResponse)) {
        return AWAITING_CHUNK;
    } else {
        currentFilters.serverToProxyResponseReceived();

        return AWAITING_INITIAL;
    }
}
 
Example 15
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error.
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
  HttpResponseStatus status;
  RestServiceErrorCode restServiceErrorCode = null;
  String errReason = null;
  if (cause instanceof RestServiceException) {
    RestServiceException restServiceException = (RestServiceException) cause;
    restServiceErrorCode = restServiceException.getErrorCode();
    errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode);
    status = getHttpResponseStatus(errorResponseStatus);
    if (shouldSendFailureReason(status, restServiceException)) {
      errReason = new String(
          Utils.getRootCause(cause).getMessage().replaceAll("[\n\t\r]", " ").getBytes(StandardCharsets.US_ASCII),
          StandardCharsets.US_ASCII);
    }
  } else if (Utils.isPossibleClientTermination(cause)) {
    nettyMetrics.clientEarlyTerminationCount.inc();
    status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    errorResponseStatus = ResponseStatus.InternalServerError;
  } else {
    nettyMetrics.internalServerErrorCount.inc();
    status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    errorResponseStatus = ResponseStatus.InternalServerError;
  }
  logger.trace("Constructed error response for the client - [{} - {}]", status, errReason);
  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
  response.headers().set(HttpHeaderNames.DATE, new GregorianCalendar().getTime());
  HttpUtil.setContentLength(response, 0);
  if (errReason != null) {
    response.headers().set(FAILURE_REASON_HEADER, errReason);
  }
  if (restServiceErrorCode != null && HttpStatusClass.CLIENT_ERROR.contains(status.code())) {
    response.headers().set(ERROR_CODE_HEADER, restServiceErrorCode.name());
  }
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
  // if there is an ALLOW header in the response so far constructed, copy it
  if (responseMetadata.headers().contains(HttpHeaderNames.ALLOW)) {
    response.headers().set(HttpHeaderNames.ALLOW, responseMetadata.headers().get(HttpHeaderNames.ALLOW));
  } else if (errorResponseStatus == ResponseStatus.MethodNotAllowed) {
    logger.warn("Response is {} but there is no value for {}", ResponseStatus.MethodNotAllowed,
        HttpHeaderNames.ALLOW);
  }
  copyTrackingHeaders(responseMetadata, response);
  HttpUtil.setKeepAlive(response, shouldKeepAlive(status));
  return response;
}
 
Example 16
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the common workflow of the {@link NettyResponseChannel} i.e., add some content to response body via
 * {@link NettyResponseChannel#write(ByteBuffer, Callback)} and then complete the response.
 * <p/>
 * These responses have the header Content-Length set.
 * @throws Exception
 */
@Test
public void responsesWithContentLengthTest() throws Exception {
  EmbeddedChannel channel = createEmbeddedChannel();
  MockNettyMessageProcessor processor = channel.pipeline().get(MockNettyMessageProcessor.class);
  final int ITERATIONS = 10;
  for (int i = 0; i < ITERATIONS; i++) {
    boolean isKeepAlive = i != (ITERATIONS - 1);
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(MockNettyMessageProcessor.CHUNK_COUNT_HEADER_NAME, i);
    HttpRequest httpRequest =
        RestTestUtils.createRequest(HttpMethod.POST, TestingUri.ResponseWithContentLength.toString(), httpHeaders);
    HttpUtil.setKeepAlive(httpRequest, isKeepAlive);
    channel.writeInbound(httpRequest);
    verifyCallbacks(processor);

    // first outbound has to be response.
    HttpResponse response = channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
    long contentLength = HttpUtil.getContentLength(response, -1);
    assertEquals("Unexpected Content-Length", MockNettyMessageProcessor.CHUNK.length * i, contentLength);
    if (contentLength == 0) {
      // special case. Since Content-Length is set, the response should be an instance of FullHttpResponse.
      assertTrue("Response not instance of FullHttpResponse", response instanceof FullHttpResponse);
    } else {
      HttpContent httpContent = null;
      for (int j = 0; j < i; j++) {
        httpContent = channel.readOutbound();
        byte[] returnedContent = new byte[httpContent.content().readableBytes()];
        httpContent.content().readBytes(returnedContent);
        httpContent.release();
        assertArrayEquals("Content does not match with expected content", MockNettyMessageProcessor.CHUNK,
            returnedContent);
      }
      // When we know the content-length, the last httpContent would be an instance of LastHttpContent and there is no
      // empty last http content following it.
      // the last HttpContent should also be an instance of LastHttpContent
      assertTrue("The last part of the content is not LastHttpContent", httpContent instanceof LastHttpContent);
    }
    assertEquals("Unexpected channel state on the server", isKeepAlive, channel.isActive());
  }
}
 
Example 17
Source File: DoradoServerHandler.java    From dorado with Apache License 2.0 4 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, Object msg) {
	FullHttpRequest request = (FullHttpRequest) msg;
	FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);

	boolean isKeepAlive = HttpUtil.isKeepAlive(request);
	HttpUtil.setKeepAlive(response, isKeepAlive);
	response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");
	response.headers().set(HttpHeaderNames.SERVER, "Dorado");

	ChannelFuture channelFuture = null;
	try {
		set(ctx.channel());
		HttpRequest _request = new HttpRequestImpl(request);
		HttpResponse _response = new HttpResponseImpl(response);

		Router router = webapp.getUriRoutingRegistry().findRouteController(_request);
		if (router == null) {
			response.setStatus(HttpResponseStatus.NOT_FOUND);
			ByteBufUtil.writeUtf8(response.content(),
					String.format("Resource not found, url: [%s], http_method: [%s]", _request.getRequestURI(),
							_request.getMethod()));
		} else {
			router.invoke(_request, _response);
		}
	} catch (Throwable ex) {
		LogUtils.error("handle http request error", ex);
		response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
		ByteBufUtil.writeUtf8(response.content(), ExceptionUtils.toString(ex));
	} finally {
		unset();
		if (isKeepAlive) {
			HttpUtil.setContentLength(response, response.content().readableBytes());
		}
		channelFuture = ctx.channel().writeAndFlush(response);
		if (!isKeepAlive && channelFuture != null) {
			channelFuture.addListener(ChannelFutureListener.CLOSE);
		}
		ReferenceCountUtil.release(msg);
		status.handledRequestsIncrement();
	}
}
 
Example 18
Source File: SpdyHttpDecoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static FullHttpRequest createHttpRequest(SpdyHeadersFrame requestFrame, ByteBufAllocator alloc)
   throws Exception {
    // Create the first line of the request from the name/value pairs
    SpdyHeaders headers     = requestFrame.headers();
    HttpMethod  method      = HttpMethod.valueOf(headers.getAsString(METHOD));
    String      url         = headers.getAsString(PATH);
    HttpVersion httpVersion = HttpVersion.valueOf(headers.getAsString(VERSION));
    headers.remove(METHOD);
    headers.remove(PATH);
    headers.remove(VERSION);

    boolean release = true;
    ByteBuf buffer = alloc.buffer();
    try {
        FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, url, buffer);

        // Remove the scheme header
        headers.remove(SCHEME);

        // Replace the SPDY host header with the HTTP host header
        CharSequence host = headers.get(HOST);
        headers.remove(HOST);
        req.headers().set(HttpHeaderNames.HOST, host);

        for (Map.Entry<CharSequence, CharSequence> e : requestFrame.headers()) {
            req.headers().add(e.getKey(), e.getValue());
        }

        // The Connection and Keep-Alive headers are no longer valid
        HttpUtil.setKeepAlive(req, true);

        // Transfer-Encoding header is not valid
        req.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
        release = false;
        return req;
    } finally {
        if (release) {
            buffer.release();
        }
    }
}
 
Example 19
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Translates and adds HTTP/2 request headers to HTTP/1.1 headers.
 *
 * @param inputHeaders the HTTP/2 request headers to convert.
 * @param outputHeaders the object which will contain the resulting HTTP/1.1 headers.
 */
public static void toNettyHttp1ClientHeader(
        HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders) {
    toNettyHttp1Client(inputHeaders, outputHeaders, false);
    HttpUtil.setKeepAlive(outputHeaders, HttpVersion.HTTP_1_1, true);
}
 
Example 20
Source File: ArmeriaHttpUtil.java    From armeria with Apache License 2.0 2 votes vote down vote up
/**
 * Translates and adds HTTP/2 response headers to HTTP/1.1 headers.
 *
 * @param inputHeaders the HTTP/2 response headers to convert.
 * @param outputHeaders the object which will contain the resulting HTTP/1.1 headers.
 */
public static void toNettyHttp1ServerHeader(
        HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders) {
    toNettyHttp1Server(inputHeaders, outputHeaders, false);
    HttpUtil.setKeepAlive(outputHeaders, HttpVersion.HTTP_1_1, true);
}