Search in sources :

Example 1 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project flink by apache.

the class HttpRequestHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    try {
        if (msg instanceof HttpRequest) {
            currentRequest = (HttpRequest) msg;
            currentRequestPath = null;
            if (currentDecoder != null) {
                currentDecoder.destroy();
                currentDecoder = null;
            }
            if (currentRequest.getMethod() == HttpMethod.GET || currentRequest.getMethod() == HttpMethod.DELETE) {
                // directly delegate to the router
                ctx.fireChannelRead(currentRequest);
            } else if (currentRequest.getMethod() == HttpMethod.POST) {
                // POST comes in multiple objects. First the request, then the contents
                // keep the request and path for the remaining objects of the POST request
                currentRequestPath = new QueryStringDecoder(currentRequest.getUri(), ENCODING).path();
                currentDecoder = new HttpPostRequestDecoder(DATA_FACTORY, currentRequest, ENCODING);
            } else {
                throw new IOException("Unsupported HTTP method: " + currentRequest.getMethod().name());
            }
        } else if (currentDecoder != null && msg instanceof HttpContent) {
            // received new chunk, give it to the current decoder
            HttpContent chunk = (HttpContent) msg;
            currentDecoder.offer(chunk);
            try {
                while (currentDecoder.hasNext()) {
                    InterfaceHttpData data = currentDecoder.next();
                    if (data.getHttpDataType() == HttpDataType.FileUpload) {
                        DiskFileUpload file = (DiskFileUpload) data;
                        if (file.isCompleted()) {
                            String name = file.getFilename();
                            File target = new File(tmpDir, UUID.randomUUID() + "_" + name);
                            file.renameTo(target);
                            QueryStringEncoder encoder = new QueryStringEncoder(currentRequestPath);
                            encoder.addParam("filepath", target.getAbsolutePath());
                            encoder.addParam("filename", name);
                            currentRequest.setUri(encoder.toString());
                        }
                    }
                    data.release();
                }
            } catch (EndOfDataDecoderException ignored) {
            }
            if (chunk instanceof LastHttpContent) {
                HttpRequest request = currentRequest;
                currentRequest = null;
                currentRequestPath = null;
                currentDecoder.destroy();
                currentDecoder = null;
                // fire next channel handler
                ctx.fireChannelRead(request);
            }
        }
    } catch (Throwable t) {
        currentRequest = null;
        currentRequestPath = null;
        if (currentDecoder != null) {
            currentDecoder.destroy();
            currentDecoder = null;
        }
        if (ctx.channel().isActive()) {
            byte[] bytes = ExceptionUtils.stringifyException(t).getBytes(ENCODING);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes));
            response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) EndOfDataDecoderException(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDecoderException) IOException(java.io.IOException) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) DiskFileUpload(io.netty.handler.codec.http.multipart.DiskFileUpload) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) File(java.io.File) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder)

Example 2 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project flink by apache.

the class PipelineErrorHandler method sendError.

private void sendError(ChannelHandlerContext ctx, String error) {
    if (ctx.channel().isActive()) {
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(error.getBytes(ConfigConstants.DEFAULT_CHARSET)));
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        ctx.writeAndFlush(response);
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 3 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project flink by apache.

the class RuntimeMonitorHandler method respondAsLeader.

@Override
protected void respondAsLeader(ChannelHandlerContext ctx, Routed routed, ActorGateway jobManager) {
    FullHttpResponse response;
    try {
        // we only pass the first element in the list to the handlers.
        Map<String, String> queryParams = new HashMap<>();
        for (String key : routed.queryParams().keySet()) {
            queryParams.put(key, routed.queryParam(key));
        }
        Map<String, String> pathParams = new HashMap<>(routed.pathParams().size());
        for (String key : routed.pathParams().keySet()) {
            pathParams.put(key, URLDecoder.decode(routed.pathParams().get(key), ENCODING.toString()));
        }
        InetSocketAddress address = (InetSocketAddress) ctx.channel().localAddress();
        queryParams.put(WEB_MONITOR_ADDRESS_KEY, (httpsEnabled ? "https://" : "http://") + address.getHostName() + ":" + address.getPort());
        response = handler.handleRequest(pathParams, queryParams, jobManager);
    } catch (NotFoundException e) {
        // this should result in a 404 error code (not found)
        ByteBuf message = e.getMessage() == null ? Unpooled.buffer(0) : Unpooled.wrappedBuffer(e.getMessage().getBytes(ENCODING));
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, message);
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        LOG.debug("Error while handling request", e);
    } catch (Exception e) {
        byte[] bytes = ExceptionUtils.stringifyException(e).getBytes(ENCODING);
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes));
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        LOG.debug("Error while handling request", e);
    }
    response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    // Content-Encoding:utf-8
    response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, ENCODING.name());
    KeepAliveWrite.flush(ctx, routed.request(), response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 4 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project flink by apache.

the class HandlerRedirectUtils method getUnavailableResponse.

public static HttpResponse getUnavailableResponse() {
    String result = "Service temporarily unavailable due to an ongoing leader election. Please refresh.";
    byte[] bytes = result.getBytes(ConfigConstants.DEFAULT_CHARSET);
    HttpResponse unavailableResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(bytes));
    unavailableResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, bytes.length);
    unavailableResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, MimeTypes.getMimeTypeForExtension("txt"));
    return unavailableResponse;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 5 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project flink by apache.

the class HandlerRedirectUtils method getRedirectResponse.

public static HttpResponse getRedirectResponse(String redirectAddress, String path, boolean httpsEnabled) throws Exception {
    checkNotNull(redirectAddress, "Redirect address");
    checkNotNull(path, "Path");
    String protocol = httpsEnabled ? "https" : "http";
    String newLocation = String.format("%s://%s%s", protocol, redirectAddress, path);
    HttpResponse redirectResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
    redirectResponse.headers().set(HttpHeaders.Names.LOCATION, newLocation);
    redirectResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
    return redirectResponse;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Aggregations

DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)72 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)44 ByteBuf (io.netty.buffer.ByteBuf)27 HttpResponse (io.netty.handler.codec.http.HttpResponse)10 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)8 Test (org.junit.Test)7 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)5 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 ChannelFuture (io.netty.channel.ChannelFuture)4 IOException (java.io.IOException)4 Map (java.util.Map)4 HttpContent (io.netty.handler.codec.http.HttpContent)3 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)3 File (java.io.File)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 FullHttpMessage (io.netty.handler.codec.http.FullHttpMessage)2