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());
}
}
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);
}
}
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);
}
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));
}
}
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);
}
}
Aggregations