Example usage for io.netty.bootstrap ServerBootstrap childHandler

List of usage examples for io.netty.bootstrap ServerBootstrap childHandler

Introduction

In this page you can find the example usage for io.netty.bootstrap ServerBootstrap childHandler.

Prototype

ChannelHandler childHandler

To view the source code for io.netty.bootstrap ServerBootstrap childHandler.

Click Source Link

Usage

From source file:org.springframework.boot.context.embedded.netty.NettyEmbeddedServletContainer.java

License:Apache License

@Override
public void start() throws EmbeddedServletContainerException {
    ServerBootstrap b = new ServerBootstrap();
    groups(b);//w ww .j a v  a2  s  .co  m
    servletExecutor = new DefaultEventExecutorGroup(50);
    b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context));

    // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here
    context.setInitialised(true);

    ChannelFuture future = b.bind(address).awaitUninterruptibly();
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable cause = future.cause();
    if (null != cause) {
        throw new EmbeddedServletContainerException("Could not start Netty server", cause);
    }
    logger.info(context.getServerInfo() + " started on port: " + getPort());
}

From source file:org.vertx.java.core.http.impl.DefaultHttpServer.java

License:Open Source License

public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestHandler == null && wsHandler == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }//w  ww.j  a v a  2s  .  c  o m
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;

    synchronized (vertx.sharedHttpServers()) {
        id = new ServerID(port, host);

        serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port;

        DefaultHttpServer shared = vertx.sharedHttpServers().get(id);
        if (shared == null) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.applyConnectionOptions(bootstrap);
            tcpHelper.checkSSL(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine();
                        engine.setUseClientMode(false);
                        switch (tcpHelper.getClientAuth()) {
                        case REQUEST: {
                            engine.setWantClientAuth(true);
                            break;
                        }
                        case REQUIRED: {
                            engine.setNeedClientAuth(true);
                            break;
                        }
                        case NONE: {
                            engine.setNeedClientAuth(false);
                            break;
                        }
                        }
                        pipeline.addLast("ssl", new SslHandler(engine));
                    }
                    pipeline.addLast("flashpolicy", new FlashPolicyHandler());
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder());
                    if (compressionSupported) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (tcpHelper.isSSL() || compressionSupported) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                Channel serverChannel = bindFuture.channel();
                serverChannelGroup.add(serverChannel);
                bindFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if (!channelFuture.isSuccess()) {
                            vertx.sharedHttpServers().remove(id);
                        }
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<HttpServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            addHandlers(actualServer);
        }
        actualServer.bindFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (listenHandler != null) {
                    final AsyncResult<HttpServer> res;
                    if (future.isSuccess()) {
                        res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this);
                    } else {
                        res = new DefaultFutureResult<>(future.cause());
                        listening = false;
                    }
                    actualCtx.execute(future.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!future.isSuccess()) {
                    listening = false;
                    // No handler - log so user can see failure
                    actualCtx.reportException(future.cause());
                }
            }
        });
    }
    return this;
}

From source file:org.vertx.java.core.net.impl.DefaultNetServer.java

License:Open Source License

public NetServer listen(final int port, final String host,
        final Handler<AsyncResult<NetServer>> listenHandler) {
    if (connectHandler == null) {
        throw new IllegalStateException("Set connect handler first");
    }/*  w  w w  . j a  v  a 2s . c  o  m*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;
    this.host = host;

    synchronized (vertx.sharedNetServers()) {
        id = new ServerID(port, host);
        DefaultNetServer shared = vertx.sharedNetServers().get(id);
        if (shared == null || port == 0) { // Wildcard port will imply a new actual server each time
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.checkSSL(vertx);

            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        SslHandler sslHandler = tcpHelper.createSslHandler(vertx, false);
                        pipeline.addLast("ssl", sslHandler);
                    }
                    if (tcpHelper.isSSL()) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            tcpHelper.applyConnectionOptions(bootstrap);

            if (connectHandler != null) {
                // Share the event loop thread to also serve the NetServer's network traffic.
                handlerManager.addHandler(connectHandler, actualCtx);
            }

            try {
                InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(host), port);
                bindFuture = bootstrap.bind(addr).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        runListeners();
                    }
                });
                this.addListener(new Runnable() {
                    @Override
                    public void run() {
                        if (bindFuture.isSuccess()) {
                            log.trace("Net server listening on " + host + ":"
                                    + bindFuture.channel().localAddress());
                            // Update port to actual port - wildcard port 0 might have been used
                            DefaultNetServer.this.port = ((InetSocketAddress) bindFuture.channel()
                                    .localAddress()).getPort();
                            DefaultNetServer.this.id = new ServerID(DefaultNetServer.this.port, id.host);
                            vertx.sharedNetServers().put(id, DefaultNetServer.this);
                        } else {
                            vertx.sharedNetServers().remove(id);
                        }
                    }
                });
                serverChannelGroup.add(bindFuture.channel());
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<NetServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            if (port != 0) {
                vertx.sharedNetServers().put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            checkConfigs(actualServer, this);
            actualServer = shared;
            this.port = shared.port();
            if (connectHandler != null) {
                // Share the event loop thread to also serve the NetServer's network traffic.
                actualServer.handlerManager.addHandler(connectHandler, actualCtx);
            }
        }

        // just add it to the future so it gets notified once the bind is complete
        actualServer.addListener(new Runnable() {
            public void run() {
                if (listenHandler != null) {
                    final AsyncResult<NetServer> res;
                    if (actualServer.bindFuture.isSuccess()) {
                        res = new DefaultFutureResult<NetServer>(DefaultNetServer.this);
                    } else {
                        listening = false;
                        res = new DefaultFutureResult<>(actualServer.bindFuture.cause());
                    }
                    actualCtx.execute(actualServer.bindFuture.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!actualServer.bindFuture.isSuccess()) {
                    // No handler - log so user can see failure
                    actualCtx.reportException(actualServer.bindFuture.cause());
                    listening = false;
                }
            }
        });

    }
    return this;
}

From source file:org.waarp.commandexec.server.LocalExecServer.java

License:Open Source License

/**
 * Takes 3 optional arguments:<br>
 * - no argument: implies 127.0.0.1 + 9999 port<br>
 * - arguments:<br>//from  w w  w . j  a  v  a2 s. c  o  m
 * "addresse" "port"<br>
 * "addresse" "port" "default delay"<br>
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null));
    int port = 9999;
    InetAddress addr;
    long delay = LocalExecDefaultResult.MAXWAITPROCESS;
    if (args.length >= 2) {
        addr = InetAddress.getByName(args[0]);
        port = Integer.parseInt(args[1]);
        if (args.length > 2) {
            delay = Long.parseLong(args[2]);
        }
    } else {
        byte[] loop = { 127, 0, 0, 1 };
        addr = InetAddress.getByAddress(loop);
    }
    // Configure the server.
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        WaarpNettyUtil.setServerBootstrap(bootstrap, bossGroup, workerGroup, 30000);

        // Configure the pipeline factory.
        bootstrap.childHandler(new LocalExecServerInitializer(delay, executor));

        // Bind and start to accept incoming connections only on local address.
        ChannelFuture future = bootstrap.bind(new InetSocketAddress(addr, port));

        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

        // Wait until all threads are terminated.
        bossGroup.terminationFuture().sync();
        workerGroup.terminationFuture().sync();
    }
}

From source file:org.waarp.commandexec.ssl.server.LocalExecSslServer.java

License:Open Source License

/**
 * Takes 3 to 8 arguments (last 5 are optional arguments):<br>
 * - mandatory arguments: filename keystorepaswwd keypassword<br>
 * - if no more arguments are provided, it implies 127.0.0.1 + 9999 as port and no certificates<br>
 * - optional arguments:<br>/* w w w .  j  ava 2s .co  m*/
 * "port"<br>
 * "port" "trustfilename" "trustpassword"<br>
 * "port" "trustfilename" "trustpassword" "addresse"<br>
 * "port" "trustfilename" "trustpassword" "addresse" "default delay"<br>
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null));
    int port = 9999;
    InetAddress addr;
    long delay = LocalExecDefaultResult.MAXWAITPROCESS;
    String keyStoreFilename, keyStorePasswd, keyPassword;
    String trustStoreFilename = null, trustStorePasswd = null;
    byte[] loop = { 127, 0, 0, 1 };
    addr = InetAddress.getByAddress(loop);
    if (args.length >= 3) {
        keyStoreFilename = args[0];
        keyStorePasswd = args[1];
        keyPassword = args[2];
        if (args.length >= 4) {
            port = Integer.parseInt(args[3]);
            if (args.length >= 6) {
                trustStoreFilename = args[4];
                trustStorePasswd = args[5];
                if (args.length >= 7) {
                    addr = InetAddress.getByName(args[6]);
                    if (args.length > 7) {
                        delay = Long.parseLong(args[7]);
                    }
                }
            }
        }
    } else {
        System.err.println("Need at least 3 arguments: Filename KeyStorePswd KeyPswd");
        return;
    }
    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    WaarpNettyUtil.setServerBootstrap(bootstrap, bossGroup, workerGroup, 30000);

    // Load the KeyStore (No certificates)
    WaarpSecureKeyStore WaarpSecureKeyStore = new WaarpSecureKeyStore(keyStoreFilename, keyStorePasswd,
            keyPassword);
    if (trustStoreFilename != null) {
        // Include certificates
        WaarpSecureKeyStore.initTrustStore(trustStoreFilename, trustStorePasswd, true);
    } else {
        WaarpSecureKeyStore.initEmptyTrustStore();
    }
    WaarpSslContextFactory waarpSslContextFactory = new WaarpSslContextFactory(WaarpSecureKeyStore, true);
    // Configure the pipeline factory.
    bootstrap.childHandler(new LocalExecSslServerInitializer(waarpSslContextFactory, delay, executor));

    // Bind and start to accept incoming connections only on local address.
    bootstrap.bind(new InetSocketAddress(addr, port));
}

From source file:org.waarp.gateway.kernel.rest.HttpRestHandlerTest.java

License:Open Source License

/**
 * Initialize the REST service (server side) for one restConfiguration
 * /*from   w  w  w.  j  av a2s. c  om*/
 * @param restConfiguration
 */
public static void initializeService(RestConfiguration restConfiguration) {
    instantiateHandlers(restConfiguration);
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // Configure the server.
    ServerBootstrap httpBootstrap = new ServerBootstrap();
    WaarpNettyUtil.setServerBootstrap(httpBootstrap, bossGroup, workerGroup, 30000);

    // Configure the pipeline factory.
    httpBootstrap.childHandler(new HttpRestInitializer(restConfiguration));
    // Bind and start to accept incoming connections.
    ChannelFuture future = null;
    if (restConfiguration != null && !restConfiguration.REST_ADDRESS.isEmpty()) {
        future = httpBootstrap
                .bind(new InetSocketAddress(restConfiguration.REST_ADDRESS, restConfiguration.REST_PORT));
    } else {
        future = httpBootstrap.bind(new InetSocketAddress(restConfiguration.REST_PORT));
    }
    try {
        future.await();
        group.add(future.channel());
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.waarp.openr66.protocol.http.rest.HttpRestR66Handler.java

License:Open Source License

/**
 * Initialize the REST service (server side) for one restConfiguration
 * //ww  w. ja  v  a2  s . c o m
 * @param restConfiguration
 */
public static void initializeService(RestConfiguration restConfiguration) {
    instantiateHandlers(restConfiguration);
    if (group == null) {
        group = Configuration.configuration.getHttpChannelGroup();
    }
    // Configure the server.
    ServerBootstrap httpBootstrap = new ServerBootstrap();
    WaarpNettyUtil.setServerBootstrap(httpBootstrap, Configuration.configuration.getHttpBossGroup(),
            Configuration.configuration.getHttpWorkerGroup(),
            (int) Configuration.configuration.getTIMEOUTCON());
    // Set up the event pipeline factory.
    if (restConfiguration.REST_SSL) {
        httpBootstrap.childHandler(new HttpRestR66Initializer(false, Configuration.getWaarpSslContextFactory(),
                restConfiguration));
    } else {
        httpBootstrap.childHandler(new HttpRestR66Initializer(false, null, restConfiguration));
    }
    // Bind and start to accept incoming connections.
    ChannelFuture future;
    if (restConfiguration != null && restConfiguration.REST_ADDRESS != null
            && !restConfiguration.REST_ADDRESS.isEmpty()) {
        future = httpBootstrap
                .bind(new InetSocketAddress(restConfiguration.REST_ADDRESS, restConfiguration.REST_PORT));
    } else {
        future = httpBootstrap.bind(new InetSocketAddress(restConfiguration.REST_PORT));
    }
    try {
        future.await();
    } catch (InterruptedException e) {
    }
    if (future.isSuccess()) {
        group.add(future.channel());
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.websocket.management.WebsocketEndpointManager.java

License:Open Source License

public boolean startListener(int port, String name, InboundProcessorParams params) {
    if (WebsocketEventExecutorManager.getInstance().isRegisteredExecutor(port)) {
        log.info("Netty Listener already started on port " + port);
        return true;
    }/*  w ww  .j a v a 2 s .  c o m*/

    InboundWebsocketConfiguration config = buildConfiguration(port, name, params);
    NettyThreadPoolConfiguration threadPoolConfig = new NettyThreadPoolConfiguration(
            config.getBossThreadPoolSize(), config.getWorkerThreadPoolSize());
    InboundWebsocketEventExecutor eventExecutor = new InboundWebsocketEventExecutor(threadPoolConfig);
    WebsocketEventExecutorManager.getInstance().registerEventExecutor(port, eventExecutor);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventExecutor.getBossGroupThreadPool(), eventExecutor.getWorkerGroupThreadPool())
            .channel(NioServerSocketChannel.class);
    InboundWebsocketChannelInitializer handler = new InboundWebsocketChannelInitializer();
    handler.setClientBroadcastLevel(config.getBroadcastLevel());
    handler.setOutflowDispatchSequence(config.getOutFlowDispatchSequence());
    handler.setOutflowErrorSequence(config.getOutFlowErrorSequence());
    handler.setSubprotocolHandlers(
            SubprotocolBuilderUtil.stringToSubprotocolHandlers(config.getSubprotocolHandler()));
    handler.setPipelineHandler(
            PipelineHandlerBuilderUtil.stringToPipelineHandlers(config.getPipelineHandler()));
    handler.setDispatchToCustomSequence(config.getDispatchToCustomSequence());
    handler.setPortOffset(PersistenceUtils.getPortOffset(params.getProperties()));
    bootstrap.childHandler(handler);
    try {
        bootstrap.bind(new InetSocketAddress(port)).sync();
        log.info("Netty Listener starting on port " + port);
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    }
    return true;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.websocket.management.WebsocketEndpointManager.java

License:Open Source License

public boolean startSSLListener(int port, String name, InboundProcessorParams params) {
    if (WebsocketEventExecutorManager.getInstance().isRegisteredExecutor(port)) {
        log.info("Netty Listener already started on port " + port);
        return true;
    }/*w  ww  . j a va  2  s. com*/

    InboundWebsocketConfiguration config = buildConfiguration(port, name, params);
    InboundWebsocketSSLConfiguration sslConfiguration = buildSSLConfiguration(params);
    NettyThreadPoolConfiguration threadPoolConfig = new NettyThreadPoolConfiguration(
            config.getBossThreadPoolSize(), config.getWorkerThreadPoolSize());
    InboundWebsocketEventExecutor eventExecutor = new InboundWebsocketEventExecutor(threadPoolConfig);
    WebsocketEventExecutorManager.getInstance().registerEventExecutor(port, eventExecutor);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventExecutor.getBossGroupThreadPool(), eventExecutor.getWorkerGroupThreadPool())
            .channel(NioServerSocketChannel.class);
    InboundWebsocketChannelInitializer handler = new InboundWebsocketChannelInitializer();
    handler.setSslConfiguration(sslConfiguration);
    handler.setClientBroadcastLevel(config.getBroadcastLevel());
    handler.setOutflowDispatchSequence(config.getOutFlowDispatchSequence());
    handler.setOutflowErrorSequence(config.getOutFlowErrorSequence());
    handler.setSubprotocolHandlers(
            SubprotocolBuilderUtil.stringToSubprotocolHandlers(config.getSubprotocolHandler()));
    handler.setPipelineHandler(
            PipelineHandlerBuilderUtil.stringToPipelineHandlers(config.getPipelineHandler()));
    handler.setDispatchToCustomSequence(config.getDispatchToCustomSequence());
    handler.setPortOffset(PersistenceUtils.getPortOffset(params.getProperties()));
    bootstrap.childHandler(handler);
    try {
        bootstrap.bind(new InetSocketAddress(port)).sync();
        log.info("Netty SSL Listener starting on port " + port);
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    }
    return true;
}

From source file:org.wso2.carbon.protobuf.registry.internal.ProtobufRegistryActivator.java

License:Open Source License

public void start(BundleContext bundleContext) {

    log.info("/////////////////////////////////////");

    // load protobuf server configurations from pbs xml
    ProtobufConfiguration configuration = null;
    try {/*from ww  w. ja  va2  s  .  co m*/
        configuration = ProtobufConfigFactory.build();
    } catch (ProtobufConfigurationException e) {
        String msg = "Error while loading pbs xml file " + e.getLocalizedMessage();
        log.error(msg, e);
        return;
    }

    if (!configuration.isEnabled()) {
        log.debug("ProtobufServer is not enabled in pbs xml");
        return;
    }

    log.info("Starting ProtobufServer...");

    // gathering configurations into local variables
    ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
    org.wso2.carbon.protobuf.registry.config.ServerConfiguration serverConfig = configuration
            .getServerConfiguration();
    ServerCallExecutorThreadPoolConfiguration callExecutorConfig = serverConfig
            .getServerCallExecutorThreadPoolConfiguration();
    TimeoutExecutorThreadPoolConfiguration timeoutExecutorConfig = serverConfig
            .getTimeoutExecutorThreadPoolConfiguration();
    TimeoutCheckerThreadPoolConfiguration timeoutCheckerConfig = serverConfig
            .getTimeoutCheckerThreadPoolConfiguration();
    LoggerConfiguration loggerConfig = serverConfig.getLoggerConfiguration();
    TransportConfiguration transportConfig = configuration.getTransportConfiguration();
    AcceptorsConfiguration acceptorsConfig = transportConfig.getAcceptorsConfiguration();
    ChannelHandlersConfiguration channelHandlersConfig = transportConfig.getChannelHandlersConfiguration();

    String hostName = carbonConfig.getFirstProperty("HostName");
    int port = serverConfig.getPort();
    int portOffset = Integer.parseInt(carbonConfig.getFirstProperty("Ports.Offset"));
    int effectivePort = port + portOffset;
    // server information
    PeerInfo serverInfo = new PeerInfo(hostName, effectivePort);

    int callExecutorCorePoolSize = callExecutorConfig.getCorePoolSize();
    int callExecutorMaxPoolSize = callExecutorConfig.getMaxPoolSize();
    int callExecutorMaxPoolTimeout = callExecutorConfig.getMaxPoolTimeout();
    int callExecutorWorkQueueCapacity = callExecutorConfig.getWorkQueueCapacity();
    // call executor
    RpcServerCallExecutor callExecutor = new ThreadPoolCallExecutor(callExecutorCorePoolSize,
            callExecutorMaxPoolSize, callExecutorMaxPoolTimeout, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(callExecutorWorkQueueCapacity), Executors.defaultThreadFactory());

    serverFactory = new DuplexTcpServerPipelineFactory(serverInfo);
    serverFactory.setRpcServerCallExecutor(callExecutor);

    // if SSL encryption is enabled
    if (serverConfig.isSSLEnabled()) {
        //read keystore and truststore from carbon
        String keystorePassword = carbonConfig.getFirstProperty("Security.KeyStore.Password");
        String keystorePath = carbonConfig.getFirstProperty("Security.KeyStore.Location");
        String truststorePassword = carbonConfig.getFirstProperty("Security.TrustStore.Password");
        String truststorePath = carbonConfig.getFirstProperty("Security.TrustStore.Location");
        RpcSSLContext sslCtx = new RpcSSLContext();
        sslCtx.setKeystorePassword(keystorePassword);
        sslCtx.setKeystorePath(keystorePath);
        sslCtx.setTruststorePassword(truststorePassword);
        sslCtx.setTruststorePath(truststorePath);
        try {
            sslCtx.init();
        } catch (Exception e) {
            String msg = "Couldn't create SSL Context : " + e.getLocalizedMessage();
            log.error(msg, e);
            return;
        }
        serverFactory.setSslContext(sslCtx);
    }

    // Timeout Executor
    int timeoutExecutorCorePoolSize = timeoutExecutorConfig.getCorePoolSize();
    int timeoutExecutorMaxPoolSize = timeoutExecutorConfig.getMaxPoolSize();
    int timeoutExecutorKeepAliveTime = timeoutExecutorConfig.getKeepAliveTime();
    BlockingQueue<Runnable> timeoutExecutorWorkQueue = new ArrayBlockingQueue<Runnable>(
            timeoutExecutorCorePoolSize, false);
    ThreadFactory timeoutExecutorTF = new RenamingThreadFactoryProxy("timeout",
            Executors.defaultThreadFactory());
    RpcTimeoutExecutor timeoutExecutor = new TimeoutExecutor(timeoutExecutorCorePoolSize,
            timeoutExecutorMaxPoolSize, timeoutExecutorKeepAliveTime, TimeUnit.SECONDS,
            timeoutExecutorWorkQueue, timeoutExecutorTF);

    // Timeout Checker
    int timeoutCheckerSleepTimeMs = timeoutCheckerConfig.getPeriod();
    int timeoutCheckerCorePoolSize = timeoutCheckerConfig.getCorePoolSize();
    ThreadFactory timeoutCheckerTF = new RenamingThreadFactoryProxy("check", Executors.defaultThreadFactory());
    RpcTimeoutChecker timeoutChecker = new TimeoutChecker(timeoutCheckerSleepTimeMs, timeoutCheckerCorePoolSize,
            timeoutCheckerTF);
    timeoutChecker.setTimeoutExecutor(timeoutExecutor);
    timeoutChecker.startChecking(serverFactory.getRpcClientRegistry());

    // setup a RPC event listener - it just logs what happens
    RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();
    RpcConnectionEventListener listener = new RpcConnectionEventListener() {
        @Override
        public void connectionReestablished(RpcClientChannel clientChannel) {
            log.info("Protobuf connection Reestablished " + clientChannel);
        }

        @Override
        public void connectionOpened(RpcClientChannel clientChannel) {
            log.info("Protobuf connection Opened " + clientChannel);
        }

        @Override
        public void connectionLost(RpcClientChannel clientChannel) {
            log.info("Protobuf connection Lost " + clientChannel);
        }

        @Override
        public void connectionChanged(RpcClientChannel clientChannel) {
            log.info("Protobuf connection Changed " + clientChannel);
        }
    };
    rpcEventNotifier.setEventListener(listener);
    serverFactory.registerConnectionEventListener(rpcEventNotifier);

    // ProtobufServer Logger
    boolean isLogReq = loggerConfig.isLogReqProtoEnabled();
    boolean isLogRes = loggerConfig.isLogResProtoEnabled();
    boolean isLogEve = loggerConfig.isLogEventProtoEnabled();
    CategoryPerServiceLogger logger = new CategoryPerServiceLogger();
    logger.setLogRequestProto(isLogReq);
    logger.setLogResponseProto(isLogRes);
    logger.setLogEventProto(isLogEve);

    if (isLogReq || isLogRes || isLogEve) {
        serverFactory.setLogger(logger);
    } else {
        serverFactory.setLogger(null);
    }

    // Call acceptors parameters
    int acceptorsPoolSize = acceptorsConfig.getPoolSize();
    int acceptorsSendBufferSize = acceptorsConfig.getSendBufferSize();
    int acceptorsReceiverBufferSize = acceptorsConfig.getReceiverBufferSize();
    // Channel handlers parameters
    int channelHandlersPoolSize = channelHandlersConfig.getPoolSize();
    int channelHandlersSendBufferSize = channelHandlersConfig.getSendBufferSize();
    int channelHandlersReceiverBufferSize = channelHandlersConfig.getReceiverBufferSize();
    // enable nagle's algorithm or not
    boolean tcpNoDelay = transportConfig.isTCPNoDelay();

    // boss and worker thread factories
    ThreadFactory bossTF = new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory());
    NioEventLoopGroup boss = new NioEventLoopGroup(acceptorsPoolSize, bossTF);
    ThreadFactory workersTF = new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory());
    NioEventLoopGroup workers = new NioEventLoopGroup(channelHandlersPoolSize, workersTF);

    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, workers);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_SNDBUF, acceptorsSendBufferSize);
    bootstrap.option(ChannelOption.SO_RCVBUF, acceptorsReceiverBufferSize);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, channelHandlersReceiverBufferSize);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, channelHandlersSendBufferSize);
    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
    bootstrap.childHandler(serverFactory);
    bootstrap.localAddress(serverInfo.getPort());

    // To release resources on shutdown
    CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
    shutdownHandler.addResource(boss);
    shutdownHandler.addResource(workers);
    shutdownHandler.addResource(callExecutor);
    shutdownHandler.addResource(timeoutChecker);
    shutdownHandler.addResource(timeoutExecutor);

    // Bind and start to accept incoming connections.
    bootstrap.bind();
    log.info("ProtobufServer Serving " + serverInfo);
    // Register ProtobufServer Registry as an OSGi service
    ProtobufRegistry pbsRegistry = new ProtobufRegistryImpl(serverFactory);
    bundleContext.registerService(ProtobufRegistry.class.getName(), pbsRegistry, null);
}