Search in sources :

Example 66 with HttpResponseStatus

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

the class HandlerUtils method sendResponse.

/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param keepAlive If the connection should be kept alive.
 * @param message which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 */
public static CompletableFuture<Void> sendResponse(@Nonnull ChannelHandlerContext channelHandlerContext, boolean keepAlive, @Nonnull String message, @Nonnull HttpResponseStatus statusCode, @Nonnull Map<String, String> headers) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode);
    response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);
    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
        response.headers().set(headerEntry.getKey(), headerEntry.getValue());
    }
    if (keepAlive) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET);
    ByteBuf b = Unpooled.copiedBuffer(buf);
    HttpHeaders.setContentLength(response, buf.length);
    // write the initial line and the header.
    channelHandlerContext.write(response);
    channelHandlerContext.write(b);
    ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    // close the connection, if no keep-alive is needed
    if (!keepAlive) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
    return toCompletableFuture(lastContentFuture);
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) Map(java.util.Map)

Example 67 with HttpResponseStatus

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

the class HttpBlobHandler method writeToFile.

private void writeToFile(HttpRequest request, ByteBuf input, boolean last, final boolean continueExpected) throws IOException {
    if (digestBlob == null) {
        throw new IllegalStateException("digestBlob is null in writeToFile");
    }
    RemoteDigestBlob.Status status = digestBlob.addContent(input, last);
    HttpResponseStatus exitStatus = null;
    switch(status) {
        case FULL:
            exitStatus = HttpResponseStatus.CREATED;
            break;
        case PARTIAL:
            // tell the client to continue
            if (continueExpected) {
                ctx.write(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.CONTINUE));
            }
            return;
        case MISMATCH:
            exitStatus = HttpResponseStatus.BAD_REQUEST;
            break;
        case EXISTS:
            exitStatus = HttpResponseStatus.CONFLICT;
            break;
        case FAILED:
            exitStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
            break;
        default:
            throw new IllegalArgumentException("Unknown status: " + status);
    }
    assert exitStatus != null : "exitStatus should not be null";
    LOGGER.trace("writeToFile exit status http:{} blob: {}", exitStatus, status);
    simpleResponse(request, exitStatus);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) RemoteDigestBlob(io.crate.blob.RemoteDigestBlob) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

Example 68 with HttpResponseStatus

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

the class ZipkinPortUnificationHandler method handleHttpMessage.

@Override
protected void handleHttpMessage(final ChannelHandlerContext ctx, final FullHttpRequest request) throws URISyntaxException {
    URI uri = new URI(request.uri());
    String path = uri.getPath().endsWith("/") ? uri.getPath() : uri.getPath() + "/";
    // Validate Uri Path and HTTP method of incoming Zipkin spans.
    if (!ZIPKIN_VALID_PATHS.contains(path)) {
        writeHttpResponse(ctx, HttpResponseStatus.BAD_REQUEST, "Unsupported URL path.", request);
        logWarning("Requested URI path '" + path + "' is not supported.", null, ctx);
        return;
    }
    if (!request.method().toString().equalsIgnoreCase(ZIPKIN_VALID_HTTP_METHOD)) {
        writeHttpResponse(ctx, HttpResponseStatus.BAD_REQUEST, "Unsupported Http method.", request);
        logWarning("Requested http method '" + request.method().toString() + "' is not supported.", null, ctx);
        return;
    }
    HttpResponseStatus status;
    StringBuilder output = new StringBuilder();
    try {
        byte[] bytesArray = new byte[request.content().nioBuffer().remaining()];
        request.content().nioBuffer().get(bytesArray, 0, bytesArray.length);
        BytesDecoder<zipkin2.Span> decoder = SpanBytesDecoderDetector.decoderForListMessage(bytesArray);
        List<zipkin2.Span> zipkinSpanSink = new ArrayList<>();
        decoder.decodeList(bytesArray, zipkinSpanSink);
        // Handle case when tracing is disabled, ignore reported spans.
        if (isFeatureDisabled(traceDisabled, SPAN_DISABLED, discardedBatches, output)) {
            status = HttpResponseStatus.ACCEPTED;
            writeHttpResponse(ctx, status, output, request);
            discardedTraces.inc(zipkinSpanSink.size());
            receivedSpansTotal.inc(zipkinSpanSink.size());
            processedBatches.inc();
            return;
        }
        receivedSpansTotal.inc(zipkinSpanSink.size());
        processZipkinSpans(zipkinSpanSink);
        status = HttpResponseStatus.ACCEPTED;
        processedBatches.inc();
    } catch (Exception e) {
        failedBatches.inc();
        output.append(errorMessageWithRootCause(e));
        status = HttpResponseStatus.BAD_REQUEST;
        logger.log(Level.WARNING, "Zipkin batch processing failed", Throwables.getRootCause(e));
    }
    writeHttpResponse(ctx, status, output, request);
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ArrayList(java.util.ArrayList) URI(java.net.URI) Span(wavefront.report.Span) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 69 with HttpResponseStatus

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

the class WriteHttpJsonPortUnificationHandler method handleHttpMessage.

@Override
protected void handleHttpMessage(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    HttpResponseStatus status = HttpResponseStatus.OK;
    String requestBody = request.content().toString(CharsetUtil.UTF_8);
    try {
        JsonNode metrics = jsonParser.readTree(requestBody);
        if (!metrics.isArray()) {
            logger.warning("metrics is not an array!");
            pointHandler.reject((ReportPoint) null, "[metrics] is not an array!");
            status = HttpResponseStatus.BAD_REQUEST;
            writeHttpResponse(ctx, status, "", request);
            return;
        }
        reportMetrics(metrics);
        writeHttpResponse(ctx, status, "", request);
    } catch (Exception e) {
        status = HttpResponseStatus.BAD_REQUEST;
        logWarning("WF-300: Failed to handle incoming write_http request", e, ctx);
        writeHttpResponse(ctx, status, errorMessageWithRootCause(e), request);
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 70 with HttpResponseStatus

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

the class AbstractLineDelimitedHandler method handleHttpMessage.

/**
 * Handles an incoming HTTP message. Accepts HTTP POST on all paths
 */
@Override
protected void handleHttpMessage(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    StringBuilder output = new StringBuilder();
    HttpResponseStatus status;
    try {
        DataFormat format = getFormat(request);
        Splitter.on('\n').trimResults().omitEmptyStrings().split(request.content().toString(CharsetUtil.UTF_8)).forEach(line -> processLine(ctx, line, format));
        status = HttpResponseStatus.ACCEPTED;
    } catch (Exception e) {
        status = HttpResponseStatus.BAD_REQUEST;
        output.append(errorMessageWithRootCause(e));
        logWarning("WF-300: Failed to handle HTTP POST", e, ctx);
    }
    writeHttpResponse(ctx, status, output, request);
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DataFormat(com.wavefront.agent.formatter.DataFormat)

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