Example usage for io.netty.channel.socket SocketChannel localAddress

List of usage examples for io.netty.channel.socket SocketChannel localAddress

Introduction

In this page you can find the example usage for io.netty.channel.socket SocketChannel localAddress.

Prototype

@Override
    InetSocketAddress localAddress();

Source Link

Usage

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

public CompletableFuture<ModbusTcpSlave> bind(String host, int port) {
    CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>();

    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
        @Override/*from   w  w  w  .  j  av a2 s  . c om*/
        protected void initChannel(SocketChannel channel) throws Exception {
            channelCounter.inc();
            logger.info("channel initialized: {}", channel);

            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            channel.pipeline()
                    .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder()));
            channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this));

            channel.closeFuture().addListener(future -> channelCounter.dec());
        }
    };

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    bootstrap.bind(host, port).addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            Channel channel = future.channel();
            serverChannels.put(channel.localAddress(), channel);
            bindFuture.complete(ModbusTcpSlave.this);
        } else {
            bindFuture.completeExceptionally(future.cause());
        }
    });

    return bindFuture;
}

From source file:com.tc.websocket.server.WebSocketServerInitializer.java

License:Apache License

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

    IConfig cfg = Config.getInstance();/*ww  w  .j av a2  s.  c o m*/

    //if we need to check for ByteBuf leaks.
    if (cfg.isLeakDetector()) {
        ResourceLeakDetector.setLevel(Level.ADVANCED);
    }

    //so we get enough data to build our pipeline
    ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(1024));

    ChannelPipeline pipeline = ch.pipeline();

    int incomingPort = ch.localAddress().getPort();

    //if users are coming in on a different port than the proxy port we need to redirect them.
    if (cfg.isProxy() && cfg.getPort() != incomingPort) {
        redirectBuilder.apply(pipeline);
        return;
    }

    if (cfg.isEncrypted()) {
        SslContext sslContext = factory.createSslContext(Config.getInstance());
        SSLEngine engine = sslContext.newEngine(ch.alloc());
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(cfg.isCertAuth());
        ch.pipeline().addFirst("ssl", new SslHandler(engine));
    }

    if (cfg.isProxy()) {
        pipeline.channel().config().setAutoRead(false);
        pipeline.addLast(
                guicer.inject(new ProxyFrontendHandler(cfg.getProxyBackendHost(), cfg.getProxyBackendPort())));

    } else {
        websocketBuilder.apply(pipeline);
    }

}

From source file:freddo.dtalk2.broker.netty.NettyBroker.java

License:Apache License

@Override
public void start() {
    ServerBootstrap b = new ServerBootstrap();
    b.group(mBossGroup, mWorkerGroup).handler(new LoggingHandler(LogLevel.INFO))
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w w w  .  j  av  a 2s .c om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // if (sslCtx != null) {
                    // pipeline.addLast(sslCtx.newHandler(ch.alloc()));
                    // }
                    pipeline.addLast(new HttpServerCodec());
                    pipeline.addLast(new HttpObjectAggregator(65536));
                    pipeline.addLast(new NettyBrokerHandler());
                }
            });

    try {
        // Bind and start to accept incoming connections.
        Channel ch = b.bind(mSocketAddress).sync().channel();
        mSocketAddress = (InetSocketAddress) ch.localAddress();
        LOG.info("Server binded host: {}, port: {}", mSocketAddress.getHostName(), mSocketAddress.getPort());
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void doStart(int attempt) {
    assert Thread.holdsLock(mux) : "Thread must hold lock.";

    ServerBootstrap boot = new ServerBootstrap();

    if (acceptors instanceof EpollEventLoopGroup) {
        if (DEBUG) {
            log.debug("Using EPOLL server socket channel.");
        }/*from www.j a v  a 2 s. c  om*/

        boot.channel(EpollServerSocketChannel.class);
    } else {
        if (DEBUG) {
            log.debug("Using NIO server socket channel.");
        }

        boot.channel(NioServerSocketChannel.class);
    }

    boot.group(acceptors, workers);

    setOpts(boot);
    setChildOpts(boot);

    boot.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            mayBeRetry(ctx.channel(), attempt, cause);
        }
    });

    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            InetSocketAddress remoteAddress = channel.remoteAddress();
            InetSocketAddress localAddress = channel.localAddress();

            synchronized (mux) {
                if (state == STOPPING || state == STOPPED) {
                    if (DEBUG) {
                        log.debug("Closing connection since server is in {} state [address={}].", state,
                                remoteAddress);
                    }

                    channel.close();

                    return;
                }

                // Setup pipeline.
                ChannelPipeline pipe = channel.pipeline();

                // Configure SSL.
                if (ssl != null) {
                    pipe.addLast(ssl.newHandler(channel.alloc()));
                }

                // Message codecs.
                NetworkProtocolCodec codec = new NetworkProtocolCodec(codecs);

                pipe.addLast(new NetworkProtocolVersion.Decoder());
                pipe.addLast(codec.encoder());
                pipe.addLast(codec.decoder());

                // Client handler.
                NettyServerClient client = new NettyServerClient(remoteAddress, localAddress, ssl != null,
                        hbInterval, hbLossThreshold, hbDisabled, handlers, workers);

                pipe.addLast(client);

                // Register client to this server.
                clients.put(channel, client);

                // Unregister client on disconnect.
                channel.closeFuture().addListener(close -> {
                    if (DEBUG) {
                        log.debug("Removing connection from server registry [address={}]", remoteAddress);
                    }

                    synchronized (mux) {
                        clients.remove(channel);
                    }
                });
            }
        }
    });

    ChannelFuture bindFuture = boot.bind(address);

    server = bindFuture.channel();

    bindFuture.addListener((ChannelFutureListener) bind -> {
        if (bind.isSuccess()) {
            synchronized (mux) {
                failoverInProgress = false;

                if (state == STARTING) {
                    state = STARTED;

                    // Updated since port can be automatically assigned by the underlying OS.
                    address = (InetSocketAddress) bind.channel().localAddress();

                    if (DEBUG) {
                        log.debug("Started [address={}]", address);
                    }

                    if (!startFuture.isDone() && callback != null) {
                        callback.onStart(this);
                    }

                    startFuture.complete(this);
                }
            }
        } else {
            mayBeRetry(bind.channel(), attempt, bind.cause());
        }
    });
}

From source file:org.apache.drill.exec.rpc.BasicClient.java

License:Apache License

public R initRemoteConnection(SocketChannel channel) {
    local = channel.localAddress();
    remote = channel.remoteAddress();
    return null;
}

From source file:org.apache.drill.exec.rpc.BasicServer.java

License:Apache License

@Override
public C initRemoteConnection(SocketChannel channel) {
    local = channel.localAddress();
    remote = channel.remoteAddress();
    return null;
}

From source file:org.apache.flink.mesos.util.MesosArtifactServer.java

License:Apache License

public MesosArtifactServer(String prefix, String serverHostname, int configuredPort, Configuration config)
        throws Exception {
    if (configuredPort < 0 || configuredPort > 0xFFFF) {
        throw new IllegalArgumentException("File server port is invalid: " + configuredPort);
    }//w w  w  .ja  v  a2 s  .c  om

    // Config to enable https access to the artifact server
    boolean enableSSL = config.getBoolean(ConfigConstants.MESOS_ARTIFACT_SERVER_SSL_ENABLED,
            ConfigConstants.DEFAULT_MESOS_ARTIFACT_SERVER_SSL_ENABLED) && SSLUtils.getSSLEnabled(config);

    if (enableSSL) {
        LOG.info("Enabling ssl for the artifact server");
        try {
            serverSSLContext = SSLUtils.createSSLServerContext(config);
        } catch (Exception e) {
            throw new IOException("Failed to initialize SSLContext for the artifact server", e);
        }
    } else {
        serverSSLContext = null;
    }

    router = new Router();

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            Handler handler = new Handler(router);

            // SSL should be the first handler in the pipeline
            if (serverSSLContext != null) {
                SSLEngine sslEngine = serverSSLContext.createSSLEngine();
                sslEngine.setUseClientMode(false);
                ch.pipeline().addLast("ssl", new SslHandler(sslEngine));
            }

            ch.pipeline().addLast(new HttpServerCodec()).addLast(new ChunkedWriteHandler())
                    .addLast(handler.name(), handler).addLast(new UnknownFileHandler());
        }
    };

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

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

    Channel ch = this.bootstrap.bind(serverHostname, configuredPort).sync().channel();
    this.serverChannel = ch;

    InetSocketAddress bindAddress = (InetSocketAddress) ch.localAddress();
    String address = bindAddress.getAddress().getHostAddress();
    int port = bindAddress.getPort();

    String httpProtocol = (serverSSLContext != null) ? "https" : "http";

    baseURL = new URL(httpProtocol, serverHostname, port, "/" + prefix + "/");

    LOG.info("Mesos Artifact Server Base URL: {}, listening at {}:{}", baseURL, address, port);
}

From source file:org.apache.flink.runtime.webmonitor.WebRuntimeMonitor.java

License:Apache License

public WebRuntimeMonitor(Configuration config, LeaderRetrievalService leaderRetrievalService,
        ActorSystem actorSystem) throws IOException, InterruptedException {

    this.leaderRetrievalService = checkNotNull(leaderRetrievalService);
    this.timeout = AkkaUtils.getTimeout(config);
    this.retriever = new JobManagerRetriever(this, actorSystem, AkkaUtils.getTimeout(config), timeout);

    final WebMonitorConfig cfg = new WebMonitorConfig(config);

    final int configuredPort = cfg.getWebFrontendPort();
    if (configuredPort < 0) {
        throw new IllegalArgumentException("Web frontend port is invalid: " + configuredPort);
    }//from w  w  w . j a v  a  2 s .  c om

    final WebMonitorUtils.LogFileLocation logFiles = WebMonitorUtils.LogFileLocation.find(config);

    // create an empty directory in temp for the web server
    String rootDirFileName = "flink-web-" + UUID.randomUUID();
    webRootDir = new File(getBaseDir(config), rootDirFileName);
    LOG.info("Using directory {} for the web interface files", webRootDir);

    final boolean webSubmitAllow = cfg.isProgramSubmitEnabled();
    if (webSubmitAllow) {
        // create storage for uploads
        String uploadDirName = "flink-web-upload-" + UUID.randomUUID();
        this.uploadDir = new File(getBaseDir(config), uploadDirName);
        if (!uploadDir.mkdir() || !uploadDir.canWrite()) {
            throw new IOException("Unable to create temporary directory to support jar uploads.");
        }
        LOG.info("Using directory {} for web frontend JAR file uploads", uploadDir);
    } else {
        this.uploadDir = null;
    }

    ExecutionGraphHolder currentGraphs = new ExecutionGraphHolder();

    // - Back pressure stats ----------------------------------------------

    stackTraceSamples = new StackTraceSampleCoordinator(actorSystem, 60000);

    // Back pressure stats tracker config
    int cleanUpInterval = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_CLEAN_UP_INTERVAL,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_CLEAN_UP_INTERVAL);

    int refreshInterval = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_REFRESH_INTERVAL,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_REFRESH_INTERVAL);

    int numSamples = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_NUM_SAMPLES,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_NUM_SAMPLES);

    int delay = config.getInteger(ConfigConstants.JOB_MANAGER_WEB_BACK_PRESSURE_DELAY,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_BACK_PRESSURE_DELAY);

    FiniteDuration delayBetweenSamples = new FiniteDuration(delay, TimeUnit.MILLISECONDS);

    backPressureStatsTracker = new BackPressureStatsTracker(stackTraceSamples, cleanUpInterval, numSamples,
            delayBetweenSamples);

    // --------------------------------------------------------------------

    executorService = new ForkJoinPool();

    ExecutionContextExecutor context = ExecutionContext$.MODULE$.fromExecutor(executorService);

    router = new Router()
            // config how to interact with this web server
            .GET("/config", handler(new DashboardConfigHandler(cfg.getRefreshInterval())))

            // the overview - how many task managers, slots, free slots, ...
            .GET("/overview", handler(new ClusterOverviewHandler(DEFAULT_REQUEST_TIMEOUT)))

            // job manager configuration
            .GET("/jobmanager/config", handler(new JobManagerConfigHandler(config)))

            // overview over jobs
            .GET("/joboverview", handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, true, true)))
            .GET("/joboverview/running",
                    handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, true, false)))
            .GET("/joboverview/completed",
                    handler(new CurrentJobsOverviewHandler(DEFAULT_REQUEST_TIMEOUT, false, true)))

            .GET("/jobs", handler(new CurrentJobIdsHandler(DEFAULT_REQUEST_TIMEOUT)))

            .GET("/jobs/:jobid", handler(new JobDetailsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices", handler(new JobDetailsHandler(currentGraphs)))

            .GET("/jobs/:jobid/vertices/:vertexid", handler(new JobVertexDetailsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasktimes",
                    handler(new SubtasksTimesHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/taskmanagers",
                    handler(new JobVertexTaskManagersHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/accumulators",
                    handler(new JobVertexAccumulatorsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/checkpoints",
                    handler(new JobVertexCheckpointsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/backpressure",
                    handler(new JobVertexBackPressureHandler(currentGraphs, backPressureStatsTracker,
                            refreshInterval)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/accumulators",
                    handler(new SubtasksAllAccumulatorsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum",
                    handler(new SubtaskCurrentAttemptDetailsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum/attempts/:attempt",
                    handler(new SubtaskExecutionAttemptDetailsHandler(currentGraphs)))
            .GET("/jobs/:jobid/vertices/:vertexid/subtasks/:subtasknum/attempts/:attempt/accumulators",
                    handler(new SubtaskExecutionAttemptAccumulatorsHandler(currentGraphs)))

            .GET("/jobs/:jobid/plan", handler(new JobPlanHandler(currentGraphs)))
            .GET("/jobs/:jobid/config", handler(new JobConfigHandler(currentGraphs)))
            .GET("/jobs/:jobid/exceptions", handler(new JobExceptionsHandler(currentGraphs)))
            .GET("/jobs/:jobid/accumulators", handler(new JobAccumulatorsHandler(currentGraphs)))
            .GET("/jobs/:jobid/checkpoints", handler(new JobCheckpointsHandler(currentGraphs)))

            .GET("/taskmanagers", handler(new TaskManagersHandler(DEFAULT_REQUEST_TIMEOUT)))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/metrics",
                    handler(new TaskManagersHandler(DEFAULT_REQUEST_TIMEOUT)))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/log",
                    new TaskManagerLogHandler(retriever, context, jobManagerAddressPromise.future(), timeout,
                            TaskManagerLogHandler.FileMode.LOG, config))
            .GET("/taskmanagers/:" + TaskManagersHandler.TASK_MANAGER_ID_KEY + "/stdout",
                    new TaskManagerLogHandler(retriever, context, jobManagerAddressPromise.future(), timeout,
                            TaskManagerLogHandler.FileMode.STDOUT, config))

            // log and stdout
            .GET("/jobmanager/log",
                    logFiles.logFile == null ? new ConstantTextHandler("(log file unavailable)")
                            : new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout,
                                    logFiles.logFile))

            .GET("/jobmanager/stdout",
                    logFiles.stdOutFile == null ? new ConstantTextHandler("(stdout file unavailable)")
                            : new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout,
                                    logFiles.stdOutFile))

            // Cancel a job via GET (for proper integration with YARN this has to be performed via GET)
            .GET("/jobs/:jobid/yarn-cancel", handler(new JobCancellationHandler()))

            // DELETE is the preferred way of canceling a job (Rest-conform)
            .DELETE("/jobs/:jobid/cancel", handler(new JobCancellationHandler()))

            // stop a job via GET (for proper integration with YARN this has to be performed via GET)
            .GET("/jobs/:jobid/yarn-stop", handler(new JobStoppingHandler()))

            // DELETE is the preferred way of stopping a job (Rest-conform)
            .DELETE("/jobs/:jobid/stop", handler(new JobStoppingHandler()));

    if (webSubmitAllow) {
        router
                // fetch the list of uploaded jars.
                .GET("/jars", handler(new JarListHandler(uploadDir)))

                // get plan for an uploaded jar
                .GET("/jars/:jarid/plan", handler(new JarPlanHandler(uploadDir)))

                // run a jar
                .POST("/jars/:jarid/run", handler(new JarRunHandler(uploadDir, timeout)))

                // upload a jar
                .POST("/jars/upload", handler(new JarUploadHandler(uploadDir)))

                // delete an uploaded jar from submission interface
                .DELETE("/jars/:jarid", handler(new JarDeleteHandler(uploadDir)));
    } else {
        router
                // send an Access Denied message (sort of)
                // Every other GET request will go to the File Server, which will not provide
                // access to the jar directory anyway, because it doesn't exist in webRootDir.
                .GET("/jars", handler(new JarAccessDeniedHandler()));
    }

    // this handler serves all the static contents
    router.GET("/:*",
            new StaticFileServerHandler(retriever, jobManagerAddressPromise.future(), timeout, webRootDir));

    // add shutdown hook for deleting the directories and remaining temp files on shutdown
    try {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                cleanup();
            }
        });
    } catch (IllegalStateException e) {
        // race, JVM is in shutdown already, we can safely ignore this
        LOG.debug("Unable to add shutdown hook, shutdown already in progress", e);
    } catch (Throwable t) {
        // these errors usually happen when the shutdown is already in progress
        LOG.warn("Error while adding shutdown hook", t);
    }

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            Handler handler = new Handler(router);

            ch.pipeline().addLast(new HttpServerCodec()).addLast(new HttpRequestHandler(uploadDir))
                    .addLast(handler.name(), handler).addLast(new PipelineErrorHandler(LOG));
        }
    };

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

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

    Channel ch = this.bootstrap.bind(configuredPort).sync().channel();
    this.serverChannel = ch;

    InetSocketAddress bindAddress = (InetSocketAddress) ch.localAddress();
    String address = bindAddress.getAddress().getHostAddress();
    int port = bindAddress.getPort();

    LOG.info("Web frontend listening at " + address + ':' + port);
}

From source file:org.kaazing.messaging.driver.transport.netty.tcp.NettyTransportContext.java

License:Apache License

public NettyTransportContext() {
    super();//from w  w w. j a v  a 2  s  .  c om

    if (USE_SSL) {
        SelfSignedCertificate ssc = null;
        try {
            ssc = new SelfSignedCertificate();
            serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
            clientSslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } catch (CertificateException e) {
            LOGGER.error("CertificateException", e);
            throw new IllegalArgumentException("Error creating transport context", e);
        } catch (SSLException e) {
            LOGGER.error("SSLException", e);
            throw new IllegalArgumentException("Error creating transport context", e);
        }
    } else {
        serverSslCtx = null;
        clientSslCtx = null;
    }

    // Configure the server.
    serverBossGroup = new NioEventLoopGroup(1);
    serverWorkerGroup = new NioEventLoopGroup();

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    final ChannelPipeline p = ch.pipeline();
                    if (serverSslCtx != null) {
                        p.addLast(serverSslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new LengthFieldBasedFrameDecoder(1000000, 0, 4, 0, 4));
                    serverReceivingTransportsLock.readLock().lock();
                    try {
                        serverReceivingTransports.forEach((nettyReceivingTransport) -> {
                            if (ch.localAddress().equals(nettyReceivingTransport.getInetSocketAddress())
                                    || nettyReceivingTransport.isInAddrAny()
                                            && ch.localAddress().getPort() == nettyReceivingTransport
                                                    .getInetSocketAddress().getPort()) {
                                p.addLast(nettyReceivingTransport.getNettyChannelHandler());
                            }
                        });
                    } finally {
                        serverReceivingTransportsLock.readLock().unlock();
                    }

                }
            });

    bootstrap = new Bootstrap();
    group = new NioEventLoopGroup();
    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 (clientSslCtx != null) {
                        p.addLast(clientSslCtx.newHandler(ch.alloc()));
                    }
                }
            });
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.TcpChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(final SocketChannel ch) {
    if (ch.remoteAddress() != null) {
        InetAddress radioHeadAddress = ch.remoteAddress().getAddress();
        int port = ch.localAddress().getPort();
        int remotePort = ch.remoteAddress().getPort();
        LOG.debug("Incoming connection from (remote address): {}:{} --> :{}", radioHeadAddress.toString(),
                remotePort, port);/*  w ww.j a  v a 2s  .c o  m*/

        if (!getRadioHeadConnectionHandler().accept(radioHeadAddress)) {
            ch.disconnect();
            LOG.debug("Incoming connection rejected");
            return;
        }
    }
    LOG.debug("Incoming connection accepted - building pipeline");
    allChannels.add(ch);
    ConnectionFacade connectionFacade = null;
    connectionFacade = connectionAdapterFactory.createConnectionFacade(ch, null);
    try {
        LOG.trace("initChannel - getRadioHeadConnectionHandler: {}", getRadioHeadConnectionHandler());
        getRadioHeadConnectionHandler().onRadioHeadConnected(connectionFacade);
        connectionFacade.checkListeners();
        ch.pipeline().addLast(PipelineHandlers.IDLE_HANDLER.name(),
                new IdleHandler(getRadioHeadIdleTimeout(), TimeUnit.MILLISECONDS));
        boolean tlsPresent = false;

        // If this channel is configured to support SSL it will only support SSL
        if (getTlsConfiguration() != null) {
            tlsPresent = true;
            SslContextFactory sslFactory = new SslContextFactory(getTlsConfiguration());
            SSLEngine engine = sslFactory.getServerContext().createSSLEngine();
            engine.setNeedClientAuth(true);
            engine.setUseClientMode(false);
            ch.pipeline().addLast(PipelineHandlers.SSL_HANDLER.name(), new SslHandler(engine));
        }

        ch.pipeline().addLast(PipelineHandlers.OCP_XML_DECODER.name(),
                new OCPXmlDecoder(connectionFacade, tlsPresent));
        LOG.trace("TcpChannelInitializer - initChannel OCPXmlDecoder()");

        OCPDecoder ocpDecoder = new OCPDecoder();
        ocpDecoder.setDeserializationFactory(getDeserializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OCP_DECODER.name(), ocpDecoder);
        LOG.trace("TcpChannelInitializer - initChannel ocpDecoder()");

        OCPEncoder ocpEncoder = new OCPEncoder();
        ocpEncoder.setSerializationFactory(getSerializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OCP_ENCODER.name(), ocpEncoder);
        LOG.trace("TcpChannelInitializer - initChannel ocpEncoder()");

        ch.pipeline().addLast(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name(),
                new DelegatingInboundHandler(connectionFacade));
        LOG.trace("TcpChannelInitializer - initChannel DelegatingInboundHandler()");

        if (!tlsPresent) {
            connectionFacade.fireConnectionReadyNotification();
        }
        LOG.trace("TcpChannelInitializer - initChannel End");
    } catch (Exception e) {
        LOG.warn("Failed to initialize channel", e);
        ch.close();
    }
}