Java Code Examples for io.netty.channel.ChannelHandler

The following are top voted examples for showing how to use io.netty.channel.ChannelHandler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: qonduit   File: Server.java   View source code 7 votes vote down vote up
protected ChannelHandler setupWSChannel(SslContext sslCtx, Configuration conf, DataStore datastore) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
            ch.pipeline().addLast("httpServer", new HttpServerCodec());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
            ch.pipeline().addLast("sessionExtractor", new WebSocketHttpCookieHandler(config));
            ch.pipeline().addLast("idle-handler", new IdleStateHandler(conf.getWebsocket().getTimeout(), 0, 0));
            ch.pipeline().addLast("ws-protocol", new WebSocketServerProtocolHandler(WS_PATH, null, true));
            ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(datastore, config));
            ch.pipeline().addLast("error", new WSExceptionHandler());
        }
    };

}
 
Example 2
Project: ZentrelaRPG   File: TinyProtocol.java   View source code 6 votes vote down vote up
/**
 * Add a custom channel handler to the given channel.
 * 
 * Method modified by @Edasakii to fix bug on reload caused by CastException
 * 
 * @param player - the channel to inject.
 * @return The packet interceptor.
 */
private PacketInterceptor injectChannelInternal(Channel channel) {
    try {
        ChannelHandler ch = channel.pipeline().get(handlerName);
        PacketInterceptor interceptor = null;
        if (ch != null && ch instanceof PacketInterceptor) {
            interceptor = (PacketInterceptor) ch;
        } else {
            interceptor = new PacketInterceptor();
            channel.pipeline().addBefore("packet_handler", handlerName, interceptor);
            uninjectedChannels.remove(channel);
        }
        return interceptor;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 3
Project: nitmproxy   File: Http2FrontendHandler.java   View source code 6 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("{} : handlerAdded", connectionInfo);

    Http2Connection connection = new DefaultHttp2Connection(true);
    ChannelHandler http2ConnHandler = new HttpToHttp2ConnectionHandlerBuilder()
            .frameListener(new DelegatingDecompressorFrameListener(
                    connection,
                    new InboundHttp2ToHttpAdapterBuilder(connection)
                            .maxContentLength(master.config().getMaxContentLength())
                            .propagateSettings(true)
                            .build()))
            .connection(connection)
            .frameLogger(new Http2FrameLogger(LogLevel.DEBUG))
            .build();
    ctx.pipeline()
       .addBefore(ctx.name(), null, http2ConnHandler)
       .addBefore(ctx.name(), null, new Http2Handler());
}
 
Example 4
Project: nitmproxy   File: Http2BackendHandler.java   View source code 6 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("{} : handlerAdded", connectionInfo);

    Http2Connection connection = new DefaultHttp2Connection(false);
    ChannelHandler http2ConnHandler = new HttpToHttp2ConnectionHandlerBuilder()
            .frameListener(new DelegatingDecompressorFrameListener(
                    connection,
                    new InboundHttp2ToHttpAdapterBuilder(connection)
                            .maxContentLength(master.config().getMaxContentLength())
                            .propagateSettings(true)
                            .build()))
            .frameLogger(new Http2FrameLogger(LogLevel.DEBUG))
            .connection(connection)
            .build();
    ctx.pipeline()
       .addBefore(ctx.name(), null, http2ConnHandler)
       .addBefore(ctx.name(), null, new Http2Handler());
}
 
Example 5
Project: skylla   File: SkyllaChannelInitializer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();

    ChannelHandler lengthFieldBasedFrameDecoder = NettyUtils.createLengthFieldBasedFrameDecoder(32768, 0, 4);
    pipeline.addLast(lengthFieldBasedFrameDecoder);

    ChannelHandler packetDecoder = new SkyllaPacketDecoder(this.protocol);
    pipeline.addLast(packetDecoder);

    ChannelHandler lengthFieldPrepender = NettyUtils.createLengthFieldPrepender(4);
    pipeline.addLast(lengthFieldPrepender);

    ChannelHandler packetEncoder = new SkyllaPacketEncoder(this.protocol);
    pipeline.addLast(packetEncoder);

    ChannelHandler packetHandler = new SkyllaConnection(socketChannel, this.protocol);
    pipeline.addLast(packetHandler);
}
 
Example 6
Project: skylla   File: SimpleSkyllaClient.java   View source code 6 votes vote down vote up
@Override
public void connect() {
    this.workerGroup = NettyUtils.createEventLoopGroup(4);

    Class<? extends Channel> channelClazz = NettyUtils.getChannel();
    ChannelHandler channelInitializer = new SkyllaChannelInitializer(this.config.getProtocol());

    Bootstrap bootstrap = new Bootstrap();

    try {
        channel = bootstrap
                .channel(channelClazz)
                .group(this.workerGroup)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, 50)
                .handler(channelInitializer)
                .connect(this.config.getServerHost(), this.config.getServerPort())
                .sync().channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 7
Project: DecompiledMinecraft   File: NetworkSystem.java   View source code 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 8
Project: CustomWorldGen   File: NetworkSystem.java   View source code 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
@SideOnly(Side.CLIENT)
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)SERVER_NIO_EVENTLOOP.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 9
Project: util4j   File: NettyTextWebSocketClient.java   View source code 6 votes vote down vote up
/**
	 * 适配
	 */
	@Override
	protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
		ChannelHandler result=new ShareableChannelInboundHandler() {
			@Override
			public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
				Channel ch=ctx.channel();
				ch.pipeline().addLast(new HttpClientCodec());
            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
				ctx.pipeline().remove(this);//移除当前handler
				ctx.pipeline().fireChannelRegistered();//重新从第一个handler抛出事件
			}
		};
//		ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//            	ch.pipeline().addLast(new HttpClientCodec());
//            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
	}
 
Example 10
Project: util4j   File: NettyBinaryWebSocketClient.java   View source code 6 votes vote down vote up
/**
	 * 适配
	 */
	@Override
	protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
		ChannelHandler result=new ShareableChannelInboundHandler() {
			@Override
			public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
				Channel ch=ctx.channel();
				ch.pipeline().addLast(new HttpClientCodec());
            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
				ctx.pipeline().remove(this);//移除当前handler
				ctx.fireChannelRegistered();//重新从第一个handler抛出事件
			}
		};
//		ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//            	ch.pipeline().addLast(new HttpClientCodec());
//            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
	}
 
Example 11
Project: BaseClient   File: NetworkSystem.java   View source code 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 12
Project: BaseClient   File: NetworkSystem.java   View source code 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 13
Project: qonduit   File: NonSslRedirectHandler.java   View source code 6 votes vote down vote up
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(Names.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
Example 14
Project: NioSmtpClient   File: SmtpSessionTest.java   View source code 6 votes vote down vote up
private SslHandler getSslHandler() throws Exception {
  // get SslHandler if it was added to the pipeline
  ArgumentCaptor<ChannelHandler> captor = ArgumentCaptor.forClass(ChannelHandler.class);
  verify(pipeline).addFirst(captor.capture());
  SslHandler sslHandler = (SslHandler) captor.getValue();

  // mock and store the context so we can get the handshake future
  ChannelHandlerContext context = mock(ChannelHandlerContext.class);
  when(context.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
  when(context.channel()).thenReturn(mock(Channel.class, Answers.RETURNS_MOCKS.get()));

  // add the handler but prevent the handshake from running automatically
  when(channel.isActive()).thenReturn(false);
  sslHandler.handlerAdded(context);

  return sslHandler;
}
 
Example 15
Project: CustomWorldGen   File: NetworkRegistry.java   View source code 6 votes vote down vote up
/**
 * INTERNAL Create a new channel pair with the specified name and channel handlers.
 * This is used internally in forge and FML
 *
 * @param container The container to associate the channel with
 * @param name The name for the channel
 * @param handlers Some {@link ChannelHandler} for the channel
 * @return an {@link EnumMap} of the pair of channels. keys are {@link Side}. There will always be two entries.
 */
public EnumMap<Side,FMLEmbeddedChannel> newChannel(ModContainer container, String name, ChannelHandler... handlers)
{
    if (channels.get(Side.CLIENT).containsKey(name) || channels.get(Side.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || (name.startsWith("FML") && !("FML".equals(container.getModId()))))
    {
        throw new RuntimeException("That channel is already registered");
    }
    EnumMap<Side,FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);

    for (Side side : Side.values())
    {
        FMLEmbeddedChannel channel = new FMLEmbeddedChannel(container, name, side, handlers);
        channels.get(side).put(name,channel);
        result.put(side, channel);
    }
    return result;
}
 
Example 16
Project: Backmemed   File: NetworkSystem.java   View source code 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)SERVER_NIO_EVENTLOOP.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 17
Project: redant   File: InterceptorUtil.java   View source code 5 votes vote down vote up
public static ChannelHandler[] getPreInterceptors(){
    preLock.lock();
    try {
        if(preInterceptors==null){
            preInterceptors = getInterceptors(PreHandleInterceptor.class);
        }
    }finally {
        preLock.unlock();
    }
    return ArrayUtil.clone(preInterceptors);
}
 
Example 18
Project: redant   File: InterceptorUtil.java   View source code 5 votes vote down vote up
public static ChannelHandler[] getAfterInterceptors(){
    afterLock.lock();
    try {
        if(afterInterceptors==null){
            afterInterceptors = getInterceptors(AfterHandleInterceptor.class);
        }
    }finally {
        afterLock.unlock();
    }
    return ArrayUtil.clone(afterInterceptors);
}
 
Example 19
Project: nitmproxy   File: BackendChannelBootstrap.java   View source code 5 votes vote down vote up
public ChannelFuture connect(ChannelHandlerContext fromCtx, NitmProxyMaster master, ConnectionInfo connectionInfo,
                             ChannelHandler handler) {
    return new Bootstrap()
            .group(fromCtx.channel().eventLoop())
            .channel(fromCtx.channel().getClass())
            .handler(handler)
            .connect(connectionInfo.getServerAddr().getHost(),
                     connectionInfo.getServerAddr().getPort());
}
 
Example 20
Project: CustomWorldGen   File: FMLEmbeddedChannel.java   View source code 5 votes vote down vote up
public String findChannelHandlerNameForType(Class<? extends ChannelHandler> type)
{
    String targetName = null;
    for (Entry<String, ChannelHandler> entry : pipeline())
    {
        if (type.isInstance(entry.getValue()))
        {
            targetName = entry.getKey();
            break;
        }
    }
    return targetName;
}
 
Example 21
Project: nitmproxy   File: NitmProxyMaster.java   View source code 5 votes vote down vote up
public ChannelHandler proxyHandler(Address clientAddress) {
    switch (config.getProxyMode()) {
    case HTTP:
        return new HttpProxyHandler(this, new ConnectionInfo(clientAddress));
    case SOCKS:
        return new SocksProxyHandler(this, new ConnectionInfo(clientAddress));
    default:
        throw new IllegalStateException("No proxy mode available: " + config.getProxyMode());
    }
}
 
Example 22
Project: nitmproxy   File: Http1FrontendHandlerTest.java   View source code 5 votes vote down vote up
private Http1FrontendHandler httpProxyHandler(boolean outboundAvailable) {
    if (outboundAvailable) {
        when(master.connect(any(), any(), any())).then(
                invocationOnMock ->  {
                    outboundChannel = new EmbeddedChannel((ChannelHandler) invocationOnMock.getArguments()[2]);
                    return outboundChannel.newSucceededFuture();
                });
    } else {
        when(master.connect(any(), any(), any())).then(
                invocationOnMock ->  inboundChannel.newPromise().setFailure(new Exception()));
    }
    return new Http1FrontendHandler(master, connectionInfo());
}
 
Example 23
Project: CustomWorldGen   File: FMLEmbeddedChannel.java   View source code 5 votes vote down vote up
public FMLEmbeddedChannel(ModContainer container, String channelName, Side source, ChannelHandler... handlers)
{
    super(handlers);
    this.attr(NetworkRegistry.FML_CHANNEL).set(channelName);
    this.attr(NetworkRegistry.CHANNEL_SOURCE).set(source);
    this.attr(NetworkRegistry.MOD_CONTAINER).setIfAbsent(container);
    this.pipeline().addFirst("fml:outbound",new FMLOutboundHandler());
}
 
Example 24
Project: DecompiledMinecraft   File: NetworkManager.java   View source code 5 votes vote down vote up
/**
 * Prepares a clientside NetworkManager: establishes a connection to the socket supplied and configures the channel
 * pipeline. Returns the newly created instance.
 */
public static NetworkManager provideLocalClient(SocketAddress address)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)CLIENT_LOCAL_EVENTLOOP.getValue())).handler(new ChannelInitializer<Channel>()
    {
        protected void initChannel(Channel p_initChannel_1_) throws Exception
        {
            p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(LocalChannel.class)).connect(address).syncUninterruptibly();
    return networkmanager;
}
 
Example 25
Project: util4j   File: NettyClient.java   View source code 5 votes vote down vote up
public NettyClient(NettyClientConfig config,InetSocketAddress target,ChannelHandler handler) {
	super(target);
	if(config.getIoWorkers().isShutdown())
	{
		throw new UnsupportedOperationException("config is unActive");
	}
	this.config=config;
	this.handler=handler;
}
 
Example 26
Project: util4j   File: NettyClient.java   View source code 5 votes vote down vote up
/**
 * 包装一个初始化父类channel的handler
 * @param handler 业务handler
 * @return
 */
private ChannelHandler channelInitFix(final ChannelHandler handler)
{
	ChannelHandler fixedHandler=new ShareableChannelInboundHandler() {
		@Override
		public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
			Channel ch=ctx.channel();
			setChannel(ch);
			ctx.pipeline().addLast(handler);
			ctx.pipeline().remove(this);//移除当前handler
			ctx.fireChannelRegistered();//从当前handler往后抛出事件
		}
	};
	return fixedHandler;
}
 
Example 27
Project: CustomWorldGen   File: SimpleNetworkWrapper.java   View source code 5 votes vote down vote up
private String generateName(ChannelPipeline pipeline, ChannelHandler handler)
{
    try
    {
        return (String)generateName.invoke(defaultChannelPipeline.cast(pipeline), handler);
    }
    catch (Exception e)
    {
        FMLLog.log(Level.FATAL, e, "It appears we somehow have a not-standard pipeline. Huh");
        throw Throwables.propagate(e);
    }
}
 
Example 28
Project: util4j   File: NettyClientConfig.java   View source code 5 votes vote down vote up
/**
 * 因为每次连接执行都会init都会被remove,所以每次调用booter都会用新的handler来进行连接配置
 * @param address
 * @param init
 * @return
 */
protected ChannelFuture doBooterConnect(InetSocketAddress address,final ChannelHandler init)
{
	ChannelFuture cf;
	synchronized (booter) {
		if(booter.config().group()==null)
		{
			booterInit();
		}
		final CountDownLatch latch=new CountDownLatch(1);
		ChannelHandler handler=initHandlerAdapter(init);
		booter.handler(handler);
		cf=booter.connect(address);
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				log.trace("connect operationComplete:isDone="+future.isDone()+",isSuccess="+future.isSuccess());
				if(future.isDone() && future.isSuccess())
				{
					latch.countDown();
				}
			}
		});
		try {
			latch.await(getConnectTimeOutMills(),TimeUnit.MILLISECONDS);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
	return cf;
}
 
Example 29
Project: util4j   File: NettyServer.java   View source code 5 votes vote down vote up
/**
	 * 初始化handler适配包装
	 * @param init
	 * @return
	 */
	protected ChannelHandler initLogHandlerAdapter(ChannelHandler init)
	{
		ChannelHandler handler=new  ShareableChannelInboundHandler() {
			@Override
			public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
				Channel ch=ctx.channel();
				manageChannel(ch);
				LogLevel level=config.getChannelLevel();
				if(level!=null)
				{//单个链路的日志记录器
					ch.pipeline().addLast(new LoggerHandler(level));
				}
				ch.pipeline().addLast(init);
				ctx.pipeline().remove(this);//移除当前handler
				ctx.fireChannelRegistered();//从当前handler往后抛出事件
			}
		};
//		ChannelHandler handler=new ChannelInitializer<Channel>() {
//			@Override
//			protected void initChannel(Channel ch) throws Exception {
//				channelGroup.add(ch);
//				LogLevel level=config.getLevel();
//				if(level!=null)
//				{
//					ch.pipeline().addLast(new LoggerHandler(config.getLevel()));
//				}
//				ch.pipeline().addLast(init);
//			}
//		};
		return handler;
	}
 
Example 30
Project: util4j   File: NettyServer.java   View source code 5 votes vote down vote up
@Override
protected final ChannelFuture doBind(InetSocketAddress local) {
	booter.localAddress(local);
	initServerOptions(optionConfig());
	ChannelHandler fixedHandler=fixHandlerBeforeDoBooterBind(handler);//修正handler
	return doBooterBind(local,fixedHandler);//启动端口绑定
}
 
Example 31
Project: util4j   File: NettyServer.java   View source code 5 votes vote down vote up
protected ChannelFuture doBooterBind(InetSocketAddress local,final ChannelHandler fixedHandler) {
	ChannelFuture cf;
	synchronized (booter) {
		final CountDownLatch latch=new CountDownLatch(1);
		LoggerHandler loggerHandler=null;//server接收处理链路的日志记录器
		LogLevel level=config.getLevel();
		if(level!=null)
		{
			loggerHandler=new LoggerHandler(level);
		}
		ChannelHandler childHandler=initLogHandlerAdapter(fixedHandler);
		booter.handler(loggerHandler).childHandler(childHandler);
		cf=booter.bind(local);
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				latch.countDown();
			}
		});
		try {
			latch.await(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
	return cf;
}
 
Example 32
Project: BaseClient   File: NetworkManager.java   View source code 5 votes vote down vote up
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    Class <? extends SocketChannel > oclass;
    LazyLoadBase <? extends EventLoopGroup > lazyloadbase;

    if (Epoll.isAvailable() && p_181124_2_)
    {
        oclass = EpollSocketChannel.class;
        lazyloadbase = field_181125_e;
    }
    else
    {
        oclass = NioSocketChannel.class;
        lazyloadbase = CLIENT_NIO_EVENTLOOP;
    }

    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
    {
        protected void initChannel(Channel p_initChannel_1_) throws Exception
        {
            try
            {
                p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
            }
            catch (ChannelException var3)
            {
                ;
            }

            p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
    return networkmanager;
}
 
Example 33
Project: BaseClient   File: NetworkManager.java   View source code 5 votes vote down vote up
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    Class <? extends SocketChannel > oclass;
    LazyLoadBase <? extends EventLoopGroup > lazyloadbase;

    if (Epoll.isAvailable() && p_181124_2_)
    {
        oclass = EpollSocketChannel.class;
        lazyloadbase = field_181125_e;
    }
    else
    {
        oclass = NioSocketChannel.class;
        lazyloadbase = CLIENT_NIO_EVENTLOOP;
    }

    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
    {
        protected void initChannel(Channel p_initChannel_1_) throws Exception
        {
            try
            {
                p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true));
            }
            catch (ChannelException var3)
            {
                ;
            }

            p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly();
    return networkmanager;
}
 
Example 34
Project: cardea   File: SimpleCardeaServer.java   View source code 5 votes vote down vote up
@Override
public void start() {
    this.bossGroup = NettyUtils.createEventLoopGroup(1);
    this.workerGroup = new NioEventLoopGroup(4);

    Class<? extends ServerChannel> serverChannelClazz = NettyUtils.getServerChannelClass();
    ChannelHandler channelHandler = new CardeaServerChannelInitializer(this.backendManager);

    this.logger.info("Starting backend handling tasks.");

    this.executorService
            .scheduleAtFixedRate(new CheckDeadBackendsTask(this.backendManager), 10, 10,
                    TimeUnit.SECONDS);
    this.executorService
            .scheduleAtFixedRate(new BackendRecoverTask(this.backendManager), 10, 10,
                    TimeUnit.SECONDS);

    this.logger.info("Starting server and proxying all connections on *:",
            this.config.getServerPort());

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap
                .channel(serverChannelClazz)
                .group(this.bossGroup, this.workerGroup)
                .childHandler(channelHandler)
                .childOption(ChannelOption.AUTO_READ, false)
                .bind(this.config.getServerPort())
                .sync().channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    this.logger.info("Started reverse proxy on *:", this.config.getServerPort());
}
 
Example 35
Project: qonduit   File: Server.java   View source code 5 votes vote down vote up
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {

        return new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("compressor", new HttpContentCompressor());
                ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
                ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
                final Configuration.Cors corsCfg = config.getHttp().getCors();
                final CorsConfig.Builder ccb;
                if (corsCfg.isAllowAnyOrigin()) {
                    ccb = new CorsConfig.Builder();
                } else {
                    ccb = new CorsConfig.Builder(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
                }
                if (corsCfg.isAllowNullOrigin()) {
                    ccb.allowNullOrigin();
                }
                if (corsCfg.isAllowCredentials()) {
                    ccb.allowCredentials();
                }
                corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
                corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
                CorsConfig cors = ccb.build();
                LOG.trace("Cors configuration: {}", cors);
                ch.pipeline().addLast("cors", new CorsHandler(cors));
                ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
                ch.pipeline().addLast("strict", new StrictTransportHandler(config));
                ch.pipeline().addLast("login", new X509LoginRequestHandler(config));
                ch.pipeline().addLast("doLogin", new BasicAuthLoginRequestHandler(config));
                ch.pipeline().addLast("error", new HttpExceptionHandler());
            }
        };
    }
 
Example 36
Project: qonduit   File: TestServer.java   View source code 5 votes vote down vote up
@Override
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
            ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
            ch.pipeline().addLast("decoder", new HttpRequestDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
            ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
            ch.pipeline().addLast("capture", httpRequests);
        }
    };
}
 
Example 37
Project: NioImapClient   File: ImapClientState.java   View source code 5 votes vote down vote up
public void addHandler(ChannelHandler handler) {
  if (channel != null) {
    channel.pipeline().addLast(executorGroup, handler);
  }

  handlers.add(handler);
}
 
Example 38
Project: kcp-netty   File: UkcpServerBootstrapConfig.java   View source code 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(super.toString());
    buf.setLength(buf.length() - 1);
    buf.append(", ");
    Map<ChannelOption<?>, Object> childOptions = childOptions();
    if (!childOptions.isEmpty()) {
        buf.append("childOptions: ");
        buf.append(childOptions);
        buf.append(", ");
    }
    Map<AttributeKey<?>, Object> childAttrs = childAttrs();
    if (!childAttrs.isEmpty()) {
        buf.append("childAttrs: ");
        buf.append(childAttrs);
        buf.append(", ");
    }
    ChannelHandler childHandler = childHandler();
    if (childHandler != null) {
        buf.append("childHandler: ");
        buf.append(childHandler);
        buf.append(", ");
    }
    if (buf.charAt(buf.length() - 1) == '(') {
        buf.append(')');
    } else {
        buf.setCharAt(buf.length() - 2, ')');
        buf.setLength(buf.length() - 1);
    }

    return buf.toString();
}
 
Example 39
Project: aws-sdk-java-v2   File: ChannelPipelineInitializer.java   View source code 5 votes vote down vote up
public ChannelPipelineInitializer(SslContext sslContext) {
    this.sslContext = sslContext;

    List<ChannelHandler> tmpHandlers = new ArrayList<>();
    if (log.isLoggingLevelEnabled("debug")) {
        tmpHandlers.add(new LoggingHandler(log::debug));
    }

    handlers = tmpHandlers.toArray(new ChannelHandler[0]);
}
 
Example 40
Project: aws-sdk-java-v2   File: ChannelUtils.java   View source code 5 votes vote down vote up
/**
 * Removes handlers of the given class types from the pipeline.
 *
 * @param pipeline the pipeline to remove handlers from
 * @param handlers handlers to remove, identified by class
 */
@SafeVarargs
public static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers) {
    for (Class<? extends ChannelHandler> handler : handlers) {
        if (pipeline.get(handler) != null) {
            pipeline.remove(handler);
        }
    }
}