Search in sources :

Example 51 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project brave by openzipkin.

the class TestHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
    if (msg instanceof HttpRequest) {
        req = (HttpRequest) msg;
        String path = req.uri();
        int queryIndex = path.indexOf('?');
        if (queryIndex != -1)
            path = path.substring(0, queryIndex);
        String content = null;
        HttpResponseStatus status = OK;
        if (path.equals("/") && req.method().equals(HttpMethod.OPTIONS)) {
            content = null;
        } else if (path.equals("/foo")) {
            content = "bar";
        } else if (path.equals("/baggage")) {
            content = BAGGAGE_FIELD.getValue();
        } else if (path.equals("/child")) {
            httpTracing.tracing().tracer().nextSpan().name("child").start().finish();
            content = "happy";
        } else if (path.equals("/exception")) {
            throw new IOException("exception");
        } else if (path.equals("/badrequest")) {
            status = BAD_REQUEST;
        } else {
            status = NOT_FOUND;
        }
        writeResponse(ctx, status, content);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException)

Example 52 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project ambry by linkedin.

the class NettyResponseChannel method getHttpResponseStatus.

/**
 * Converts a {@link ResponseStatus} into a {@link HttpResponseStatus}.
 * @param responseStatus {@link ResponseStatus} that needs to be mapped to a {@link HttpResponseStatus}.
 * @return the {@link HttpResponseStatus} that maps to the {@link ResponseStatus}.
 */
private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) {
    HttpResponseStatus status;
    switch(responseStatus) {
        case Ok:
            nettyMetrics.okCount.inc();
            status = HttpResponseStatus.OK;
            break;
        case Created:
            nettyMetrics.createdCount.inc();
            status = HttpResponseStatus.CREATED;
            break;
        case Accepted:
            nettyMetrics.acceptedCount.inc();
            status = HttpResponseStatus.ACCEPTED;
            break;
        case PartialContent:
            nettyMetrics.partialContentCount.inc();
            status = HttpResponseStatus.PARTIAL_CONTENT;
            break;
        case NotModified:
            nettyMetrics.notModifiedCount.inc();
            status = HttpResponseStatus.NOT_MODIFIED;
            break;
        case BadRequest:
            nettyMetrics.badRequestCount.inc();
            status = HttpResponseStatus.BAD_REQUEST;
            break;
        case Unauthorized:
            nettyMetrics.unauthorizedCount.inc();
            status = HttpResponseStatus.UNAUTHORIZED;
            break;
        case NotFound:
            nettyMetrics.notFoundCount.inc();
            status = HttpResponseStatus.NOT_FOUND;
            break;
        case Conflict:
            nettyMetrics.conflictCount.inc();
            status = HttpResponseStatus.CONFLICT;
            break;
        case Gone:
            nettyMetrics.goneCount.inc();
            status = HttpResponseStatus.GONE;
            break;
        case Forbidden:
            nettyMetrics.forbiddenCount.inc();
            status = HttpResponseStatus.FORBIDDEN;
            break;
        case ProxyAuthenticationRequired:
            nettyMetrics.proxyAuthRequiredCount.inc();
            status = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
            break;
        case RangeNotSatisfiable:
            nettyMetrics.rangeNotSatisfiableCount.inc();
            status = HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
            break;
        case TooManyRequests:
            nettyMetrics.tooManyRequests.inc();
            status = HttpResponseStatus.TOO_MANY_REQUESTS;
            break;
        case RequestTooLarge:
            nettyMetrics.requestTooLargeCount.inc();
            status = HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
            break;
        case InternalServerError:
            nettyMetrics.internalServerErrorCount.inc();
            status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
            break;
        case ServiceUnavailable:
            nettyMetrics.serviceUnavailableErrorCount.inc();
            status = HttpResponseStatus.SERVICE_UNAVAILABLE;
            break;
        case InsufficientCapacity:
            nettyMetrics.insufficientCapacityErrorCount.inc();
            status = HttpResponseStatus.INSUFFICIENT_STORAGE;
            break;
        case PreconditionFailed:
            nettyMetrics.preconditionFailedErrorCount.inc();
            status = HttpResponseStatus.PRECONDITION_FAILED;
            break;
        case MethodNotAllowed:
            nettyMetrics.methodNotAllowedErrorCount.inc();
            status = HttpResponseStatus.METHOD_NOT_ALLOWED;
            break;
        default:
            nettyMetrics.unknownResponseStatusCount.inc();
            status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
            break;
    }
    return status;
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

Example 53 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project ambry by linkedin.

the class HealthCheckHandlerTest method testHealthCheckRequest.

/**
 * 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();
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 54 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project ambry by linkedin.

the class MockChannelHandlerContext method errorResponseTest.

/**
 * Tests that error responses are correctly formed.
 */
@Test
public void errorResponseTest() {
    EmbeddedChannel channel = createEmbeddedChannel();
    for (RestServiceErrorCode errorCode : RestServiceErrorCode.values()) {
        for (boolean includeExceptionMessageInResponse : new boolean[] { true, false }) {
            HttpHeaders httpHeaders = new DefaultHttpHeaders();
            httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, errorCode);
            if (includeExceptionMessageInResponse) {
                httpHeaders.set(MockNettyMessageProcessor.INCLUDE_EXCEPTION_MESSAGE_IN_RESPONSE_HEADER_NAME, "true");
            }
            channel.writeInbound(RestTestUtils.createRequest(HttpMethod.HEAD, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders));
            HttpResponse response = channel.readOutbound();
            HttpResponseStatus expectedStatus = getExpectedHttpResponseStatus(errorCode);
            assertEquals("Unexpected response status", expectedStatus, response.status());
            boolean containsFailureReasonHeader = response.headers().contains(NettyResponseChannel.FAILURE_REASON_HEADER);
            if (expectedStatus == HttpResponseStatus.BAD_REQUEST || expectedStatus == HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE || includeExceptionMessageInResponse) {
                assertTrue("Could not find failure reason header.", containsFailureReasonHeader);
            } else {
                assertFalse("Should not have found failure reason header.", containsFailureReasonHeader);
            }
            if (HttpStatusClass.CLIENT_ERROR.contains(response.status().code())) {
                assertEquals("Wrong error code", errorCode, RestServiceErrorCode.valueOf(response.headers().get(NettyResponseChannel.ERROR_CODE_HEADER)));
            } else {
                assertFalse("Should not have found error code header", response.headers().contains(NettyResponseChannel.ERROR_CODE_HEADER));
            }
            if (expectedStatus == HttpResponseStatus.METHOD_NOT_ALLOWED) {
                assertEquals("Unexpected value for " + HttpHeaderNames.ALLOW, MockNettyMessageProcessor.METHOD_NOT_ALLOWED_ALLOW_HEADER_VALUE, response.headers().get(HttpHeaderNames.ALLOW));
            }
            if (response instanceof FullHttpResponse) {
                // assert that there is no content
                assertEquals("The response should not contain content", 0, ((FullHttpResponse) response).content().readableBytes());
            } else {
                HttpContent content = channel.readOutbound();
                assertTrue("End marker should be received", content instanceof LastHttpContent);
                content.release();
            }
            assertNull("There should be no more data in the channel", channel.readOutbound());
            boolean shouldBeAlive = !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(expectedStatus);
            assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive());
            assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpUtil.isKeepAlive(response));
            if (!shouldBeAlive) {
                channel = createEmbeddedChannel();
            }
        }
    }
    channel.close();
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 55 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project pinpoint by naver.

the class HttpClientOperationsOnInboundNextInterceptor method doInBeforeTrace.

@Override
public void doInBeforeTrace(SpanEventRecorder recorder, AsyncContext asyncContext, Object target, Object[] args) {
    final HttpResponse httpResponses = (HttpResponse) args[1];
    try {
        final HttpResponseStatus httpResponseStatus = httpResponses.status();
        if (httpResponseStatus != null) {
            recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, httpResponseStatus.code());
        }
        this.responseHeaderRecorder.recordHeader(recorder, httpResponses);
    } catch (Exception ignore) {
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Aggregations

HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)73 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)17 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)16 ByteBuf (io.netty.buffer.ByteBuf)15 HttpMethod (io.netty.handler.codec.http.HttpMethod)11 IOException (java.io.IOException)11 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)10 HttpResponse (io.netty.handler.codec.http.HttpResponse)10 HttpVersion (io.netty.handler.codec.http.HttpVersion)9 URI (java.net.URI)7 Test (org.junit.Test)7 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)6 URISyntaxException (java.net.URISyntaxException)6 Map (java.util.Map)6 Test (org.junit.jupiter.api.Test)6 Channel (io.netty.channel.Channel)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 HttpHeaderValues (io.netty.handler.codec.http.HttpHeaderValues)4 Duration (java.time.Duration)4 ArrayList (java.util.ArrayList)4