List of usage examples for io.netty.channel ChannelHandlerContext executor
EventExecutor executor();
From source file:org.jboss.aerogear.simplepush.server.netty.UserAgentReaperHandler.java
License:Apache License
@Override public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { if (started()) { return;/*ww w.j a v a2 s . c o m*/ } final SimplePushServerConfig config = simplePushServer.config(); logger.info("Creating UserAgentReaper job : " + config.userAgentReaperTimeout()); scheduleFuture = ctx.executor().scheduleAtFixedRate(new UserAgentReaper(simplePushServer), config.userAgentReaperTimeout(), config.userAgentReaperTimeout(), TimeUnit.MILLISECONDS); reaperStarted.set(true); }
From source file:org.jboss.aerogear.simplepush.server.netty.UserAgentReaperHandlerTest.java
License:Apache License
@SuppressWarnings({ "rawtypes", "unchecked" }) private ChannelHandlerContext channelHandlerContext() { final ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); final EventExecutor eventExecutor = mock(EventExecutor.class); final ScheduledFuture future = mock(ScheduledFuture.class); when(eventExecutor.scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class))) .thenReturn(future);/*www. j a va 2 s. c om*/ when(ctx.executor()).thenReturn(eventExecutor); when(ctx.pipeline()).thenReturn(mock(ChannelPipeline.class)); return ctx; }
From source file:org.kobeyoung81.socksproxy.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 w w w . j a v a 2s . 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(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)); } }); //System.out.println(request.toString()); } 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)); //System.out.println(request.host() +":"+ request.port()); //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080); 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:org.ratpackframework.server.internal.NettyHandlerAdapter.java
License:Apache License
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return;//from w ww .j a va 2 s .c o m } final FullHttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); Request request = new DefaultRequest(new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.getMethod().name(), nettyRequest.getUri(), nettyRequest.content()); final Channel channel = ctx.channel(); final DefaultStatus responseStatus = new DefaultStatus(); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyResponse.headers()); final ByteBuf responseBody = nettyResponse.content(); FileHttpTransmitter fileHttpTransmitter = new DefaultFileHttpTransmitter(nettyRequest, nettyResponse, channel); Response response = new DefaultResponse(responseStatus, responseHeaders, responseBody, fileHttpTransmitter, new Runnable() { @Override public void run() { nettyResponse.setStatus(responseStatus.getResponseStatus()); responseHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, responseBody.writerIndex()); boolean shouldClose = true; if (channel.isOpen()) { if (isKeepAlive(nettyRequest)) { responseHeaders.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); shouldClose = false; } ChannelFuture future = channel.writeAndFlush(nettyResponse); if (shouldClose) { future.addListener(ChannelFutureListener.CLOSE); } } } }); if (registry == null) { throw new IllegalStateException("Registry is not set, channel is not registered"); } final Context context = new DefaultContext(request, response, registry, ctx.executor(), blockingExecutorService, return404); handler.handle(context); }
From source file:org.redisson.client.handler.BaseConnectionHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { List<RFuture<Object>> futures = new ArrayList<RFuture<Object>>(); RedisClientConfig config = redisClient.getConfig(); if (config.getPassword() != null) { RFuture<Object> future = connection.async(RedisCommands.AUTH, config.getPassword()); futures.add(future);//w w w . ja v a 2s . c o m } if (config.getDatabase() != 0) { RFuture<Object> future = connection.async(RedisCommands.SELECT, config.getDatabase()); futures.add(future); } if (config.getClientName() != null) { RFuture<Object> future = connection.async(RedisCommands.CLIENT_SETNAME, config.getClientName()); futures.add(future); } if (config.isReadOnly()) { RFuture<Object> future = connection.async(RedisCommands.READONLY); futures.add(future); } if (config.getPingConnectionInterval() > 0) { RFuture<Object> future = connection.async(RedisCommands.PING); futures.add(future); } if (futures.isEmpty()) { ctx.fireChannelActive(); connectionPromise.trySuccess(connection); return; } final AtomicBoolean retry = new AtomicBoolean(); final AtomicInteger commandsCounter = new AtomicInteger(futures.size()); for (RFuture<Object> future : futures) { future.onComplete((res, e) -> { if (e != null) { if (e instanceof RedisLoadingException) { if (retry.compareAndSet(false, true)) { ctx.executor().schedule(() -> { channelActive(ctx); }, 1, TimeUnit.SECONDS); } return; } connection.closeAsync(); connectionPromise.tryFailure(e); return; } if (commandsCounter.decrementAndGet() == 0) { ctx.fireChannelActive(); connectionPromise.trySuccess(connection); } }); } }
From source file:org.tiger.netty.rpc.all.client.HeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("HeartBeatReqHandler channelRead ..." + System.currentTimeMillis()); System.out.println(msg);//from w w w .jav a2 s.co m NettyMessage message = (NettyMessage) msg; // ????? 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:org.wyb.sows.client.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) { System.err.println("Not able to establish bridge. Inform proxy client."); ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); }/*ww w . java 2 s .c o m*/ Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { if (SocksServer.isDebug) { System.out.println("Bridge is established. Inform proxy client."); } SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()); resp.setProtocolVersion(request.protocolVersion()); ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove(SocksServerConnectHandler.this); // ctx.pipeline().addLast(new StringByteCodec()); pipeline.addLast(new WebSocketRelayHandler(outboundChannel)); } }); } else { System.err.println("Not able to establish bridge. Inform proxy client."); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); // Add authentication headers HttpHeaders authHeader = new DefaultHttpHeaders(); authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName); byte[] nonce = SowsAuthHelper.randomBytes(16); String seed = SowsAuthHelper.base64(nonce); authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed); byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII)); String token = SowsAuthHelper.base64(sha1); authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token); // initiating websocket client handler final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise, request.host(), request.port(), inboundChannel); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); if (SocksServer.isDebug) { System.out.println("Try to connect to bridge service."); } b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results if (SocksServer.isDebug) { System.out.printf("Brige service connection is established. host=%s,port=%d \r\n", bridgeServiceUri.getHost(), bridgeServiceUri.getPort()); } } else { // Close the connection if the connection attempt has // failed. System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n", bridgeServiceUri.getHost(), bridgeServiceUri.getPort()); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:pers.zlf.sslocal.handler.shadowsocks.ShadowsocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { final Option option = ShadowsocksClient.getShadowsocksOption(ctx.channel()); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override//from ww w .j av a2 s.co 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(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(ShadowsocksServerConnectHandler.this); outboundChannel.pipeline().addLast( new ShadowsocksMessageCodec(CryptoFactory .createCrypto(option.getMethod(), option.getPassword())), new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); outboundChannel.writeAndFlush(request); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); ChannelUtils.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(option.getRemoteHost(), option.getRemotePort()).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. if (logger.isErrorEnabled()) { logger.error("Failed to connect shadowsocks server", future.cause()); } ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); ChannelUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:reactor.ipc.netty.http.server.HttpServerHandler.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == NettyPipeline.handlerTerminatedEvent()) { if (mustRecycleEncoder) { mustRecycleEncoder = false;/* w w w .j a v a 2 s.c o m*/ pendingResponses -= 1; ctx.pipeline().replace(NettyPipeline.HttpEncoder, NettyPipeline.HttpEncoder, new HttpResponseEncoder()); } if (pipelined != null && !pipelined.isEmpty()) { if (HttpServerOperations.log.isDebugEnabled()) { HttpServerOperations.log.debug("draining next pipelined " + "request," + " pending response count: {}, queued: " + "{}", pendingResponses, pipelined.size()); } ctx.executor().execute(this); } else { ctx.read(); } } ctx.fireUserEventTriggered(evt); }
From source file:testserver.routes.WithDelay.java
License:Apache License
@Override public void handle(final ChannelHandlerContext ctx, HttpRequest request) { ctx.executor().schedule(new Runnable() { @Override// w w w .jav a 2s.co m public void run() { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.copiedBuffer(answer, CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); ctx.writeAndFlush(response).addListener(CLOSE); } }, 10, SECONDS); }