List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.barchart.netty.common.pipeline.WebSocketConnectedNotifier.java
License:BSD License
@Override public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception { if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE || evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { ctx.fireChannelActive();/*from ww w . j av a 2 s . co m*/ ctx.fireUserEventTriggered(evt); for (final Object msg : messages) ctx.fireChannelRead(msg); messages.clear(); ctx.pipeline().remove(this); } else { ctx.fireUserEventTriggered(evt); } }
From source file:com.barchart.netty.server.http.pipeline.HttpRequestChannelHandler.java
License:BSD License
private void handleWebSocket(final ChannelHandlerContext ctx, final FullHttpRequest msg) throws Exception { // Check if this path is a websocket final HandlerFactory<? extends ChannelHandler> factory = server.webSocketFactory(msg.getUri()); if (factory == null) { sendServerError(ctx, new ServerException(HttpResponseStatus.NOT_IMPLEMENTED, "Websocket upgrade not available at this path")); } else {/*www.j a v a 2s .co m*/ // TODO log request // server.logger().access(request, 0); ctx.pipeline().addLast( // Handshaker new WebSocketServerProtocolHandler(msg.getUri()), // Fires channelActive() after handshake and removes self new WebSocketConnectedNotifier(), // BinaryWebSocketFrame <-> ByteBuf codec before user codecs new WebSocketBinaryCodec(), // Handlers should add any other codecs they need to the // pipeline using their handlerAdded() method. factory.newHandler()); // Relay handshake to websocket handler ctx.fireChannelRead(msg); // Remove self from pipeline ctx.pipeline().remove(this); } }
From source file:com.barchart.netty.server.http.websocket.WebSocketHandler.java
License:BSD License
@Override public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { initializer.initPipeline(ctx.pipeline()); ctx.pipeline().remove(this); }
From source file:com.barchart.netty.server.pipeline.NegotiationHandler.java
License:BSD License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof Capabilities) { ctx.writeAndFlush(new Capabilities() { @Override/* ww w. ja v a 2 s . c o m*/ public Set<String> capabilities() { return capabilities; } @Override public Version version() { return version; } @Override public Version minVersion() { return minVersion; } }); } else if (msg instanceof VersionRequest) { final VersionRequest request = (VersionRequest) msg; final Version v = request.version(); if (minVersion.lessThanOrEqual(v) && version.greaterThanOrEqual(v)) { activeVersion = v; ctx.writeAndFlush(new VersionResponse() { @Override public boolean success() { return true; } @Override public Version version() { return v; } }); } else { ctx.writeAndFlush(new VersionResponse() { @Override public boolean success() { return false; } @Override public Version version() { return version; } }); } } else if (msg instanceof StartTLS) { // TODO Use a specific SSL cert? final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine(); sslEngine.setUseClientMode(false); final SslHandler handler = new SslHandler(sslEngine, true); handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { if (future.isSuccess()) { secure = true; } else { secure = false; // Failed, remove handler ctx.pipeline().remove(SslHandler.class); } } }); // Add SslHandler to pipeline ctx.pipeline().addFirst(handler); // Confirm start TLS, initiate handshake ctx.writeAndFlush(new StartTLS() { }); } else { ctx.fireChannelRead(msg); // First non-negotiation message, we're done - clean up pipeline if (cleanup) { ctx.pipeline().remove(this); if (linked != null) { for (final ChannelHandler handler : linked) { ctx.pipeline().remove(handler); } } } } }
From source file:com.barchart.netty.server.pipeline.StartTLSHandler.java
License:BSD License
@Override protected void channelRead0(final ChannelHandlerContext ctx, final StartTLS msg) throws Exception { // TODO Use a specific SSL cert? final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine(); sslEngine.setUseClientMode(false);//from w w w .j a v a2s .c om final SslHandler handler = new SslHandler(sslEngine, true); handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { if (future.isSuccess()) { secure = true; } else { secure = false; // Failed, remove handler ctx.pipeline().remove(SslHandler.class); } } }); // Add SslHandler to pipeline ctx.pipeline().addFirst(handler); // Confirm start TLS, initiate handshake ctx.writeAndFlush(new StartTLS() { }); }
From source file:com.bloom.zerofs.rest.NettyResponseChannel.java
License:Open Source License
/** * Create an instance of NettyResponseChannel that will use {@code ctx} to return responses. * @param ctx the {@link ChannelHandlerContext} to use. * @param nettyMetrics the {@link NettyMetrics} instance to use. */// w w w . j ava 2 s.c o m public NettyResponseChannel(ChannelHandlerContext ctx, NettyMetrics nettyMetrics) { this.ctx = ctx; this.nettyMetrics = nettyMetrics; chunkedWriteHandler = ctx.pipeline().get(ChunkedWriteHandler.class); writeFuture = ctx.newProgressivePromise(); logger.trace("Instantiated NettyResponseChannel"); }
From source file:com.cats.version.httpserver.HttpStaticFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// www .j ava 2 s. com return; } if (request.method() == POST) { new VersionProtocolMessageHandler().handleMessage(ctx, request); return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (new URLServiceFilter(uri, ctx, request).doFilte()) { return; } if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || (!file.exists() && (file = downloadSoftWare(file)) == null)) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (!HttpStaticVersionMonitorFileServer.OPEN_ACCESS) { sendWarningInfo(ctx); return; } if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().getAndConvert(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); HttpHeaderUtil.setContentLength(response, fileLength); response.headers().set("file_flag", "yes"); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaderUtil.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.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 (!HttpHeaderUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.chenyang.proxy.http.HttpSchemaHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; String originalHost = HostNamePortUtil.getHostName(httpRequest); int originalPort = HostNamePortUtil.getPort(httpRequest); HttpRemote apnProxyRemote = new HttpRemote(originalHost, originalPort); if (!HostAuthenticationUtil.isValidAddress(apnProxyRemote.getInetSocketAddress())) { HttpErrorUtil.writeAndFlush(uaChannelCtx.channel(), HttpResponseStatus.FORBIDDEN); return; }// w w w. j av a2 s. co m Channel uaChannel = uaChannelCtx.channel(); HttpConnectionAttribute apnProxyConnectionAttribute = HttpConnectionAttribute.build( uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(), httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote); uaChannelCtx.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) != null) { uaChannelCtx.pipeline().remove(HttpUserAgentForwardHandler.HANDLER_NAME); } if (uaChannelCtx.pipeline().get(HttpUserAgentTunnelHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentTunnelHandler.HANDLER_NAME, new HttpUserAgentTunnelHandler()); } } else { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentForwardHandler.HANDLER_NAME, new HttpUserAgentForwardHandler()); } } } uaChannelCtx.fireChannelRead(msg); }
From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { // Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel())); final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY) .get().getRemote();//from w ww . j ava2 s . c o m bootstrap .connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(HttpUserAgentTunnelHandler.HANDLER_NAME); uaChannelCtx.pipeline() .addLast(new HttpRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.chiorichan.http.ssl.SniNegotiator.java
License:Mozilla Public License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!handshaken && in.readableBytes() >= 5) { String hostname = sniHostNameFromHandshakeInfo(in); if (hostname != null) hostname = IDN.toASCII(hostname, IDN.ALLOW_UNASSIGNED).toLowerCase(Locale.US); this.hostname = hostname; selectedContext = SslManager.instance().map(hostname); if (handshaken) { SSLEngine engine = selectedContext.newEngine(ctx.alloc()); List<String> supportedCipherSuites = Arrays.asList(engine.getSupportedCipherSuites()); if (!supportedCipherSuites.containsAll(enabledCipherSuites)) for (String cipher : enabledCipherSuites) if (!supportedCipherSuites.contains(cipher)) { NetworkManager.getLogger() .severe(String.format( "The SSL/TLS cipher suite '%s' is not supported by SSL Provider %s", cipher, SslContext.defaultServerProvider().name())); enabledCipherSuites.remove(cipher); }//from w w w .j a v a 2 s . c om engine.setUseClientMode(false); engine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0])); ctx.pipeline().replace(this, ctx.name(), new SslExceptionHandler(engine)); } } }