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.opendaylight.protocol.bmp.mock.BmpMockDispatcher.java

License:Open Source License

private ServerBootstrap createServerInstance() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override/*from   w  w w  .ja  va 2 s  .  com*/
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(BmpMockDispatcher.this.sessionFactory.getSession(ch, null));
            ch.pipeline().addLast(BmpMockDispatcher.this.hf.getEncoders());
        }
    });

    serverBootstrap.option(ChannelOption.SO_BACKLOG, MAX_CONNECTIONS_COUNT);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.group(bossGroup, workerGroup);
    return serverBootstrap;
}

From source file:org.opendaylight.protocol.framework.AbstractDispatcher.java

License:Open Source License

/**
 * Creates server. Each server needs factories to pass their instances to client sessions.
 *
 * @param address address to which the server should be bound
 * @param channelClass The {@link Class} which is used to create {@link Channel} instances from.
 * @param initializer instance of PipelineInitializer used to initialize the channel pipeline
 *
 * @return ChannelFuture representing the binding process
 *///from   w  w w . j  a  v  a  2s. c  om
protected <CH extends Channel> ChannelFuture createServer(final SocketAddress address,
        final Class<? extends ServerChannel> channelClass,
        final ChannelPipelineInitializer<CH, S> initializer) {
    final ServerBootstrap b = new ServerBootstrap();
    b.childHandler(new ChannelInitializer<CH>() {

        @Override
        protected void initChannel(final CH ch) {
            initializer.initializeChannel(ch, new DefaultPromise<S>(executor));
        }
    });

    b.option(ChannelOption.SO_BACKLOG, 128);
    if (LocalServerChannel.class.equals(channelClass) == false) {
        // makes no sense for LocalServer and produces warning
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);
    }
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    customizeBootstrap(b);

    if (b.group() == null) {
        b.group(bossGroup, workerGroup);
    }
    try {
        b.channel(channelClass);
    } catch (IllegalStateException e) {
        // FIXME: if this is ok, document why
        LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
    }

    // Bind and start to accept incoming connections.
    final ChannelFuture f = b.bind(address);
    LOG.debug("Initiated server {} at {}.", f, address);
    return f;
}

From source file:org.opendaylight.protocol.pcep.impl.PCEPDispatcherImpl.java

License:Open Source License

protected ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) {
    final ServerBootstrap b = new ServerBootstrap();
    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override/*ww  w.j a v a  2 s.com*/
        protected void initChannel(final SocketChannel ch) {
            initializer.initializeChannel(ch, new DefaultPromise(PCEPDispatcherImpl.this.executor));
        }
    });
    b.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);

    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    if (Epoll.isAvailable()) {
        b.channel(EpollServerSocketChannel.class);
        b.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        b.channel(NioServerSocketChannel.class);
    }
    if (this.keys.isPresent()) {
        if (Epoll.isAvailable()) {
            b.option(EpollChannelOption.TCP_MD5SIG, this.keys.get());
        } else {
            throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
        }
    }

    // Make sure we are doing round-robin processing
    b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, 1);

    if (b.group() == null) {
        b.group(this.bossGroup, this.workerGroup);
    }

    return b;
}

From source file:org.opendaylight.sxp.core.service.ConnectFacade.java

License:Open Source License

/**
 * Create new Node that listens to incoming connections
 *
 * @param node SxpNode containing options
 * @param hf   HandlerFactory providing handling of communication
 * @return ChannelFuture callback//  ww w.jav a2 s .  c om
 */
public static ChannelFuture createServer(final SxpNode node, final HandlerFactory hf) {
    if (!Epoll.isAvailable()) {
        throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
    }
    Map<InetAddress, byte[]> keyMapping = new HashMap<>();
    ServerBootstrap bootstrap = new ServerBootstrap();
    node.getDomains().forEach(d -> d.getConnectionTemplates().forEach(t -> {
        if (t.getTemplatePassword() != null && !t.getTemplatePassword().isEmpty()) {
            final byte[] password = t.getTemplatePassword().getBytes(StandardCharsets.US_ASCII);
            Search.expandPrefix(t.getTemplatePrefix())
                    .forEach(inetAddress -> keyMapping.put(inetAddress, password));
        }
    }));
    Collections2.filter(node.getAllConnections(), CONNECTION_ENTRY_WITH_PASSWORD).forEach(p -> keyMapping
            .put(p.getDestination().getAddress(), p.getPassword().getBytes(StandardCharsets.US_ASCII)));

    keyMapping.remove(node.getSourceIp());
    bootstrap.channel(EpollServerSocketChannel.class);
    bootstrap.option(EpollChannelOption.TCP_MD5SIG, keyMapping);
    bootstrap.group(eventLoopGroup);
    if (Configuration.NETTY_LOGGER_HANDLER) {
        bootstrap.handler(new LoggingHandler(LogLevel.INFO));
    }
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(hf.getDecoders());
            ch.pipeline().addLast(hf.getEncoders());
        }
    });
    return bootstrap.bind(node.getSourceIp(), node.getServerPort());
}

From source file:org.opendaylight.usc.plugin.UscPlugin.java

License:Open Source License

protected UscPlugin(LocalAddress localAddr) {
    LOG.debug("UscPlugin " + this + "started");
    localServerAddr = localAddr;//from   w w  w .  j a v  a  2s.  co  m

    final ServerBootstrap localServerBootstrap = new ServerBootstrap();
    localServerBootstrap.group(localGroup);
    localServerBootstrap.channel(LocalServerChannel.class);
    localServerBootstrap.childHandler(new ChannelInitializer<LocalChannel>() {
        @Override
        public void initChannel(final LocalChannel serverChannel) throws Exception {
            ChannelPipeline p = serverChannel.pipeline();
            p.addLast(new LoggingHandler("localServerBootstrp Handler 4", LogLevel.TRACE));

            // call this first so that the attribute will be visible
            // to the outside once the localAddress is set
            serverChannel.attr(SESSION).setIfAbsent(SettableFuture.<UscSessionImpl>create());

            // register the child channel by address for lookup
            // outside
            LocalAddress localAddress = serverChannel.remoteAddress();
            serverChannels.putIfAbsent(localAddress, SettableFuture.<LocalChannel>create());
            serverChannels.get(localAddress).set(serverChannel);

            p.addLast(new LoggingHandler("localServerBootstrp Handler 3", LogLevel.TRACE));

            // add remote device handler for route remote request
            p.addLast(remoteDeviceHandler);
            p.addLast(new LoggingHandler("localServerBootstrp Handler 2", LogLevel.TRACE));
            p.addLast(getMultiplexer());
            p.addLast(new LoggingHandler("localServerBootstrp Handler 1", LogLevel.TRACE));
        }
    });

    // Start the server.
    final ChannelFuture serverChannelFuture = localServerBootstrap.bind(localServerAddr);
    LOG.debug("serverChannel: " + serverChannelFuture);
}

From source file:org.opendaylight.usc.plugin.UscPluginTcp.java

License:Open Source License

/**
 * Constructs a new UscPluginTcp//  w  ww  .  ja v  a2  s.c  om
 */
public UscPluginTcp() {
    super(new LocalAddress("usc-local-server-tcp"));

    UscRouteBrokerService routeBroker = UscServiceUtils.getService(UscRouteBrokerService.class);
    if (routeBroker != null) {
        routeBroker.setConnetionManager(ChannelType.TCP, super.getConnectionManager());
        routeBroker.setConnetionManager(ChannelType.TLS, super.getConnectionManager());
    } else {
        log.error("UscRouteBrokerService is not found, failed to set connection manager for all TCP Channel!");
    }

    configService = UscServiceUtils.getService(UscConfigurationService.class);
    secureService = UscServiceUtils.getService(UscSecureService.class);
    agentBootstrap.group(agentGroup);
    agentBootstrap.channel(NioSocketChannel.class);
    agentBootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            if (secureService == null) {
                log.error("UscSecureService is not initialized!");
                return;
            }
            ChannelPipeline p = ch.pipeline();
            initAgentPipeline(p, secureService.getTcpClientHandler(ch));
        }
    });

    final ServerBootstrap callHomeServerTcpBootstrap = new ServerBootstrap();
    callHomeServerTcpBootstrap.group(agentGroup);
    callHomeServerTcpBootstrap.channel(NioServerSocketChannel.class);
    // callHomeServerTcpBootstrap.handler(new
    // LoggingHandler(LogLevel.TRACE));
    callHomeServerTcpBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        public void initChannel(final NioSocketChannel channel) throws Exception {
            if (secureService == null) {
                log.error("UscSecureService is not initialized!");
                return;
            }
            log.debug("Received call home TCP connection");

            ChannelPipeline p = channel.pipeline();

            addCallHomeConnection(channel.remoteAddress(), channel);

            initAgentPipeline(p, secureService.getTcpServerHandler(channel));
        }
    });
    if (configService == null) {
        log.error("UscConfigurationService is not initialized!");
        return;
    }
    final ChannelFuture callHomeChannelTcpFuture = callHomeServerTcpBootstrap
            .bind(configService.getConfigIntValue(UscConfigurationService.USC_PLUGIN_PORT));
    log.debug("callHomeChannelTcpFuture : " + callHomeChannelTcpFuture);
}

From source file:org.restexpress.RestExpress.java

License:Apache License

public Channel bind(InetSocketAddress ipAddress) {
    ServerBootstrap bootstrap = bootstrapFactory.newServerBootstrap(getIoThreadCount());
    bootstrap.childHandler(new PipelineInitializer().setExecutionHandler(initializeExecutorGroup())
            .addRequestHandler(buildRequestHandler()).setSSLContext(sslContext)
            .setMaxContentLength(serverSettings.getMaxContentSize())
            .setUseCompression(serverSettings.shouldUseCompression()));

    setBootstrapOptions(bootstrap);/*  w  ww . jav  a 2s.c om*/

    // Bind and start to accept incoming connections.
    if (shouldUseSystemOut()) {
        System.out.println(getName() + " server listening on port " + ipAddress.toString());
    }

    Channel channel = bootstrap.bind(ipAddress).channel();
    allChannels.add(channel);

    bindPlugins();
    return channel;
}

From source file:org.restnext.server.Server.java

License:Apache License

/**
 * Starts the server./* w  ww.  j  a  va  2  s .  c o m*/
 */
public void start() {
    loadAndPrintBanner();
    try {
        InetSocketAddress bindAddress = serverInitializer.getBindAddress();

        ServerBootstrap serverBootstrap = Epoll.isAvailable() ? newEpoolServerBootstrap()
                : newNioServerBootstrap();

        ChannelFuture channelFuture = serverBootstrap
                //.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(serverInitializer)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).bind(bindAddress).sync();

        LOGGER.info("Application is running at - {}://{}",
                serverInitializer.isSslConfigured() ? "https" : "http", bindAddress);

        channelFuture.channel().closeFuture().sync();

    } catch (Exception e) {
        throw new ServerException("Could not start the server", e);
    } finally {
        stop();
    }
}

From source file:org.rzo.netty.ahessian.application.jmx.remote.server.Server.java

License:Apache License

public static void main(String[] args) {
    Executor executor = Executors.newFixedThreadPool(200);
    ServerBootstrap bootstrap = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup childGroup = new NioEventLoopGroup();
    bootstrap.group(bossGroup, childGroup);
    bootstrap.channel(NioServerSocketChannel.class);

    bootstrap.childHandler(
            new RPCServerSessionPipelineFactory(new RPCServerMixinPipelineFactory(executor, childGroup)));

    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(8080));

}

From source file:org.rzo.netty.mcast.bridge.MulticastAccessPoint.java

License:Apache License

public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);

    bootstrap.childHandler(new ChannelPipelineFactory() {
        public HandlerList getPipeline() {
            return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {

                @Override//from w  w w. j a  v a 2s  .  c om
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (mcast != null && mcast.isInit())
                        mcast.send((ByteBuf) msg);
                }

                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    remoteChannels.add(ctx.channel());
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    remoteChannels.add(ctx.channel());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext paramChannelHandlerContext, Throwable e)
                        throws Exception {
                    Throwable cause = e.getCause();
                    System.out.println(e);
                }

            });
        }
    });
    try {
        bootstrap.bind(new InetSocketAddress(port)).sync();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    try {
        mcast.init(new ChannelPipelineFactory() {
            public HandlerList getPipeline() {
                return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf b = mcast.getMessage((ByteBuf) msg);
                        if (b == null)
                            return;
                        for (Channel c : remoteChannels) {
                            if (c.isActive())
                                c.write(b);
                        }
                    }

                });
            }
        });
    } catch (Exception e) {
        Constants.ahessianLogger.warn("", e);
    }

}