List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.heliosapm.tsdblite.handlers.http.HttpRequestManager.java
License:Apache License
/** * {@inheritDoc}/* www .java 2s .co m*/ * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object) */ @Override protected void channelRead0(final ChannelHandlerContext ctx, final HttpRequest msg) throws Exception { try { final String uri = msg.uri(); final Channel channel = ctx.channel(); if (uri.endsWith("/favicon.ico")) { final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, favicon); resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon"); resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize); ctx.writeAndFlush(resp); return; } else if (uri.equals("/api/put") || uri.equals("/api/metadata")) { final ChannelPipeline p = ctx.pipeline(); // p.addLast(loggingHandler, jsonAdapter, new JsonObjectDecoder(true), traceHandler); p.addLast(jsonAdapter, new JsonObjectDecoder(true), traceHandler); // if(msg instanceof FullHttpRequest) { // ByteBuf b = ((FullHttpRequest)msg).content().copy(); // ctx.fireChannelRead(b); // } ctx.fireChannelRead(msg); p.remove("requestManager"); log.info("Switched to JSON Trace Processor"); return; } final TSDBHttpRequest r = new TSDBHttpRequest(msg, ctx.channel(), ctx); final HttpRequestHandler handler = requestHandlers.get(r.getRoute()); if (handler == null) { r.send404().addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> f) throws Exception { log.info("404 Not Found for {} Complete: success: {}", r.getRoute(), f.isSuccess()); if (!f.isSuccess()) { log.error("Error sending 404", f.cause()); } }; }); return; } handler.process(r); } catch (Exception ex) { log.error("HttpRequest Routing Error", ex); } }
From source file:com.heliosapm.tsdblite.handlers.http.HttpStaticFileServerHandler.java
License:Open Source License
private void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*w w w . j av a2 s . c o m*/ return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri().replace("/api/s", "/"); final String path = uri; if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(staticRootDir, path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().getAsString(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) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } ctx.flush(); }
From source file:com.heliosapm.tsdblite.handlers.http.HttpSwitch.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final HttpRequest msg, final List<Object> out) throws Exception { final String uri = msg.uri(); log.info("-----------------------> URI [{}]", uri); if (uri.endsWith("/favicon.ico")) { final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, favicon); resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon"); resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize); ctx.writeAndFlush(resp);//from w w w . j a v a 2 s . c o m return; } ReferenceCountUtil.retain(msg); final ChannelPipeline p = ctx.pipeline(); final int index = uri.indexOf("/api/"); final String endpoint = index == -1 ? "" : uri.substring(5); if (index != -1 && pureJsonEndPoints.contains(endpoint)) { log.info("Switching to PureJSON handler"); p.addLast(eventExecutorGroup, "httpToJson", httpToJson); // p.addLast("jsonLogger", loggingHandler); p.addLast("jsonDecoder", new JsonObjectDecoder(true)); // p.addLast("jsonLogger", loggingHandler); p.addLast("traceHandler", traceHandler); p.remove(this); if (msg instanceof FullHttpMessage) { out.add(msg); } } else { log.info("Switching to Http Request Manager"); out.add(msg); p.addLast(eventExecutorGroup, "requestManager", HttpRequestManager.getInstance()); p.remove(this); } }
From source file:com.heliosapm.tsdblite.handlers.ProtocolSwitch.java
License:Apache License
private void enableGzip(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.pipeline(); p.addLast("gzipdeflater", ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP)); p.addLast("gzipinflater", ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); p.addLast("2ndPhaseSwitch", new ProtocolSwitch(false)); p.remove(this); log.info("enabled gzip: [{}]", ctx.channel().id()); }
From source file:com.heliosapm.tsdblite.handlers.ProtocolSwitch.java
License:Apache License
private void switchToHttp(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.pipeline(); //p.addLast("logging", loggingHandler); // p.addLast(new HttpObjectAggregator(1048576)); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast("httpCodec", sourceCodec); // HttpServerUpgradeHandler.UpgradeCodec upgradeCodec = new Http2ServerUpgradeCodec(new HelloWorldHttp2Handler()); // HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, Collections.singletonList(upgradeCodec), 65536); // p.addLast("http2Upgrader", upgradeHandler); // p.addLast("encoder", new HttpResponseEncoder()); // p.addLast("decoder", new HttpRequestDecoder()); // p.addLast("deflater", new HttpContentCompressor(1)); p.addLast("inflater", new HttpContentDecompressor()); //p.addLast("logging", loggingHandler); //p.addLast("encoder", new HttpResponseEncoder()); //p.addLast("logging", loggingHandler); // p.addLast("logging", loggingHandler); //WebSocketServerHandler //p.addLast(eventExecutorGroup, "requestManager", new WebSocketServerHandler()); p.addLast(new HttpObjectAggregator(1048576 * 2)); p.addLast("httpSwitch", HTTP_SWITCH); // p.addLast(eventExecutorGroup, "requestManager", HttpRequestManager.getInstance()); // p.addLast("requestManager", HttpRequestManager.getInstance()); p.remove(this); }
From source file:com.heliosapm.tsdblite.handlers.ProtocolSwitch.java
License:Apache License
private void switchToPlainText(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.pipeline(); p.addLast("framer", new LineBasedFrameDecoder(1024)); p.addLast("encoder", PLAINTEXT_ENCODER); p.addLast("decoder", PLAINTEXT_DECODER); p.addLast("traceDecoder", TRACE_DECODER); p.remove(this); log.info("switched to plain text: [{}]", ctx.channel().id()); }
From source file:com.heliosapm.webrpc.websocket.WebSocketServiceHandler.java
License:Apache License
/** * Processes an HTTP request//from www . ja v a 2s.co m * @param ctx The channel handler context * @param req The HTTP request */ public void handleRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) { log.warn("HTTP Request: {}", req); if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } String uri = req.uri(); if (!"/ws".equals(uri)) { //channelRead(ctx, req); final WebSocketServerProtocolHandler wsProto = ctx.pipeline().get(WebSocketServerProtocolHandler.class); if (wsProto != null) { try { wsProto.acceptInboundMessage(req); return; } catch (Exception ex) { log.error("Failed to dispatch http request to WebSocketServerProtocolHandler on channel [{}]", ctx.channel(), ex); } } } log.error("Failed to handle HTTP Request [{}] on channel [{}]", req, ctx.channel()); sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.MISDIRECTED_REQUEST)); }
From source file:com.hipishare.chat.server.handler.SecureChatHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. LOG.info("[]?channel"); SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); if (null != sslHandler) { sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override/* ww w .j a v a 2 s. com*/ public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { LOG.info("SSL??"); channels.add(ctx.channel()); } } }); } }
From source file:com.hop.hhxx.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*w w w. j a v a 2 s .c om*/ return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.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) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.hop.hhxx.example.http.websocketx.server.WebSocketIndexPageHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/*w w w . j a v a 2s . c om*/ } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = io.netty.example.http.websocketx.server.WebSocketServerIndexPage .getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } }