Search in sources :

Example 6 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project ambry by linkedin.

the class ChannelWriteCallback method errorResponseTest.

/**
 * Tests that error responses are correctly formed.
 */
@Test
public void errorResponseTest() {
    EmbeddedChannel channel = createEmbeddedChannel();
    for (RestServiceErrorCode errorCode : RestServiceErrorCode.values()) {
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, errorCode);
        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) {
            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 (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);
        }
        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) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) 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) UtilsTest(com.github.ambry.utils.UtilsTest) Test(org.junit.Test)

Example 7 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project java by wavefrontHQ.

the class OpenTSDBPortUnificationHandler method handleHttpMessage.

/**
 * Handles an incoming HTTP message.  The currently supported paths are:
 * {@link <ahref="http://opentsdb.net/docs/build/html/api_http/put.html">/api/put</a>}
 * {@link <ahref="http://opentsdb.net/docs/build/html/api_http/version.html">/api/version</a>},
 *
 * @throws IOException        when reading contents of HTTP body fails
 * @throws URISyntaxException when the request URI cannot be parsed
 */
private void handleHttpMessage(final ChannelHandlerContext ctx, final Object message) {
    final FullHttpRequest request = (FullHttpRequest) message;
    URI uri;
    try {
        uri = new URI(request.uri());
    } catch (URISyntaxException e) {
        String errMsg = createErrMsg(e);
        writeHttpResponse(request, ctx, HttpResponseStatus.BAD_REQUEST, errMsg);
        blockMessage("WF-300", "Request URI, '" + request.uri() + "' cannot be parsed", e, ctx);
        return;
    }
    if (uri.getPath().equals("/api/put")) {
        final ObjectMapper jsonTree = new ObjectMapper();
        HttpResponseStatus status;
        String content = "";
        // were stored successfully. If one or more data points had an error, the API will return a 400.
        try {
            if (reportMetrics(jsonTree.readTree(request.content().toString(CharsetUtil.UTF_8)))) {
                status = HttpResponseStatus.NO_CONTENT;
            } else {
                // TODO: improve error message
                // http://opentsdb.net/docs/build/html/api_http/put.html#response
                // User should understand that successful points are processed and the reason for BAD_REQUEST
                // is due to at least one failure point.
                status = HttpResponseStatus.BAD_REQUEST;
                content = "At least one data point had error.";
            }
        } catch (Exception e) {
            status = HttpResponseStatus.BAD_REQUEST;
            if (e != null) {
                content = createErrMsg(e);
            }
            blockMessage("WF-300", "Failed to handle /api/put request", e, ctx);
        }
        writeHttpResponse(request, ctx, status, content);
    } else if (uri.getPath().equals("/api/version")) {
        writeHttpResponse(request, ctx, HttpResponseStatus.OK, // TODO: should be a JSON response object (see docs)
        "Wavefront OpenTSDB Endpoint");
    // http://opentsdb.net/docs/build/html/api_http/version.html
    } else {
        writeHttpResponse(request, ctx, HttpResponseStatus.BAD_REQUEST, "Unsupported path");
        blockMessage("WF-300", "Unexpected path '" + request.uri() + "'", null, ctx);
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 8 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project wso2-synapse by wso2.

the class MockServiceCreator method routeThroughResourceMethod.

/**
 * Start service for given parameters using emulator.
 *
 * @param resource mock service resource data
 * @param emulator HttpConsumerContext emulator object
 */
private static void routeThroughResourceMethod(ServiceResource resource, HttpConsumerContext emulator) {
    int serviceResponseStatusCode = resource.getStatusCode();
    HttpResponseStatus responseStatus = HttpResponseStatus.valueOf(serviceResponseStatusCode);
    String serviceMethod = resource.getMethod();
    String serviceSubContext = resource.getSubContext();
    Map.Entry<String, Map<String, String>> checkQueryParamEntry = splitQueryParams(serviceSubContext);
    serviceSubContext = checkQueryParamEntry.getKey();
    Map<String, String> queryParams = checkQueryParamEntry.getValue();
    String serviceRequestPayload = "";
    if (resource.getRequestPayload() != null) {
        serviceRequestPayload = RequestProcessor.trimStrings(resource.getRequestPayload());
    }
    String serviceResponsePayload = resource.getResponsePayload();
    List<Map.Entry<String, String>> requestHeaders = new ArrayList<>();
    List<Map.Entry<String, String>> responseHeaders = new ArrayList<>();
    if (resource.getRequestHeaders() != null) {
        requestHeaders = resource.getRequestHeaders();
    }
    if (resource.getResponseHeaders() != null) {
        responseHeaders = resource.getResponseHeaders();
    }
    switch(serviceMethod.toUpperCase()) {
        case GET_METHOD:
            // adding headers of request
            IncomingMessage incomingMessage = request().withMethod(HttpMethod.GET).withPath(serviceSubContext);
            for (Map.Entry<String, String> queryParam : queryParams.entrySet()) {
                incomingMessage.withQueryParameter(queryParam.getKey(), queryParam.getValue());
            }
            for (Map.Entry<String, String> header : requestHeaders) {
                incomingMessage.withHeader(header.getKey(), header.getValue());
            }
            emulator.when(incomingMessage);
            // adding headers of response
            OutgoingMessage outGoingMessage = response().withBody(serviceResponsePayload).withStatusCode(responseStatus);
            for (Map.Entry<String, String> header : responseHeaders) {
                outGoingMessage.withHeader(header.getKey(), header.getValue());
            }
            emulator.respond(outGoingMessage);
            break;
        case POST_METHOD:
            // adding headers of request
            incomingMessage = request().withMethod(HttpMethod.POST).withBody(serviceRequestPayload).withPath(serviceSubContext);
            for (Map.Entry<String, String> queryParam : queryParams.entrySet()) {
                incomingMessage.withQueryParameter(queryParam.getKey(), queryParam.getValue());
            }
            for (Map.Entry<String, String> header : requestHeaders) {
                incomingMessage.withHeader(header.getKey(), header.getValue());
            }
            emulator.when(incomingMessage);
            // adding headers of response
            outGoingMessage = response().withBody(serviceResponsePayload).withStatusCode(responseStatus);
            for (Map.Entry<String, String> header : responseHeaders) {
                outGoingMessage.withHeader(header.getKey(), header.getValue());
            }
            emulator.respond(outGoingMessage);
            break;
        default:
            // adding headers of request
            incomingMessage = request().withMethod(HttpMethod.GET).withPath(serviceSubContext);
            for (Map.Entry<String, String> queryParam : queryParams.entrySet()) {
                incomingMessage.withQueryParameter(queryParam.getKey(), queryParam.getValue());
            }
            for (Map.Entry<String, String> header : requestHeaders) {
                incomingMessage.withHeader(header.getKey(), header.getValue());
            }
            emulator.when(incomingMessage);
            // adding headers of response
            outGoingMessage = response().withBody(serviceResponsePayload).withStatusCode(responseStatus);
            for (Map.Entry<String, String> header : responseHeaders) {
                outGoingMessage.withHeader(header.getKey(), header.getValue());
            }
            emulator.respond(outGoingMessage);
            break;
    }
}
Also used : OutgoingMessage(org.apache.synapse.commons.emulator.http.dsl.dto.consumer.OutgoingMessage) IncomingMessage(org.apache.synapse.commons.emulator.http.dsl.dto.consumer.IncomingMessage) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) AbstractMap(java.util.AbstractMap) Map(java.util.Map)

Example 9 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project wso2-synapse by wso2.

the class HttpResponseProcessor method writeResponse.

private boolean writeResponse(HttpRequestContext requestContext, OutgoingMessage outgoing, ChannelHandlerContext ctx) {
    boolean keepAlive = requestContext.isKeepAlive();
    HttpVersion httpVersion = consumerContext.getHttpVersion();
    HttpResponseStatus httpResponseStatus = outgoing.getStatusCode();
    FullHttpResponse response = new DefaultFullHttpResponse(httpVersion, httpResponseStatus, Unpooled.copiedBuffer(outgoing.getBody(), CharsetUtil.UTF_8));
    populateHttpHeaders(response, outgoing);
    populateCookies(response, outgoing);
    if (!keepAlive) {
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        ctx.write(response);
    }
    return keepAlive;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 10 with HttpResponseStatus

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus in project wso2-synapse by wso2.

the class HttpRequestWorker method sendAck.

/**
 * Sends a HTTP response to the client immediately after the current execution thread finishes, if the
 * 1. FORCE_SC_ACCEPTED property is true or
 * 2. A response is not written and no FORCE_SOAP_FAULT property is set or
 * 3. NIO-ACK-Requested property is set to true or
 * 4. RequestResponseTransportStatus is set to ACKED.
 */
private void sendAck() {
    if (ackShouldSend()) {
        int statusCode;
        HttpResponseStatus responseStatus;
        if (!nioAckRequested()) {
            statusCode = HttpStatus.SC_ACCEPTED;
            responseStatus = HttpResponseStatus.ACCEPTED;
        } else {
            statusCode = Integer.parseInt(msgContext.getProperty(NhttpConstants.HTTP_SC).toString());
            responseStatus = HttpResponseStatus.valueOf(statusCode);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending ACK response with status " + statusCode + ", for MessageID : " + msgContext.getMessageID());
        }
        sendResponse(statusCode, responseStatus, false, false, null, null);
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

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 Map (java.util.Map)8 URI (java.net.URI)7 Test (org.junit.Test)7 URISyntaxException (java.net.URISyntaxException)6 Test (org.junit.jupiter.api.Test)6 Channel (io.netty.channel.Channel)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)5 Duration (java.time.Duration)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4