io.netty.handler.codec.serialization.ObjectEncoder Java Examples

The following examples show how to use io.netty.handler.codec.serialization.ObjectEncoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OzymandiasClient.java    From archistar-core with GNU General Public License v2.0 6 votes vote down vote up
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {

    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);

    Bootstrap b = new Bootstrap();
    b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addLast(
                            new SslHandler(engine),
                            new ObjectEncoder(),
                            new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)),
                            handler);
                }
            });

    return b.connect("127.0.0.1", port).sync().channel();
}
 
Example #2
Source File: LightConfServerBootstrap.java    From lightconf with GNU General Public License v3.0 6 votes vote down vote up
private void bind() throws InterruptedException {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline p = socketChannel.pipeline();
                    p.addLast(new ObjectEncoder());
                    p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                    p.addLast(new ServerHandler());
                }
            });

    ChannelFuture f = bootstrap.bind(port).sync();
    if (f.isSuccess()) {
        log.info(String.format(">>>>>>>>>>>> ligthconf server started, port:%s", port));
    }
}
 
Example #3
Source File: PojoClient.java    From netty-learning with Apache License 2.0 6 votes vote down vote up
public void send() throws InterruptedException {

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new ObjectEncoder());
					p.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
					p.addLast(new PojoClientHandler());
				}
			});

			ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync();

			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
 
Example #4
Source File: NettyServer.java    From mini-dubbo with GNU General Public License v3.0 6 votes vote down vote up
public void doOpen() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast((SimpleChannelInboundHandler)handler);
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture future = serverBootstrap.bind(address,port).sync();
        //future.channel().closeFuture().sync();
    }finally{
        //workerGroup.shutdownGracefully();
        //bossGroup.shutdownGracefully();
    }
}
 
Example #5
Source File: NettyServerBootstrap.java    From netty with Apache License 2.0 6 votes vote down vote up
private void bind() throws InterruptedException {
    EventLoopGroup boss=new NioEventLoopGroup();
    EventLoopGroup worker=new NioEventLoopGroup();
    ServerBootstrap bootstrap=new ServerBootstrap();
    bootstrap.group(boss,worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline p = socketChannel.pipeline();
            p.addLast(new ObjectEncoder());
            p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            p.addLast(new NettyServerHandler());
        }
    });
    ChannelFuture f= bootstrap.bind(port).sync();
    if(f.isSuccess()){
        System.out.println("server start---------------");
    }
}
 
Example #6
Source File: RemoterHA.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Fire typed command and get object response.
 * Example Usage:
 *	CommandWritable commandWritable = new CommandWritable();
	commandWritable.setCommandForMaster(true);
	commandWritable.setUsername("JumbuneUser");
	remoter.fireCommandAndGetObjectResponse(commandWritable);

 * @param command the command
 * @return the object
 */
public Object fireCommandAndGetObjectResponse(CommandWritable commandWritable) {
	ChannelFuture channelFuture;
	// Eventually fallen back on battle tested CyclicBarrier, await(),
	// sync() on ChannelFuture didn't worked
	final CyclicBarrier barrier = new CyclicBarrier(2);

	List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();
	final ObjectResponseHandler objectResponseHandler = new ObjectResponseHandler(barrier);
	handlers.add(new ObjectEncoder());
	//setting maximum object response size which can be handled by us to 40MB
	handlers.add(new ObjectDecoder(41943040, ClassResolvers.cacheDisabled(null)));
	HeartbeatReceptionHandler hbHandler = new HeartbeatReceptionHandler();
	handlers.add(hbHandler);
	handlers.add(objectResponseHandler);
     
	CommandZNodesUtility czu = writeCommandToZK(commandWritable);

       AgentStateListener agentStateListener = new AgentStateListener(hbHandler, barrier, 4);
	new Thread(agentStateListener).start();
	
	try {
		channelFuture = acquireChannelFuture(handlers);
		writeToChannel(channelFuture.channel(), RemotingConstants.CMO_HA, commandWritable, objectResponseHandler);
		confirmBarrierAndGo(barrier);
		channelFuture.channel().close();
	} catch (Exception e) {
		if(agentStateListener.isAgentFailed()) {
			agentStateListener.stop();
		 return tryRecoveringCommandResponse(commandWritable, czu); 
		} else {
			logger.error(e.getMessage(), e);
		}			
	} finally {
		agentStateListener.stop();
		czu.removeAssociatedZNodes();
	}

	return objectResponseHandler.getResponseObject();
}
 
Example #7
Source File: ObjectEchoClient.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
         });

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #8
Source File: EchoClient.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
public void connect(int port, String host, final String filePath) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                // ch.pipeline().addLast(new StringEncoder());
                // ch.pipeline().addLast(new FixedLengthFrameDecoder(100));
                // ch.pipeline().addLast(new ChunkedWriteHandler());
                // ch.pipeline().addLast(new StringDecoder());
                // ch.pipeline().addLast(new EchoClientHandler());
                // ch.pipeline().addLast(new
                // LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                // ch.pipeline().addLast(new LengthFieldPrepender(4,false));
                ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline().addLast(new EchoClientHandler(filePath));
            }
        });
        ChannelFuture f = b.connect(host, port).sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #9
Source File: InitializerPipeline.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch)
        throws Exception {
    //使用Netty实现的线程池
    //        DefaultEventExecutorGroup e1=new DefaultEventExecutorGroup(16);
    ChannelPipeline pipeline = ch.pipeline();
    //		pipeline.addLast("decoder", new MessageDecoder());
    //      pipeline.addLast("encoder", new MessageEncoder());
    //		pipeline.addLast(e1,"handler", new CommonHandler());
    ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
    ch.pipeline().addLast(new ObjectEncoder());
    pipeline.addLast("handler", new EchoServerHandler());
}
 
Example #10
Source File: HelloWorldClient.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
        throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                 .handler(new ChannelInitializer<SocketChannel>() {
                     @Override
                     public void initChannel(SocketChannel ch)
                             throws Exception {
                         ChannelPipeline p = ch.pipeline();
                         if (sslCtx != null) {
                             p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                         }
                         p.addLast(new ObjectEncoder(),
                                   new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                   new HelloWorldClientHandler());
                     }
                 });

        // Start the client.
        ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
 
Example #11
Source File: InitializerPipeline.java    From NettyFileTransfer with Apache License 2.0 5 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		//使用Netty实现的线程池
//        DefaultEventExecutorGroup e1=new DefaultEventExecutorGroup(16);
		ChannelPipeline pipeline = ch.pipeline();
//		pipeline.addLast("decoder", new MessageDecoder());
//      pipeline.addLast("encoder", new MessageEncoder());
//		pipeline.addLast(e1,"handler", new CommonHandler());
		ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
		ch.pipeline().addLast(new ObjectEncoder());
		pipeline.addLast("handler", new EchoServerHandler());
	}
 
Example #12
Source File: EchoClient.java    From NettyFileTransfer with Apache License 2.0 5 votes vote down vote up
public void connect(int port, String host, final String filePath) throws Exception {
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				// ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
				// ch.pipeline().addLast(new StringEncoder());
				// ch.pipeline().addLast(new FixedLengthFrameDecoder(100));
				// ch.pipeline().addLast(new ChunkedWriteHandler());
				// ch.pipeline().addLast(new StringDecoder());
				// ch.pipeline().addLast(new EchoClientHandler());
				// ch.pipeline().addLast(new
				// LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
				// ch.pipeline().addLast(new LengthFieldPrepender(4,false));
				ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
				ch.pipeline().addLast(new ObjectEncoder());
				ch.pipeline().addLast(new EchoClientHandler(filePath));
			}
		});
		ChannelFuture f = b.connect(host, port).sync();
		f.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully();
	}
}
 
Example #13
Source File: FederatedWorker.java    From systemds with Apache License 2.0 5 votes vote down vote up
public void run() {
	log.info("Setting up Federated Worker");
	EventLoopGroup bossGroup = new NioEventLoopGroup(_nrThreads);
	EventLoopGroup workerGroup = new NioEventLoopGroup(_nrThreads);
	ServerBootstrap b = new ServerBootstrap();
	b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
		.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) {
				ch.pipeline()
					.addLast("ObjectDecoder",
						new ObjectDecoder(Integer.MAX_VALUE,
							ClassResolvers.weakCachingResolver(ClassLoader.getSystemClassLoader())))
					.addLast("ObjectEncoder", new ObjectEncoder())
					.addLast("FederatedWorkerHandler", new FederatedWorkerHandler(_seq, _vars));
			}
		}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
	try {
		log.info("Starting Federated Worker server at port: " + _port);
		ChannelFuture f = b.bind(_port).sync();
		log.info("Started Federated Worker at port: " + _port);
		f.channel().closeFuture().sync();
	}
	catch (InterruptedException e) {
		log.error("Federated worker interrupted");
	}
	finally {
		log.info("Federated Worker Shutting down.");
		workerGroup.shutdownGracefully();
		bossGroup.shutdownGracefully();
	}
}
 
Example #14
Source File: RemoterHA.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Fire and forget command.
 *	Example usage: CommandWritable commandWritable = new CommandWritable();
	commandWritable.setCommandString("Sending Command");
	remoter.fireAndForgetCommand(commandWritable);
 * @param command the command
 */
public void fireAndForgetCommand(CommandWritable commandWritable) {
	apisRetryCount++;
	ChannelFuture channelFuture;
	final CyclicBarrier barrier = new CyclicBarrier(2);

	List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();
	final ObjectResponseHandler objectResponseHandler = new ObjectResponseHandler(barrier);
	handlers.add(new ObjectEncoder());
	//setting maximum object response size which can be handled by us to 20MB
	handlers.add(new ObjectDecoder(20971520, ClassResolvers.cacheDisabled(null)));
	HeartbeatReceptionHandler hbHandler = new HeartbeatReceptionHandler();
	handlers.add(hbHandler);
	handlers.add(objectResponseHandler);
	
       AgentStateListener agentStateListener = new AgentStateListener(hbHandler, barrier, 4);
	new Thread(agentStateListener).start();
       
	try {
		channelFuture = acquireChannelFuture(handlers);
		writeToChannel(channelFuture.channel(), RemotingConstants.CMD_HA, commandWritable, objectResponseHandler);
		confirmBarrierAndGo(barrier);
		addCloseListener(channelFuture);
		channelFuture.channel().close();
	} catch (Exception e) {
		if(agentStateListener.isAgentFailed()) {
			agentStateListener.stop();
			if(apisRetryCount <= numApisRetries) {
				updateLeaderAgentInfo();
				fireAndForgetCommand(commandWritable);
				}
		} else {
			logger.error(e.getMessage(), e);
		}			
	} finally {
		agentStateListener.stop();
	}
	apisRetryCount = 0;
}
 
Example #15
Source File: ObjectEchoServer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoServerHandler());
            }
         });

        // Bind and start to accept incoming connections.
        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #16
Source File: RemoterHA.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void shutdownAgent() {
	ChannelFuture channelFuture;
	final CyclicBarrier barrier = new CyclicBarrier(2);

	List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();
	final ObjectResponseHandler objectResponseHandler = new ObjectResponseHandler(barrier);
	handlers.add(new ObjectEncoder());
	//setting maximum object response size which can be handled by us to 20MB
	handlers.add(new ObjectDecoder(20971520, ClassResolvers.cacheDisabled(null)));
	HeartbeatReceptionHandler hbHandler = new HeartbeatReceptionHandler();
	handlers.add(hbHandler);
	handlers.add(objectResponseHandler);
       logger.debug("going to shutdown agent");
	try {
		channelFuture = acquireChannelFuture(handlers);
		writeToChannel(channelFuture.channel(), RemotingConstants.SDA_HA, "", objectResponseHandler);
		confirmBarrierAndGo(barrier);
		addCloseListener(channelFuture);
		channelFuture.channel().close();
	} catch (Exception e) {
	
	} finally {
  
	}
	logger.debug("agent shutdown successful....");
}
 
Example #17
Source File: RemoterNNHA.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Fire and forget command.
 * 	Example usage: CommandWritable commandWritable = new CommandWritable();
 * 		commandWritable.setCommandString("Sending Command");
 * 		remoter.fireAndForgetCommand(commandWritable);
 *
 * @param commandWritable the command writable
 */
public void fireAndForgetCommand(CommandWritable commandWritable) {
	updateLeaderAgentInfo();
	apisRetryCount++;
	ChannelFuture channelFuture;
	CyclicBarrier barrier = new CyclicBarrier(2);
	List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();

	handlers.add(new ObjectEncoder());
	StringResponseHandler stringResponseHandler = new StringResponseHandler();
	handlers.add(new StringDecoder());
	handlers.add(stringResponseHandler);
	NNStateListener nnListener = new NNStateListener(this.clusterName, barrier, zkHosts);
	new Thread(nnListener).start();
       
	try {
	// sending barrier as channel attachment for dynamic integration of
	// barrier
		channelFuture = acquireChannelFuture(handlers);

		writeToChannel(channelFuture.channel(), new String[] { "C", "M", "D" }, commandWritable, barrier);
		confirmBarrierAndGo(barrier);
		addCloseListener(channelFuture);
		channelFuture.channel().close();
	} catch (Exception e) {
		if((nnListener.isNNFailed() || isNNChanged()) && apisRetryCount <= numApisRetries) {
		  logger.warn("Namenode down !! retrying connection to active Namenode");
		  logger.warn("Initiating agent failover...");
			electLeaderOnNN(); 
			updateLeaderAgentInfo();
			fireAndForgetCommand(commandWritable);
			updateGlobalState();
		} else {
			logger.error("Error in fireAndForget Command - ", e);
		}
	}finally {
		nnListener.stop();
		apisRetryCount = 0;
	}
}
 
Example #18
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke fire and get object response command handler.
 *
 * @param ctx the ctx
 */
private void invokeFireAndGetObjectResponseCommandHandler(
		ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();
	p.addLast(DECODER, new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
	p.addLast("commandHandler", new CommandAsObjectResponser());
	p.addLast(ENCODER, new ObjectEncoder());
	p.remove(this);
}
 
Example #19
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke fire and get object response command handler for HA
 *
 * @param ctx the ctx
 */
private void invokeFireAndGetObjectResponseCommandHandlerForHA(
		ChannelHandlerContext ctx) {
	EventExecutor e1 = new DefaultEventExecutorGroup(1).next();
	ChannelPipeline p = ctx.pipeline();
	p.addLast(DECODER, new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
	p.addLast(HEARTBEAT_HANDLER, new HeartbeatHandler(JumbuneAgent.getHeartBeatMillis(), 
			JumbuneAgent.getHeartBeatMillis(), JumbuneAgent.getHeartBeatMillis()));
	p.addLast(e1, new CommandAsObjectResponserHA());
	p.addLast(ENCODER, new ObjectEncoder());
	p.remove(this);
}
 
Example #20
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke fire and forget command handler for HA
 *
 * @param ctx the ctx
 */
private void invokeFireAndForgetCommandHandlerForHA(ChannelHandlerContext ctx) {
	EventExecutor e1 = new DefaultEventExecutorGroup(1).next();
	ChannelPipeline p = ctx.pipeline();
	p.addLast(DECODER, new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
	p.addLast(HEARTBEAT_HANDLER, new HeartbeatHandler(JumbuneAgent.getHeartBeatMillis(), 
			JumbuneAgent.getHeartBeatMillis(), JumbuneAgent.getHeartBeatMillis()));
	p.addLast(e1, new CommandDelegator());
	p.addLast(ENCODER, new ObjectEncoder());
	p.remove(this);
}
 
Example #21
Source File: OzymandiasServer.java    From archistar-core with GNU General Public License v2.0 5 votes vote down vote up
/**
 * setup the server listening ports and handler routines
 */
@Override
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public void run() {
    /* start up netty listener */
    final OzymandiasCommandHandler handler = new OzymandiasCommandHandler(this);

    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        SSLEngine engine = SSLContextFactory.getServerContext().createSSLEngine();
                        engine.setUseClientMode(false);

                        ch.pipeline().addLast(
                                new SslHandler(engine),
                                new ObjectEncoder(),
                                new ObjectDecoder(maxObjectSize, ClassResolvers.cacheDisabled(null)),
                                handler);
                    }
                }).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        serverChannel = b.bind(port).sync();

        // wait until the server socket is closed
        serverChannel.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #22
Source File: ServerServerCommunication.java    From archistar-core with GNU General Public License v2.0 5 votes vote down vote up
/**
 * connects to all replicas
 *
 * @throws InterruptedException
 */
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public void connect() throws InterruptedException {
    for (Entry<Integer, Integer> e : this.serverList.entrySet()) {
        int replicaId = e.getKey();
        int replicaPort = e.getValue();

        if (replicaId != myServerId) {
            Bootstrap b = new Bootstrap();
            b.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // enable SSL/TLS support
                            SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                            engine.setUseClientMode(true);

                            ch.pipeline().addLast(
                                    new SslHandler(engine),
                                    new ObjectEncoder(),
                                    new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)));
                        }
                    });

            /* wait till server is connected */
            ChannelFuture f = null;
            do {
                f = b.connect("127.0.0.1", replicaPort);
                f.await();
            } while (!(f.isDone() && f.isSuccess()));

            this.channels.add(f.sync().channel());
        }
    }
}
 
Example #23
Source File: ClientInitializer.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
@Override
    protected void initChannel(Channel channel) throws Exception {
        //IdleStateHandler检测心跳.
        ChannelPipeline p = channel.pipeline();
        p.addLast(new IdleStateHandler(20, 10, 0));
//        p.addLast(new MessageDecoder());
//        p.addLast(new MessageEncoder());
        p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())));
        p.addLast(new ObjectEncoder());
        p.addLast(new ClientHandler());
    }
 
Example #24
Source File: ObjectEchoClient.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
         });

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #25
Source File: ControllerClient.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
private void connect() {
	EventLoopGroup group = new NioEventLoopGroup(1);
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(group).channel(NioSocketChannel.class)
	.option(ChannelOption.TCP_NODELAY, true)
	.handler(new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			// support the native serialization of Java
			ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.
					weakCachingConcurrentResolver(this.getClass().getClassLoader())));
			ch.pipeline().addLast(new ObjectEncoder());
			ch.pipeline().addLast(new ControllerClientHandler());
		}
	});

	while (true) {
		try {
			Thread.sleep(1000);
			channel = bootstrap.connect(host, port).sync().channel();
			break;
		} catch (Exception e) {
			logger.error("\n\tController client startup fail!");
		}
	}
	logger.debug("\n\tController client startup successful!");
}
 
Example #26
Source File: ControllerServer.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
private void bind() {
	// configuring the NIO thread groups of the server
	// NioEventLoopGroup is a thread group, and it's specialized for 
	//     network event processing (it is actually a 'Reactor' thread group)
	EventLoopGroup bossGroup = new NioEventLoopGroup(1);
	EventLoopGroup workerGroup = new NioEventLoopGroup(1);
	try {
		// ServerBootstrap is an assistant class of Netty for setting up the NIO server
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup)
		.channel(NioServerSocketChannel.class)
		// maximum number of connections
		.option(ChannelOption.SO_BACKLOG, 1024)
		.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) {
				ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.
						weakCachingConcurrentResolver(this.getClass().getClassLoader())));
				ch.pipeline().addLast(new ObjectEncoder());
				ch.pipeline().addLast(new ControllerServerHandler());
			}
		});

		// bind the port and wait for synchronization to succeed
		ChannelFuture cf = bootstrap.bind(port).sync();
		logger.info("\n\tController server startup successful!");

		// wait for server-side listening port to close
		// if there is no this line, server would be closed right away after setting up 
		cf.channel().closeFuture().sync();
	} catch(Exception e) { 
		e.printStackTrace();
	} finally {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}
 
Example #27
Source File: DataGeneratorClient.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
private void connect() {
	// configuring the NIO thread groups of the server
	EventLoopGroup group = new NioEventLoopGroup(1);
	// Bootstrap is an assistant class of Netty for setting up client
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(group).channel(NioSocketChannel.class)
	.option(ChannelOption.TCP_NODELAY, true)
	.handler(new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.
					weakCachingConcurrentResolver(this.getClass().getClassLoader())));
			ch.pipeline().addLast(new ObjectEncoder());
			ch.pipeline().addLast(new DataGeneratorClientHandler());
		}
	});
	
	while (true) {
		try {
			Thread.sleep(1000);
			channel = bootstrap.connect(host, port).sync().channel();
			break;
		} catch (Exception e) {
			logger.info("\n\tData generator client startup fail!");
		}
	}
	logger.info("\n\tData generator client startup successful!");
}
 
Example #28
Source File: DataGeneratorServer.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
private void bind() {
	EventLoopGroup bossGroup = new NioEventLoopGroup(1);
	EventLoopGroup workerGroup = new NioEventLoopGroup(1);
	try {
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup)
		.channel(NioServerSocketChannel.class)
		.option(ChannelOption.SO_BACKLOG, 1024)
		.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) {
				ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.
						weakCachingConcurrentResolver(this.getClass().getClassLoader())));
				ch.pipeline().addLast(new ObjectEncoder());
				ch.pipeline().addLast(new DataGeneratorServerHandler());
			}
		});

		ChannelFuture cf = bootstrap.bind(port).sync();
		logger.info("\n\tData generator server startup successful!");
		cf.channel().closeFuture().sync();
	} catch(Exception e) { 
		e.printStackTrace();
	} finally {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}
 
Example #29
Source File: FederatedWorker.java    From systemds with Apache License 2.0 5 votes vote down vote up
public void run() {
	log.info("Setting up Federated Worker");
	EventLoopGroup bossGroup = new NioEventLoopGroup(_nrThreads);
	EventLoopGroup workerGroup = new NioEventLoopGroup(_nrThreads);
	ServerBootstrap b = new ServerBootstrap();
	b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
		.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) {
				ch.pipeline()
					.addLast("ObjectDecoder",
						new ObjectDecoder(Integer.MAX_VALUE,
							ClassResolvers.weakCachingResolver(ClassLoader.getSystemClassLoader())))
					.addLast("ObjectEncoder", new ObjectEncoder())
					.addLast("FederatedWorkerHandler", new FederatedWorkerHandler(_seq, _vars));
			}
		}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
	try {
		log.info("Starting Federated Worker server at port: " + _port);
		ChannelFuture f = b.bind(_port).sync();
		log.info("Started Federated Worker at port: " + _port);
		f.channel().closeFuture().sync();
	}
	catch (InterruptedException e) {
		log.error("Federated worker interrupted");
	}
	finally {
		log.info("Federated Worker Shutting down.");
		workerGroup.shutdownGracefully();
		bossGroup.shutdownGracefully();
	}
}
 
Example #30
Source File: ServerInitializer.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
@Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline p = channel.pipeline();
//        p.addLast(new MessageEncoder());
//        p.addLast(new MessageDecoder());
        p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())));
        p.addLast(new ObjectEncoder());
        p.addLast(new ServerHandler());
    }