Java Code Examples for org.jboss.netty.bootstrap.ClientBootstrap#setOption()

The following examples show how to use org.jboss.netty.bootstrap.ClientBootstrap#setOption() . 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: Fetcher.java    From incubator-tajo with Apache License 2.0 6 votes vote down vote up
public Fetcher(URI uri, File file, ClientSocketChannelFactory factory) {
  this.uri = uri;
  this.file = file;

  String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
  this.host = uri.getHost() == null ? "localhost" : uri.getHost();
  this.port = uri.getPort();
  if (port == -1) {
    if (scheme.equalsIgnoreCase("http")) {
      this.port = 80;
    } else if (scheme.equalsIgnoreCase("https")) {
      this.port = 443;
    }
  }

  bootstrap = new ClientBootstrap(factory);
  bootstrap.setOption("connectTimeoutMillis", 5000L); // set 5 sec
  bootstrap.setOption("receiveBufferSize", 1048576); // set 1M
  bootstrap.setOption("tcpNoDelay", true);

  ChannelPipelineFactory pipelineFactory = new HttpClientPipelineFactory(file);
  bootstrap.setPipelineFactory(pipelineFactory);
}
 
Example 2
Source File: NettyClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 3
Source File: NettyClient.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 4
Source File: NettyClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 5
Source File: RemoteSyncManager.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
public void startUp(FloodlightModuleContext context) 
        throws FloodlightModuleException {
    shutdown = false;
    bossExecutor = Executors.newCachedThreadPool();
    workerExecutor = Executors.newCachedThreadPool();
    
    final ClientBootstrap bootstrap =
            new ClientBootstrap(
                 new NioClientSocketChannelFactory(bossExecutor,
                                                   workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.receiveBufferSize", 
                        RPCService.SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", 
                        RPCService.CONNECT_TIMEOUT);
    pipelineFactory = new RemoteSyncPipelineFactory(this);
    bootstrap.setPipelineFactory(pipelineFactory);
    clientBootstrap = bootstrap;
}
 
Example 6
Source File: NettyClient.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(() -> {
        NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("decoder", adapter.getDecoder());
        pipeline.addLast("encoder", adapter.getEncoder());
        pipeline.addLast("handler", nettyHandler);
        return pipeline;
    });
}
 
Example 7
Source File: NettyClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 8
Source File: NettyClient.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 9
Source File: RPCService.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to remote servers.  We'll initiate the connection to
 * any nodes with a lower ID so that there will be a single connection
 * between each pair of nodes which we'll use symmetrically
 */
protected void startClients(ChannelPipelineFactory pipelineFactory) {
    final ClientBootstrap bootstrap =
            new ClientBootstrap(
                 new NioClientSocketChannelFactory(bossExecutor,
                                                   workerExecutor));
    bootstrap.setOption("child.reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", SEND_BUFFER_SIZE);
    bootstrap.setOption("child.connectTimeoutMillis", CONNECT_TIMEOUT);
    bootstrap.setPipelineFactory(pipelineFactory);
    clientBootstrap = bootstrap;

    ScheduledExecutorService ses = 
            syncManager.getThreadPool().getScheduledExecutor();
    reconnectTask = new SingletonTask(ses, new ConnectTask());
    reconnectTask.reschedule(0, TimeUnit.SECONDS);
}
 
Example 10
Source File: NettyClient.java    From anima with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doOpen() throws Throwable {
	bootstrap = new ClientBootstrap(channelFactory);
	bootstrap.setOption("keepAlive", true);
	bootstrap.setOption("tcpNoDelay", true);
	bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
	final NettyHandler nettyHandler = new NettyHandler(getConf(), this);
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() {
			NettyCodecAdapter adapter = new NettyCodecAdapter(getConf(),getCodec(), NettyClient.this);
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("decoder", adapter.getDecoder());
			pipeline.addLast("encoder", adapter.getEncoder());
			pipeline.addLast("handler", nettyHandler);
			return pipeline;
		}
	});
}
 
Example 11
Source File: NettyClient.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public void start() {
    bootstrap = new ClientBootstrap(clientChannelFactory);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("sendBufferSize", bufferSize);
    bootstrap.setOption("keepAlive", true);

    // Set up the pipeline factory.
    bootstrap.setPipelineFactory(new StormClientPipelineFactory(this, stormConf));
    reconnect();
}
 
Example 12
Source File: NettyClientFactory.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
public Client createClient(String targetIP, int targetPort, int connectTimeout) throws Exception {
	ClientBootstrap bootstrap = new ClientBootstrap(nioClient);
	bootstrap.setOption("tcpNoDelay", Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")));
	bootstrap.setOption("reuseAddress", Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
	if (connectTimeout < 1000) {
		bootstrap.setOption("connectTimeoutMillis", 1000);
	} else {
		bootstrap.setOption("connectTimeoutMillis", connectTimeout);
	}
	NettyClientHandler handler = new NettyClientHandler(this);
	bootstrap.setPipelineFactory(new NettyClientPipelineFactory(handler));
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort));
	future.awaitUninterruptibly(connectTimeout);
	if (!future.isDone()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
	}
	if (future.isCancelled()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
	}
	if (!future.isSuccess()) {
		log.error("Create connection to " + targetIP + ":" + targetPort + " error", future.getCause());
		throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.getCause());
	}
	NettyClient client = new NettyClient(future, connectTimeout);
	handler.setClient(client);
	return client;
}
 
Example 13
Source File: TimestampClient.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public TimestampClient(int timeoutMillis,TimestampHostProvider timestampHostProvider) {
    this.timeoutMillis = timeoutMillis;
    this.timestampHostProvider = timestampHostProvider;
    clientCallbacks = new ConcurrentHashMap<>();
    
    ExecutorService workerExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("timestampClient-worker-%d").setDaemon(true).build());
    ExecutorService bossExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("timestampClient-boss-%d").setDaemon(true).build());

    HashedWheelTimer hwt = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat("timestampClient-hashedWheelTimer-%d").setDaemon(true).build());
    factory = new NioClientSocketChannelFactory(bossExecutor, NETTY_BOSS_THREAD_COUNT, new NioWorkerPool(workerExecutor, NETTY_WORKER_THREAD_COUNT), hwt);

    bootstrap = new ClientBootstrap(factory);

    // If we end up needing to use one of the memory aware executors,
    // do so with code like this (leave commented out for reference).
    //
    // bootstrap.getPipeline().addLast("executor", new ExecutionHandler(
    // 	   new OrderedMemoryAwareThreadPoolExecutor(10 /* threads */, 1024*1024, 4*1024*1024)));

    bootstrap.getPipeline().addLast("decoder", new FixedLengthFrameDecoder(FIXED_MSG_RECEIVED_LENGTH));
    bootstrap.getPipeline().addLast("handler", this);

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    // bootstrap.setOption("connectTimeoutMillis", 120000);

    // Would be nice to try connecting here, but not sure if this works right. connectIfNeeded();

    try {
        registerJMX();
    } catch (Exception e) {
        SpliceLogUtils.error(LOG, "Unable to register TimestampClient with JMX. Timestamps will still be generated but metrics will not be available.");
    }
}
 
Example 14
Source File: Connection.java    From nfs-client-java with Apache License 2.0 5 votes vote down vote up
/**
 * @param remoteHost A unique name for the host to which the connection is being made.
 * @param port The remote host port being used for the connection.
 * @param usePrivilegedPort
 *            <ul>
 *            <li>If <code>true</code>, use a privileged port (below 1024)
 *            for RPC communication.</li>
 *            <li>If <code>false</code>, use any non-privileged port for RPC
 *            communication.</li>
 *            </ul>
 */
public Connection(String remoteHost, int port, boolean usePrivilegedPort) {
    _remoteHost = remoteHost;
    _port = port;
    _usePrivilegedPort = usePrivilegedPort;
    _clientBootstrap = new ClientBootstrap(NetMgr.getInstance().getFactory());
    // Configure the client.
    _clientBootstrap.setOption(REMOTE_ADDRESS_OPTION, new InetSocketAddress(_remoteHost, _port));
    _clientBootstrap.setOption("connectTimeoutMillis", CONNECT_TIMEOUT);  // set
                                                                          // connection
                                                                          // timeout
                                                                          // value
                                                                          // to
                                                                          // 10
                                                                          // seconds
    _clientBootstrap.setOption("tcpNoDelay", true);
    _clientBootstrap.setOption("keepAlive", true);
    _clientBootstrap.setOption(CONNECTION_OPTION, this);

    // Configure the pipeline factory.
    _clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        /**
         * Netty helper instance.
         */
        private final ChannelHandler ioHandler = new ClientIOHandler(_clientBootstrap);

        /* (non-Javadoc)
         * @see org.jboss.netty.channel.ChannelPipelineFactory#getPipeline()
         */
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new RPCRecordDecoder(), ioHandler);
        }
    });
}
 
Example 15
Source File: MongoProxyInboundHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable( false );

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap( cf );
    cb.setOption( "bufferFactory", HeapChannelBufferFactory.getInstance( ByteOrder.LITTLE_ENDIAN ) );
    cb.getPipeline().addLast( "framer", new MongoMessageFrame() );
    cb.getPipeline().addLast( "handler", new OutboundHandler( e.getChannel() ) );
    ChannelFuture f = cb.connect( new InetSocketAddress( remoteHost, remotePort ) );

    outboundChannel = f.getChannel();
    f.addListener( new ChannelFutureListener() {
        @Override
        public void operationComplete( ChannelFuture future ) throws Exception {
            if ( future.isSuccess() ) {
                // Connection attempt succeeded:
                // Begin to accept incoming traffic.
                inboundChannel.setReadable( true );
            }
            else {
                // Close the connection if the connection attempt has
                // failed.
                inboundChannel.close();
            }
        }
    } );
}
 
Example 16
Source File: EventClient.java    From hadoop-arch-book with Apache License 2.0 5 votes vote down vote up
public void startClient() {
  ClientBootstrap bootstrap = new ClientBootstrap(
          new NioClientSocketChannelFactory(
                  Executors.newCachedThreadPool(),
                  Executors.newCachedThreadPool()));

  try {
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      public ChannelPipeline getPipeline() {
        ChannelPipeline p = Channels.pipeline();

        handler = new NettyClientHandler();

        p.addLast("handler", handler);
        return p;
      }
    });

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("receiveBufferSize", 1048576);
    bootstrap.setOption("sendBufferSize", 1048576);

    // Start the connection attempt.

    LOG.info("EventClient: Connecting " + host + "," + port);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    LOG.info("EventClient: Connected " + host + "," + port);

    allChannels = new DefaultChannelGroup();

    // Wait until the connection is closed or the connection attempt fails.
    allChannels.add(future.getChannel());
    LOG.info("EventClient: Added to Channels ");

  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 17
Source File: NettyRpcConnection.java    From voyage with Apache License 2.0 5 votes vote down vote up
/**
	 * @param connectStatus 心跳检测状态是否正常
	 * @throws Throwable
	 */
	public void open(boolean connectStatus) throws Throwable {
		logger.info("open start,"+getConnStr());
		bootstrap = new ClientBootstrap(factory);
//		timer = new HashedWheelTimer();
		{
			bootstrap.setOption("tcpNoDelay", Boolean.parseBoolean(clientConfig.getTcpNoDelay()));
			bootstrap.setOption("reuseAddress", Boolean.parseBoolean(clientConfig.getReuseAddress()));
			bootstrap.setOption("SO_RCVBUF",1024*128);
			bootstrap.setOption("SO_SNDBUF",1024*128);
			bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
				public ChannelPipeline getPipeline() {
					ChannelPipeline pipeline = Channels.pipeline();
//					int readTimeout = clientConfig.getReadTimeout();
//					if (readTimeout > 0) {
//						pipeline.addLast("timeout", new ReadTimeoutHandler(timer,
//								readTimeout, TimeUnit.MILLISECONDS));
//					}
					pipeline.addLast("encoder", new RpcRequestEncode());
					pipeline.addLast("decoder", new RpcResponseDecode());
					pipeline.addLast("handler", NettyRpcConnection.this);
					return pipeline;
				}
			});
		}
		connected.set(connectStatus);
		logger.info("open finish,"+getConnStr());
	}
 
Example 18
Source File: BgpSessionManagerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Starts up the BGP peer and connects it to the tested BgpSessionManager
 * instance.
 *
 * @param connectToSocket the socket to connect to
 */
private void connect(InetSocketAddress connectToSocket)
    throws InterruptedException {
    //
    // Setup the BGP Peer, i.e., the "remote" BGP router that will
    // initiate the BGP connection, send BGP UPDATE messages, etc.
    //
    ChannelFactory channelFactory =
        new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
    ChannelPipelineFactory pipelineFactory = () -> {
        // Setup the transmitting pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("TestBgpPeerFrameDecoder",
                peerFrameDecoder);
        pipeline.addLast("TestBgpPeerChannelHandler",
                peerChannelHandler);
        return pipeline;
    };

    peerBootstrap = new ClientBootstrap(channelFactory);
    peerBootstrap.setOption("child.keepAlive", true);
    peerBootstrap.setOption("child.tcpNoDelay", true);
    peerBootstrap.setPipelineFactory(pipelineFactory);
    peerBootstrap.connect(connectToSocket);

    boolean result;
    // Wait until the OPEN message is received
    result = peerFrameDecoder.receivedOpenMessageLatch.await(
        MESSAGE_TIMEOUT_MS,
        TimeUnit.MILLISECONDS);
    assertThat(result, is(true));
    // Wait until the KEEPALIVE message is received
    result = peerFrameDecoder.receivedKeepaliveMessageLatch.await(
        MESSAGE_TIMEOUT_MS,
        TimeUnit.MILLISECONDS);
    assertThat(result, is(true));

    for (BgpSession bgpSession : bgpSessionManager.getBgpSessions()) {
        if (bgpSession.remoteInfo().bgpId().equals(BGP_PEER1_ID)) {
            bgpSession1 = bgpSession;
        }
        if (bgpSession.remoteInfo().bgpId().equals(BGP_PEER2_ID)) {
            bgpSession2 = bgpSession;
        }
        if (bgpSession.remoteInfo().bgpId().equals(BGP_PEER3_ID)) {
            bgpSession3 = bgpSession;
        }
    }
}
 
Example 19
Source File: NettyTcpClientTransport.java    From msgpack-rpc-java with Apache License 2.0 4 votes vote down vote up
private static void setIfNotPresent(Map<String, Object> options,
        String key, Object value, ClientBootstrap bootstrap) {
    if (!options.containsKey(key)) {
        bootstrap.setOption(key, value);
    }
}
 
Example 20
Source File: TSOClient.java    From phoenix-omid with Apache License 2.0 4 votes vote down vote up
private TSOClient(OmidClientConfiguration omidConf) throws IOException {

        // Start client with Nb of active threads = 3 as maximum.
        int tsoExecutorThreads = omidConf.getExecutorThreads();

        factory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(
                        new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
                Executors.newCachedThreadPool(
                        new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()), tsoExecutorThreads);
        // Create the bootstrap
        bootstrap = new ClientBootstrap(factory);

        requestTimeoutInMs = omidConf.getRequestTimeoutInMs();
        requestMaxRetries = omidConf.getRequestMaxRetries();
        tsoReconnectionDelayInSecs = omidConf.getReconnectionDelayInSecs();

        LOG.info("Connecting to TSO...");
        HostAndPort hp;
        switch (omidConf.getConnectionType()) {
            case HA:
                zkClient = ZKUtils.initZKClient(omidConf.getConnectionString(),
                                                omidConf.getZkNamespace(),
                                                omidConf.getZkConnectionTimeoutInSecs());
                zkCurrentTsoPath = omidConf.getZkCurrentTsoPath();
                configureCurrentTSOServerZNodeCache(zkCurrentTsoPath);
                String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
                // TSO info includes the new TSO host:port address and epoch
                String[] currentTSOAndEpochArray = tsoInfo.split("#");
                hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
                setTSOAddress(hp.getHostText(), hp.getPort());
                epoch = Long.parseLong(currentTSOAndEpochArray[1]);
                LOG.info("\t* Current TSO host:port found in ZK: {} Epoch {}", hp, getEpoch());
                break;
            case DIRECT:
            default:
                hp = HostAndPort.fromString(omidConf.getConnectionString());
                setTSOAddress(hp.getHostText(), hp.getPort());
                LOG.info("\t* TSO host:port {} will be connected directly", hp);
                break;
        }

        fsmExecutor = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
        fsm = new StateMachine.FsmImpl(fsmExecutor);
        fsm.setInitState(new DisconnectedState(fsm));

        ChannelPipeline pipeline = bootstrap.getPipeline();
        pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
        pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
        pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
        pipeline.addLast("protobufencoder", new ProtobufEncoder());
        pipeline.addLast("handler", new Handler(fsm));

        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);
        bootstrap.setOption("reuseAddress", true);
        bootstrap.setOption("connectTimeoutMillis", 100);
        lowLatency = false;



        conflictDetectionLevel = omidConf.getConflictAnalysisLevel();

    }