List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.shbxs.netty.SecureChatServerHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) {//? // System.out.println("channelactive!"); // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. //??/*from w ww. j a v a2s .c o m*/ ctx.pipeline().get(SslHandler.class).handshakeFuture() .addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush("Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); } }); }
From source file:com.shun.liu.quickserver.socksproxy.SocksServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, SocksMessage socksRequest) throws Exception { switch (socksRequest.version()) { case SOCKS4a: Socks4CommandRequest socksV4CmdRequest = (Socks4CommandRequest) socksRequest; if (socksV4CmdRequest.type() == Socks4CommandType.CONNECT) { ctx.pipeline().addLast(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else {/*w w w . jav a 2 s. com*/ ctx.close(); } break; case SOCKS5: if (socksRequest instanceof Socks5InitialRequest) { // auth support example // ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder()); // ctx.write(new DefaultSocks5AuthMethodResponse(Socks5AuthMethod.PASSWORD)); ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH)); } else if (socksRequest instanceof Socks5PasswordAuthRequest) { ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS)); } else if (socksRequest instanceof Socks5CommandRequest) { Socks5CommandRequest socks5CmdRequest = (Socks5CommandRequest) socksRequest; if (socks5CmdRequest.type() == Socks5CommandType.CONNECT) { ctx.pipeline().addLast(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }
From source file:com.slyak.services.proxy.handler.Socks5CommandRequestHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext requestChannelContext, final DefaultSocks5CommandRequest msg) throws Exception { if (Socks5CommandType.CONNECT.equals(msg.type())) { log.debug("Start to connect remote server : {}:{}", msg.dstAddr(), msg.dstPort()); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(remoteEventLoopGroup).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override/* w w w .j a v a 2 s. c om*/ protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(0, 0, 30)); pipeline.addLast(new IdleEventHandler()); pipeline.addLast(new Remote2RequestHandler(requestChannelContext.channel())); pipeline.addLast(ExceptionHandler.INSTANCE); } }); final ChannelFuture future = bootstrap.connect(msg.dstAddr(), msg.dstPort()); this.remoteChannel = future.channel(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture connectFuture) throws Exception { if (connectFuture.isSuccess()) { log.debug("Connected to remote server"); requestChannelContext.pipeline().addLast(new Request2RemoteHandler(remoteChannel)); Socks5CommandResponse response = new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, Socks5AddressType.IPv4); //add client to dest handler to receive response requestChannelContext.writeAndFlush(response); } else { log.debug("Failed to connect to remote server"); Socks5CommandResponse commandResponse = new DefaultSocks5CommandResponse( Socks5CommandStatus.FAILURE, Socks5AddressType.IPv4); requestChannelContext.writeAndFlush(commandResponse); } } }); } else { log.debug("Fire channel read"); requestChannelContext.fireChannelRead(msg); } }
From source file:com.splicemachine.stream.StreamListener.java
License:Apache License
/** * This method accepts new connections from the StreamListenerServer * * It is synchronized as is the stopAllStreams() method because we want to notify channels only once that we are no longer * interested in more data./*from w w w .ja va 2 s . c om*/ */ public synchronized void accept(ChannelHandlerContext ctx, int numPartitions, int partition) { LOG.info(String.format("Accepting connection from partition %d out of %d", partition, numPartitions)); Channel channel = ctx.channel(); this.numPartitions = numPartitions; PartitionState ps = new PartitionState(partition, queueSize); PartitionState old = partitionStateMap.putIfAbsent(partition, ps); ps = old != null ? old : ps; if (failure != null) { ps.messages.add(FAILURE); } Channel previousChannel = ps.channel; if (previousChannel != null) { LOG.info("Received connection from retried task, current state " + ps); PartitionState nextState = new PartitionState(partition, queueSize); nextState.channel = channel; ps.next = nextState; partitionMap.put(channel, ps.next); partitionMap.remove(ps.channel); // don't accept more messages from this channel // this is a new connection from a retried task ps.messages.add(RETRY); } else { partitionMap.put(channel, ps); ps.channel = channel; } if (stopped) { // we are already stopped, ask this stream to close channel.writeAndFlush(new StreamProtocol.RequestClose()); } ctx.pipeline().addLast(this); }
From source file:com.splicemachine.stream.StreamListenerServer.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { Channel channel = ctx.channel(); if (msg instanceof StreamProtocol.Init) { StreamProtocol.Init init = (StreamProtocol.Init) msg; LOG.trace("Received " + msg + " from " + channel); UUID uuid = init.uuid;//from w w w . j a va2 s. c o m int numPartitions = init.numPartitions; int partition = init.partition; final StreamListener<T> listener = listenersMap.get(uuid); if (listener != null) { // ... and hand off the channel to the listener listener.accept(ctx, numPartitions, partition); listener.addCloseable(new AutoCloseable() { @Override public void close() throws Exception { unregister(listener); } }); } else { // Listener deregistered, request close of channel LOG.warn("Listener not found, must have unregistered"); ctx.writeAndFlush(new StreamProtocol.RequestClose()); ctx.pipeline().addLast(closeHandler); } // Remove this listener ... ctx.pipeline().remove(this); } else { // ERROR LOG.error("Unexpected message, expecting Init, received: " + msg); } }
From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPCodec.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception { // Discard input if handshake failed. It is expected that the user will close the channel. if (session.handshakeFuture().isDone()) { assert !session.handshakeFuture().isSuccess(); in.skipBytes(in.readableBytes()); }/*www . jav a 2 s. co m*/ // Shake hands final ZMTPHandshake handshake; try { handshake = handshaker.handshake(in, ctx); if (handshake == null) { // Handshake is not yet done. Await more input. return; } } catch (Exception e) { session.handshakeFailure(e); ctx.fireUserEventTriggered(new ZMTPHandshakeFailure(session)); throw e; } // Handshake is done. session.handshakeSuccess(handshake); // Replace this handler with the framing encoder and decoder if (actualReadableBytes() > 0) { out.add(in.readBytes(actualReadableBytes())); } final ZMTPDecoder decoder = config.decoder().decoder(session); final ZMTPEncoder encoder = config.encoder().encoder(session); final ZMTPWireFormat wireFormat = ZMTPWireFormats.wireFormat(session.negotiatedVersion()); final ChannelHandler handler = new CombinedChannelDuplexHandler<ZMTPFramingDecoder, ZMTPFramingEncoder>( new ZMTPFramingDecoder(wireFormat, decoder), new ZMTPFramingEncoder(wireFormat, encoder)); ctx.pipeline().replace(this, ctx.name(), handler); // Tell the user that the handshake is complete ctx.fireUserEventTriggered(new ZMTPHandshakeSuccess(session, handshake)); }
From source file:com.springapp.mvc.netty.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w w w . j a v a 2s. c o m return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); 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(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); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.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 (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.tc.websocket.server.handler.ProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { ByteBuf buf = (ByteBuf) msg;/*from ww w . ja va2 s. c om*/ String data = new String(ByteBufUtil.getBytes(buf)); if (data.contains(Const.UPGRADE_WEBSOCKET) || data.contains(Const.GET_WEBSOCKET)) { proxy.set(false); } else if (data.contains(StringCache.HTTP_1_1)) { proxy.set(true); } if (proxy.get() == false) { writeToFile("frontend." + ctx.channel().id(), ByteBufUtil.getBytes(buf)); } if (Config.getInstance().isCertAuth()) { SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get("ssl"); try { X509Certificate cert = sslhandler.engine().getSession().getPeerCertificateChain()[0]; Principal p = cert.getSubjectDN(); /* Added by Miguel */ LdapName ldapDN = new LdapName(p.getName()); String username = ""; String thumbprint = getThumbPrint(cert.getEncoded()); for (Rdn rdn : ldapDN.getRdns()) { //System.out.println(rdn.getType() + " -> " + rdn.getValue()); if (rdn.getType().equals("CN")) { username = rdn.getValue().toString(); break; } } /* End Added by Miguel*/ String sessionId = parseSessionID(data); if (sessionId != null) { String current = System.getProperty("user.dir"); //System.out.println("Current working directory in Java : " + current); //File sessionFile = new File("c:/sessions/" + sessionId + ".txt"); File sessionFile = new File(current + "/data/sessions/" + sessionId + ".txt"); //only write the file if it hasn't been written yet. if (sessionFile.createNewFile()) { FileUtils.write(sessionFile, p.getName().replaceAll("\"", "").replaceAll("\\+", ",") + "\n" + username + "\n" + thumbprint); } } } catch (Exception e) { LOG.log(Level.SEVERE, null, e); } } if (proxy.get()) { ctx.channel().config().setAutoRead(false); if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } } else { //make sure the backend handler knows its a websocket connection. this.handler.setWebsocket(true); //get handle on the pipeline. ChannelPipeline pipeline = ctx.pipeline(); //apply the websocket handlers builder.apply(pipeline); //remove this handler. pipeline.remove(this); //fire the event to move on to the next handler. ctx.fireChannelRead(msg); } }
From source file:com.tesora.dve.db.mysql.portal.MSPCommandHandler.java
License:Open Source License
static void executeLoadDataStatement(ExecutorService clientExecutorService, ChannelHandlerContext ctx, SSConnection ssCon, MSPComQueryRequestMessage queryMessage) throws PEException { byte[] query = queryMessage.getQueryBytes(); NativeCharSet clientCharSet = MysqlNativeCharSet.UTF8; MysqlLoadDataInfileRequestCollector resultConsumer = new MysqlLoadDataInfileRequestCollector(ctx); try {/*from w w w. j a v a 2s .c o m*/ LoadDataRequestExecutor.execute(ctx, ssCon, resultConsumer, clientCharSet.getJavaCharset(), query); if (resultConsumer.getLoadDataInfileContext().isLocal()) { ctx.pipeline().addFirst(MSPLoadDataDecoder.class.getSimpleName(), new MSPLoadDataDecoder( clientExecutorService, ssCon, resultConsumer.getLoadDataInfileContext())); resultConsumer.sendStartDataRequest(); } } catch (PEException e) { if (MSPComQueryRequest.logger.isInfoEnabled()) MSPComQueryRequest.logger.info("Exception returned to user: ", e); resultConsumer.sendError(e); if (ctx.pipeline().get(MSPLoadDataDecoder.class.getSimpleName()) != null) { ctx.pipeline().remove(MSPLoadDataDecoder.class.getSimpleName()); } } catch (Throwable t) { if (MSPComQueryRequest.logger.isInfoEnabled()) MSPComQueryRequest.logger.info("Exception returned to user: ", t); resultConsumer.sendError(new Exception(t)); if (ctx.pipeline().get(MSPLoadDataDecoder.class.getSimpleName()) != null) { ctx.pipeline().remove(MSPLoadDataDecoder.class.getSimpleName()); } } }
From source file:com.tesora.dve.db.mysql.portal.protocol.MysqlClientAuthenticationHandler.java
License:Open Source License
private void processAcknowlegement(ChannelHandlerContext ctx, ByteBuf payload) throws Exception { byte fieldCount = payload.getByte(payload.readerIndex()); if (fieldCount == MyErrorResponse.ERRORPKT_FIELD_COUNT) { processErrorPacket(ctx, payload); } else {// ww w. jav a 2s . c o m ctx.pipeline().remove(this); enterState(AuthenticationState.AUTHENTICATED); } }