Search in sources :

Example 71 with HttpResponse

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

the class RuntimeMonitorHandlerBase method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, Routed routed) throws Exception {
    if (localJobManagerAddressFuture.isCompleted()) {
        if (localJobManagerAddress == null) {
            localJobManagerAddress = Await.result(localJobManagerAddressFuture, timeout);
        }
        Option<Tuple2<ActorGateway, Integer>> jobManager = retriever.getJobManagerGatewayAndWebPort();
        if (jobManager.isDefined()) {
            Tuple2<ActorGateway, Integer> gatewayPort = jobManager.get();
            String redirectAddress = HandlerRedirectUtils.getRedirectAddress(localJobManagerAddress, gatewayPort);
            if (redirectAddress != null) {
                HttpResponse redirect = HandlerRedirectUtils.getRedirectResponse(redirectAddress, routed.path(), httpsEnabled);
                KeepAliveWrite.flush(ctx, routed.request(), redirect);
            } else {
                respondAsLeader(ctx, routed, gatewayPort._1());
            }
        } else {
            KeepAliveWrite.flush(ctx, routed.request(), HandlerRedirectUtils.getUnavailableResponse());
        }
    } else {
        KeepAliveWrite.flush(ctx, routed.request(), HandlerRedirectUtils.getUnavailableResponse());
    }
}
Also used : Tuple2(scala.Tuple2) ActorGateway(org.apache.flink.runtime.instance.ActorGateway) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 72 with HttpResponse

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

the class StaticFileServerHandler method respondAsLeader.

/**
	 * Response when running with leading JobManager.
	 */
private void respondAsLeader(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException, URISyntaxException {
    // convert to absolute path
    final File file = new File(rootPath, requestPath);
    if (!file.exists()) {
        // file does not exist. Try to load it with the classloader
        ClassLoader cl = StaticFileServerHandler.class.getClassLoader();
        try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
            boolean success = false;
            try {
                if (resourceStream != null) {
                    URL root = cl.getResource("web");
                    URL requested = cl.getResource("web" + requestPath);
                    if (root != null && requested != null) {
                        URI rootURI = new URI(root.getPath()).normalize();
                        URI requestedURI = new URI(requested.getPath()).normalize();
                        // expected scope.
                        if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
                            logger.debug("Loading missing file from classloader: {}", requestPath);
                            // ensure that directory to file exists.
                            file.getParentFile().mkdirs();
                            Files.copy(resourceStream, file.toPath());
                            success = true;
                        }
                    }
                }
            } catch (Throwable t) {
                logger.error("error while responding", t);
            } finally {
                if (!success) {
                    logger.debug("Unable to load requested file {} from classloader", requestPath);
                    sendError(ctx, NOT_FOUND);
                    return;
                }
            }
        }
    }
    if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (!file.getCanonicalFile().toPath().startsWith(rootPath.toPath())) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    // cache validation
    final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            if (logger.isDebugEnabled()) {
                logger.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
            }
            sendNotModified(ctx);
            return;
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Responding with file '" + file.getAbsolutePath() + '\'');
    }
    // Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentTypeHeader(response, file);
    // since the log and out files are rapidly changing, we don't want to browser to cache them
    if (!(requestPath.contains("log") || requestPath.contains("out"))) {
        setDateAndCacheHeaders(response, file);
    }
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    HttpHeaders.setContentLength(response, fileLength);
    // write the initial line and the header.
    ctx.write(response);
    // write the content.
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
    // HttpChunkedInput will write the end marker (LastHttpContent) for us.
    }
    // close the connection, if no keep-alive is needed
    if (!HttpHeaders.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InputStream(java.io.InputStream) ChunkedFile(io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFileRegion(io.netty.channel.DefaultFileRegion) URI(java.net.URI) URL(java.net.URL) Date(java.util.Date) SslHandler(io.netty.handler.ssl.SslHandler) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) ChunkedFile(io.netty.handler.stream.ChunkedFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 73 with HttpResponse

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

the class ConstantTextHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, Routed routed) throws Exception {
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(encodedText));
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, encodedText.length);
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    KeepAliveWrite.flush(ctx, routed.request(), response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 74 with HttpResponse

use of io.netty.handler.codec.http.HttpResponse in project netty by netty.

the class RtspEncoder method encodeInitialLine.

@Override
protected void encodeInitialLine(final ByteBuf buf, final HttpMessage message) throws Exception {
    if (message instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) message;
        HttpHeaders.encodeAscii(request.method().toString(), buf);
        buf.writeByte(SP);
        buf.writeBytes(request.uri().getBytes(CharsetUtil.UTF_8));
        buf.writeByte(SP);
        HttpHeaders.encodeAscii(request.protocolVersion().toString(), buf);
        buf.writeBytes(CRLF);
    } else if (message instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) message;
        HttpHeaders.encodeAscii(response.protocolVersion().toString(), buf);
        buf.writeByte(SP);
        buf.writeBytes(String.valueOf(response.status().code()).getBytes(CharsetUtil.US_ASCII));
        buf.writeByte(SP);
        HttpHeaders.encodeAscii(String.valueOf(response.status().reasonPhrase()), buf);
        buf.writeBytes(CRLF);
    } else {
        throw new UnsupportedMessageTypeException("Unsupported type " + StringUtil.simpleClassName(message));
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpResponse(io.netty.handler.codec.http.HttpResponse) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException)

Example 75 with HttpResponse

use of io.netty.handler.codec.http.HttpResponse in project netty by netty.

the class SpdyHttpEncoder method encode.

@Override
protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    boolean valid = false;
    boolean last = false;
    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;
        SpdySynStreamFrame spdySynStreamFrame = createSynStreamFrame(httpRequest);
        out.add(spdySynStreamFrame);
        last = spdySynStreamFrame.isLast() || spdySynStreamFrame.isUnidirectional();
        valid = true;
    }
    if (msg instanceof HttpResponse) {
        HttpResponse httpResponse = (HttpResponse) msg;
        SpdyHeadersFrame spdyHeadersFrame = createHeadersFrame(httpResponse);
        out.add(spdyHeadersFrame);
        last = spdyHeadersFrame.isLast();
        valid = true;
    }
    if (msg instanceof HttpContent && !last) {
        HttpContent chunk = (HttpContent) msg;
        chunk.content().retain();
        SpdyDataFrame spdyDataFrame = new DefaultSpdyDataFrame(currentStreamId, chunk.content());
        if (chunk instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) chunk;
            HttpHeaders trailers = trailer.trailingHeaders();
            if (trailers.isEmpty()) {
                spdyDataFrame.setLast(true);
                out.add(spdyDataFrame);
            } else {
                // Create SPDY HEADERS frame out of trailers
                SpdyHeadersFrame spdyHeadersFrame = new DefaultSpdyHeadersFrame(currentStreamId, validateHeaders);
                spdyHeadersFrame.setLast(true);
                Iterator<Entry<CharSequence, CharSequence>> itr = trailers.iteratorCharSequence();
                while (itr.hasNext()) {
                    Map.Entry<CharSequence, CharSequence> entry = itr.next();
                    final CharSequence headerName = headersToLowerCase ? AsciiString.of(entry.getKey()).toLowerCase() : entry.getKey();
                    spdyHeadersFrame.headers().add(headerName, entry.getValue());
                }
                // Write DATA frame and append HEADERS frame
                out.add(spdyDataFrame);
                out.add(spdyHeadersFrame);
            }
        } else {
            out.add(spdyDataFrame);
        }
        valid = true;
    }
    if (!valid) {
        throw new UnsupportedMessageTypeException(msg);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponse(io.netty.handler.codec.http.HttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) Entry(java.util.Map.Entry) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException)

Aggregations

HttpResponse (io.netty.handler.codec.http.HttpResponse)127 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)57 Test (org.junit.Test)50 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)30 HttpRequest (io.netty.handler.codec.http.HttpRequest)27 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)26 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)24 HttpContent (io.netty.handler.codec.http.HttpContent)18 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)18 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)14 ChannelFuture (io.netty.channel.ChannelFuture)12 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)12 ByteBuf (io.netty.buffer.ByteBuf)10 AsciiString (io.netty.util.AsciiString)9 HttpObject (io.netty.handler.codec.http.HttpObject)7 Map (java.util.Map)7 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)7 WebSocketExtensionData (io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionData)6 IOException (java.io.IOException)6 Settings (org.elasticsearch.common.settings.Settings)6