List of usage examples for io.netty.channel ChannelHandlerContext executor
EventExecutor executor();
From source file:at.yawk.dbus.protocol.auth.AuthClient.java
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { for (ChannelHandler handler : handlers) { ctx.pipeline().addBefore(ctx.executor(), ctx.name(), null, handler); }/*from w w w. j a v a 2s .com*/ super.handlerAdded(ctx); }
From source file:at.yawk.dbus.protocol.codec.DbusMainProtocol.java
private void add(ChannelHandlerContext ctx, ChannelHandler handler) { ctx.pipeline().addBefore(ctx.executor(), ctx.name(), null, handler); }
From source file:books.netty.protocol.netty.client.HeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; // ?????// w ww. j ava 2s . c om if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { System.out.println("Client receive server heart beat message : ---> " + message); } else ctx.fireChannelRead(msg); }
From source file:cc.agentx.client.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { boolean proxyMode = isAgentXNeeded(request.host()); log.info("\tClient -> Proxy \tTarget {}:{} [{}]", request.host(), request.port(), proxyMode ? "AGENTX" : "DIRECT"); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override/*ww w. j av a 2 s .c o m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(channelFuture -> { ByteBuf byteBuf = Unpooled.buffer(); request.encodeAsByteBuf(byteBuf); if (byteBuf.hasArray()) { byte[] xRequestBytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, xRequestBytes); if (proxyMode) { // handshaking to remote proxy xRequestBytes = requestWrapper.wrap(xRequestBytes); outboundChannel.writeAndFlush(Unpooled.wrappedBuffer( exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes))); } // task handover ReferenceCountUtil.retain(request); // auto-release? a trap? ctx.pipeline().remove(XConnectHandler.this); outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(), proxyMode ? wrapper : rawWrapper, false)); ctx.pipeline().addLast(new XRelayHandler(outboundChannel, proxyMode ? wrapper : rawWrapper, true)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); String host = request.host(); int port = request.port(); if (host.equals(config.getConsoleDomain())) { host = "localhost"; port = config.getConsolePort(); } else if (proxyMode) { host = config.getServerHost(); port = config.getServerPort(); } // ping target bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.channel().writeAndFlush( new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); }
From source file:cc.agentx.server.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {/*from www .ja va 2s . c om*/ ByteBuf byteBuf = (ByteBuf) msg; if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (!requestParsed) { if (!exposedRequest) { bytes = wrapper.unwrap(bytes); if (bytes == null) { log.info("\tClient -> Proxy \tHalf Request"); return; } } XRequest xRequest = requestWrapper.parse(bytes); String host = xRequest.getHost(); int port = xRequest.getPort(); int dataLength = xRequest.getSubsequentDataLength(); if (dataLength > 0) { byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length); if (exposedRequest) { tailData = wrapper.unwrap(tailData); if (tailData != null) { tailDataBuffer.write(tailData, 0, tailData.length); } } else { tailDataBuffer.write(tailData, 0, tailData.length); } } log.info("\tClient -> Proxy \tTarget {}:{}{}", host, port, DnsCache.isCached(host) ? " [Cached]" : ""); if (xRequest.getAtyp() == XRequest.Type.DOMAIN) { try { host = DnsCache.get(host); if (host == null) { host = xRequest.getHost(); } } catch (UnknownHostException e) { log.warn("\tClient <- Proxy \tBad DNS! ({})", e.getMessage()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); return; } } Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { // handle tail byte[] tailData = tailDataBuffer.toByteArray(); tailDataBuffer.close(); if (tailData.length > 0) { log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length); } outboundChannel .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData) : Unpooled.EMPTY_BUFFER) .addListener(channelFuture -> { // task handover outboundChannel.pipeline() .addLast(new XRelayHandler(ctx.channel(), wrapper, false)); ctx.pipeline() .addLast(new XRelayHandler(outboundChannel, wrapper, true)); ctx.pipeline().remove(XConnectHandler.this); }); } else { if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); final String finalHost = host; bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (ctx.channel().isActive()) { log.warn("\tClient <- Proxy \tBad Ping! ({}:{})", finalHost, port); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); requestParsed = true; } else { bytes = wrapper.unwrap(bytes); if (bytes != null) tailDataBuffer.write(bytes, 0, bytes.length); } } } finally { ReferenceCountUtil.release(msg); } }
From source file:cn.david.socks.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override//from www . j a va 2s .c om public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:com.addthis.hydra.query.aggregate.MeshSourceAggregator.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { executor = ctx.executor(); }
From source file:com.addthis.hydra.query.MeshQueryMaster.java
License:Apache License
protected void writeQuery(ChannelHandlerContext ctx, Query query, ChannelPromise promise) throws Exception { String[] opsLog = query.getOps(); // being able to log and monitor rops is kind of important // creates query for worker and updates local query ops (!mutates query!) // TODO: fix this pipeline interface Query remoteQuery = query.createPipelinedQuery(); if (keepy != null) { keepy.resolveAlias(query);/*from w w w . j ava2 s . co m*/ keepy.validateJobForQuery(query); } Map<Integer, Set<FileReferenceWrapper>> fileReferenceMap; try { fileReferenceMap = cachey.get(query.getJob()); if ((fileReferenceMap == null) || fileReferenceMap.isEmpty()) { throw new QueryException("[MeshQueryMaster] No file references found for job: " + query.getJob()); } } catch (ExecutionException e) { log.warn("", e); throw new QueryException("Exception getting file references: " + e.getMessage()); } int canonicalTasks = 0; if (keepy != null) { canonicalTasks = keepy.validateTaskCount(query, fileReferenceMap); } else { for (Integer taskId : fileReferenceMap.keySet()) { if (taskId > canonicalTasks) { canonicalTasks = taskId; } } // tasks are zero indexed canonicalTasks += 1; } QueryTaskSource[] sourcesByTaskID = new QueryTaskSource[canonicalTasks]; for (int i = 0; i < canonicalTasks; i++) { Set<FileReferenceWrapper> sourceOptions = fileReferenceMap.get(i); QueryTaskSourceOption[] taskSourceOptions = new QueryTaskSourceOption[sourceOptions.size()]; int taskSourceOptionsIndex = 0; for (FileReferenceWrapper wrapper : sourceOptions) { FileReference queryReference = wrapper.fileReference; WorkerData workerData = worky.get(queryReference.getHostUUID()); taskSourceOptions[taskSourceOptionsIndex] = new QueryTaskSourceOption(queryReference, workerData.queryLeases); taskSourceOptionsIndex += 1; } sourcesByTaskID[i] = new QueryTaskSource(taskSourceOptions); } MeshSourceAggregator aggregator = new MeshSourceAggregator(sourcesByTaskID, meshy, this, remoteQuery); ctx.pipeline().addLast(ctx.executor(), "query aggregator", aggregator); TrackerHandler trackerHandler = new TrackerHandler(tracker, opsLog); ctx.pipeline().addLast(ctx.executor(), "query tracker", trackerHandler); ctx.pipeline().remove(this); ctx.pipeline().write(query, promise); }
From source file:com.alibaba.dubbo.qos.server.handler.QosProcessHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { welcomeFuture = ctx.executor().schedule(new Runnable() { @Override//w w w . j ava 2s.c om public void run() { if (welcome != null) { ctx.write(Unpooled.wrappedBuffer(welcome.getBytes())); ctx.writeAndFlush(Unpooled.wrappedBuffer(prompt.getBytes())); } } }, 500, TimeUnit.MILLISECONDS); }
From source file:com.baidu.rigel.biplatform.ma.file.client.monitor.FileServerMonitor.java
License:Open Source License
/** * {@inheritDoc}// w ww . j a v a 2s . c o m */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("receive message from server --> " + msg); if ("handshake".equals(msg)) { heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 1, TimeUnit.SECONDS); } else if ("pang".equals(msg)) { logger.info("Client receive server heart beat message : -->" + msg); } else { ctx.fireChannelRead(msg); } }