Example usage for io.netty.handler.ssl SslContext newClientContext

List of usage examples for io.netty.handler.ssl SslContext newClientContext

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContext newClientContext.

Prototype

@Deprecated
public static SslContext newClientContext() throws SSLException 

Source Link

Document

Creates a new client-side SslContext .

Usage

From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketBase.java

License:Apache License

private void connect() {
    try {//from  www  . j a  v a2  s  . c  o  m
        final URI uri = new URI(url);
        if (uri == null) {
            return;
        }
        if (uri.getHost().contains("com")) {
            siteFlag = 1;
        }
        group = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();
        final SslContext sslCtx = SslContext.newClientContext();
        final WebSocketClientHandler handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        new DefaultHttpHeaders(), Integer.MAX_VALUE),
                service, moniter);
        bootstrap.group(group).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
                        }
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                    }
                });

        future = bootstrap.connect(uri.getHost(), uri.getPort());
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture future) throws Exception {
            }
        });
        channel = future.sync().channel();
        handler.handshakeFuture().sync();
        this.setStatus(true);
    } catch (Exception e) {
        Log.e(TAG, "WebSocketClient start error " + e.getLocalizedMessage());
        group.shutdownGracefully();
        this.setStatus(false);
    }
}

From source file:com.google.cloud.bigtable.hbase.BigtableOptions.java

License:Open Source License

private TransportOptions createTransportOptions(InetAddress host) throws IOException {
    return new TransportOptions(TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, host, port,
            new TransportOptions.SslContextFactory() {
                @Override/*from  w ww . j  av  a  2 s.c  o  m*/
                public SslContext create() {
                    try {
                        // We create multiple channels via refreshing and pooling channel implementation.
                        // Each one needs its own SslContext.
                        return SslContext.newClientContext();
                    } catch (SSLException e) {
                        throw new IllegalStateException("Could not create an ssl context.", e);
                    }
                }
            }, customEventLoopGroup);
}

From source file:com.ibm.mqlight.api.impl.network.NettyNetworkService.java

License:Apache License

@Override
public void connect(Endpoint endpoint, NetworkListener listener, Promise<NetworkChannel> promise) {
    final String methodName = "connect";
    logger.entry(this, methodName, endpoint, listener, promise);

    SslContext sslCtx = null;//from w  w w. j a  va2 s. c om
    try {
        if (endpoint.getCertChainFile() != null && endpoint.getCertChainFile().exists()) {
            try (FileInputStream fileInputStream = new FileInputStream(endpoint.getCertChainFile())) {
                KeyStore jks = KeyStore.getInstance("JKS");
                jks.load(fileInputStream, null);
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(jks);
                sslCtx = SslContext.newClientContext();
                if (sslCtx instanceof JdkSslContext) {
                    ((JdkSslContext) sslCtx).context().init(null, trustManagerFactory.getTrustManagers(), null);
                }
            } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
                    | KeyManagementException e) {
                logger.data(this, methodName, e.toString());
            }
        }
        // fallback to passing as .PEM file (or null, which loads default cacerts)
        if (sslCtx == null) {
            sslCtx = SslContext.newClientContext(endpoint.getCertChainFile());
        }

        final SSLEngine sslEngine = sslCtx.newEngine(null, endpoint.getHost(), endpoint.getPort());
        sslEngine.setUseClientMode(true);

        final LinkedList<String> enabledProtocols = new LinkedList<String>() {
            private static final long serialVersionUID = 7838479468739671083L;
            {
                for (String protocol : sslEngine.getSupportedProtocols()) {
                    if (!disabledProtocolPattern.matcher(protocol).matches()) {
                        add(protocol);
                    }
                }
            }
        };
        sslEngine.setEnabledProtocols(enabledProtocols.toArray(new String[0]));
        logger.data(this, methodName, "enabledProtocols", Arrays.toString(sslEngine.getEnabledProtocols()));

        final LinkedList<String> enabledCipherSuites = new LinkedList<String>() {
            private static final long serialVersionUID = 7838479468739671083L;
            {
                for (String cipher : sslEngine.getSupportedCipherSuites()) {
                    if (!disabledCipherPattern.matcher(cipher).matches()) {
                        add(cipher);
                    }
                }
            }
        };
        sslEngine.setEnabledCipherSuites(enabledCipherSuites.toArray(new String[0]));
        logger.data(this, methodName, "enabledCipherSuites",
                Arrays.toString(sslEngine.getEnabledCipherSuites()));

        if (endpoint.getVerifyName()) {
            SSLParameters sslParams = sslEngine.getSSLParameters();
            sslParams.setEndpointIdentificationAlgorithm("HTTPS");
            sslEngine.setSSLParameters(sslParams);
        }

        // The listener must be added to the ChannelFuture before the bootstrap channel initialisation completes (i.e.
        // before the NettyInboundHandler is added to the channel pipeline) otherwise the listener may not be able to 
        // see the NettyInboundHandler, when its operationComplete() method is called (there is a small window where
        // the socket connection fails just after initChannel has complete but before ConnectListener is added, with
        // the ConnectListener.operationComplete() being called as though the connection was successful)
        // Hence we synchronise here and within the ChannelInitializer.initChannel() method.
        synchronized (bootstrapSync) {
            final ChannelHandler handler;
            if (endpoint.useSsl()) {
                handler = new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        synchronized (bootstrapSync) {
                            ch.pipeline().addFirst(new SslHandler(sslEngine));
                            ch.pipeline().addLast(new NettyInboundHandler(ch));
                        }
                    }
                };
            } else {
                handler = new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        synchronized (bootstrapSync) {
                            ch.pipeline().addLast(new NettyInboundHandler(ch));
                        }
                    }
                };
            }
            final Bootstrap bootstrap = getBootstrap(endpoint.useSsl(), sslEngine, handler);
            final ChannelFuture f = bootstrap.connect(endpoint.getHost(), endpoint.getPort());
            f.addListener(new ConnectListener(endpoint, f, promise, listener));
        }

    } catch (SSLException e) {
        if (e.getCause() == null) {
            promise.setFailure(new SecurityException(e.getMessage(), e));
        } else {
            promise.setFailure(new SecurityException(e.getCause().getMessage(), e.getCause()));
        }
    }

    logger.exit(this, methodName);
}

From source file:com.kixeye.kixmpp.server.KixmppServerTest.java

License:Apache License

@Test
public void testUserMapping() throws Exception {
    try (KixmppServer server = new KixmppServer(new InetSocketAddress(SocketUtils.findAvailableTcpPort()),
            "testChat", new InetSocketAddress(SocketUtils.findAvailableTcpPort()), new ConstNodeDiscovery())) {
        Assert.assertNotNull(server.start().get(2, TimeUnit.SECONDS));

        ((InMemoryAuthenticationService) server.module(SaslKixmppServerModule.class).getAuthenticationService())
                .addUser("testUser", "testPassword");
        server.module(MucKixmppServerModule.class).addService("conference").addRoom("someRoom");

        try (KixmppClient client = new KixmppClient(SslContext.newClientContext(), KixmppClient.Type.TCP)) {
            final LinkedBlockingQueue<Presence> presences = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucJoin> mucJoins = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucMessage> mucMessages = new LinkedBlockingQueue<>();

            Assert.assertNotNull(/*from  w  ww .j  a  va 2 s  .c o m*/
                    client.connect("localhost", server.getBindAddress().getPort(), server.getDomain()).get(2,
                            TimeUnit.SECONDS));

            client.module(PresenceKixmppClientModule.class).addPresenceListener(new PresenceListener() {
                public void handle(Presence presence) {
                    presences.offer(presence);
                }
            });

            client.module(MucKixmppClientModule.class).addJoinListener(new MucListener<MucJoin>() {
                public void handle(MucJoin event) {
                    mucJoins.offer(event);
                }
            });

            client.module(MucKixmppClientModule.class).addMessageListener(new MucListener<MucMessage>() {
                public void handle(MucMessage event) {
                    mucMessages.offer(event);
                }
            });

            Assert.assertNotNull(
                    client.login("testUser", "testPassword", "testResource").get(2, TimeUnit.SECONDS));
            client.module(PresenceKixmppClientModule.class).updatePresence(new Presence());

            Assert.assertNotNull(server.getChannel(KixmppJid.fromRawJid("testUser@testchat/testResource")));
        }

        int count = 0;

        while (count < 50
                && server.getChannel(KixmppJid.fromRawJid("testUser@testchat/testResource")) != null) {
            count++;
            System.gc();
            Thread.sleep(100);
        }

        Assert.assertNull(server.getChannel(KixmppJid.fromRawJid("testUser@testchat/testResource")));
    }
}

From source file:com.kixeye.kixmpp.server.KixmppServerTest.java

License:Apache License

@Test
public void testSimpleUsingKixmpp() throws Exception {
    try (KixmppServer server = new KixmppServer(new InetSocketAddress(SocketUtils.findAvailableTcpPort()),
            "testChat", new InetSocketAddress(SocketUtils.findAvailableTcpPort()), new ConstNodeDiscovery())) {
        Assert.assertNotNull(server.start().get(2, TimeUnit.SECONDS));

        ((InMemoryAuthenticationService) server.module(SaslKixmppServerModule.class).getAuthenticationService())
                .addUser("testUser", "testPassword");
        server.module(MucKixmppServerModule.class).addService("conference").addRoom("someRoom");

        try (KixmppClient client = new KixmppClient(SslContext.newClientContext(), KixmppClient.Type.TCP)) {
            final LinkedBlockingQueue<Presence> presences = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucJoin> mucJoins = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucMessage> mucMessages = new LinkedBlockingQueue<>();

            Assert.assertNotNull(/*from   w ww. jav  a  2 s .c  o m*/
                    client.connect("localhost", server.getBindAddress().getPort(), server.getDomain()).get(2,
                            TimeUnit.SECONDS));

            client.module(PresenceKixmppClientModule.class).addPresenceListener(new PresenceListener() {
                public void handle(Presence presence) {
                    presences.offer(presence);
                }
            });

            client.module(MucKixmppClientModule.class).addJoinListener(new MucListener<MucJoin>() {
                public void handle(MucJoin event) {
                    mucJoins.offer(event);
                }
            });

            client.module(MucKixmppClientModule.class).addMessageListener(new MucListener<MucMessage>() {
                public void handle(MucMessage event) {
                    mucMessages.offer(event);
                }
            });

            Assert.assertNotNull(
                    client.login("testUser", "testPassword", "testResource").get(2, TimeUnit.SECONDS));
            client.module(PresenceKixmppClientModule.class).updatePresence(new Presence());

            Assert.assertNotNull(presences.poll(2, TimeUnit.SECONDS));

            client.module(MucKixmppClientModule.class)
                    .joinRoom(KixmppJid.fromRawJid("someRoom@conference.testChat"), "testNick");

            MucJoin mucJoin = mucJoins.poll(2, TimeUnit.SECONDS);

            Assert.assertNotNull(mucJoin);

            client.module(MucKixmppClientModule.class).sendRoomMessage(mucJoin.getRoomJid(), "someMessage",
                    "testNick");

            MucMessage mucMessage = mucMessages.poll(2, TimeUnit.SECONDS);

            Assert.assertNotNull(mucMessage);
            Assert.assertEquals("someMessage", mucMessage.getBody());
        }
    }
}

From source file:com.kixeye.kixmpp.server.KixmppServerTest.java

License:Apache License

@Test
public void testSimpleUsingKixmppWithWebSocket() throws Exception {
    try (KixmppServer server = new KixmppServer(new InetSocketAddress(SocketUtils.findAvailableTcpPort()),
            "testChat", new InetSocketAddress(SocketUtils.findAvailableTcpPort()), new ConstNodeDiscovery())) {
        server.enableWebSocket();// w w  w . ja  v a  2 s . c  o  m

        Assert.assertNotNull(server.start().get(2, TimeUnit.SECONDS));

        ((InMemoryAuthenticationService) server.module(SaslKixmppServerModule.class).getAuthenticationService())
                .addUser("testUser", "testPassword");
        server.module(MucKixmppServerModule.class).addService("conference").addRoom("someRoom");

        try (KixmppClient client = new KixmppClient(SslContext.newClientContext(),
                KixmppClient.Type.WEBSOCKET)) {
            final LinkedBlockingQueue<Presence> presences = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucJoin> mucJoins = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucMessage> mucMessages = new LinkedBlockingQueue<>();

            Assert.assertNotNull(
                    client.connect("localhost", server.getWebSocketAddress().getPort(), server.getDomain())
                            .get(2, TimeUnit.SECONDS));

            client.module(PresenceKixmppClientModule.class).addPresenceListener(new PresenceListener() {
                public void handle(Presence presence) {
                    presences.offer(presence);
                }
            });

            client.module(MucKixmppClientModule.class).addJoinListener(new MucListener<MucJoin>() {
                public void handle(MucJoin event) {
                    mucJoins.offer(event);
                }
            });

            client.module(MucKixmppClientModule.class).addMessageListener(new MucListener<MucMessage>() {
                public void handle(MucMessage event) {
                    mucMessages.offer(event);
                }
            });

            Assert.assertNotNull(
                    client.login("testUser", "testPassword", "testResource").get(2, TimeUnit.SECONDS));
            client.module(PresenceKixmppClientModule.class).updatePresence(new Presence());

            Assert.assertNotNull(presences.poll(2, TimeUnit.SECONDS));

            client.module(MucKixmppClientModule.class)
                    .joinRoom(KixmppJid.fromRawJid("someRoom@conference.testChat"), "testNick");

            MucJoin mucJoin = mucJoins.poll(2, TimeUnit.SECONDS);

            Assert.assertNotNull(mucJoin);

            client.module(MucKixmppClientModule.class).sendRoomMessage(mucJoin.getRoomJid(), "someMessage",
                    "testNick");

            MucMessage mucMessage = mucMessages.poll(2, TimeUnit.SECONDS);

            Assert.assertNotNull(mucMessage);
            Assert.assertEquals("someMessage", mucMessage.getBody());
        }
    }
}

From source file:com.kixeye.kixmpp.server.KixmppServerTest.java

License:Apache License

@Test
public void testSimpleUsingKixmppWithHistory() throws Exception {
    try (KixmppServer server = new KixmppServer(new InetSocketAddress(SocketUtils.findAvailableTcpPort()),
            "testChat", new InetSocketAddress(SocketUtils.findAvailableTcpPort()), new ConstNodeDiscovery())) {
        Assert.assertNotNull(server.start().get(2, TimeUnit.SECONDS));

        ((InMemoryAuthenticationService) server.module(SaslKixmppServerModule.class).getAuthenticationService())
                .addUser("testUser", "testPassword");
        server.module(MucKixmppServerModule.class).addService("conference").addRoom("someRoom");

        server.module(MucKixmppServerModule.class).setHistoryProvider(new MucHistoryProvider() {
            public Promise<List<MucHistory>> getHistory(KixmppJid roomJid, KixmppJid userJid, Integer maxChars,
                    Integer maxStanzas, Integer seconds, String since) {
                Promise<List<MucHistory>> promise = server.createPromise();
                List<MucHistory> history = new ArrayList<>(maxStanzas);

                for (int i = 0; i < maxStanzas; i++) {
                    history.add(new MucHistory(
                            KixmppJid.fromRawJid("user" + i + "@" + server.getDomain() + "/computer"), roomJid,
                            "nick" + i, "message" + i, System.currentTimeMillis()));
                }//from  w  ww.  jav  a  2  s .c  o  m

                promise.setSuccess(history);
                return promise;
            }
        });

        try (KixmppClient client = new KixmppClient(SslContext.newClientContext(), KixmppClient.Type.TCP)) {
            final LinkedBlockingQueue<Presence> presences = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucJoin> mucJoins = new LinkedBlockingQueue<>();
            final LinkedBlockingQueue<MucMessage> mucMessages = new LinkedBlockingQueue<>();

            Assert.assertNotNull(
                    client.connect("localhost", server.getBindAddress().getPort(), server.getDomain()).get(2,
                            TimeUnit.SECONDS));

            client.module(PresenceKixmppClientModule.class).addPresenceListener(new PresenceListener() {
                public void handle(Presence presence) {
                    presences.offer(presence);
                }
            });

            client.module(MucKixmppClientModule.class).addJoinListener(new MucListener<MucJoin>() {
                public void handle(MucJoin event) {
                    mucJoins.offer(event);
                }
            });

            client.module(MucKixmppClientModule.class).addMessageListener(new MucListener<MucMessage>() {
                public void handle(MucMessage event) {
                    mucMessages.offer(event);
                }
            });

            Assert.assertNotNull(
                    client.login("testUser", "testPassword", "testResource").get(2, TimeUnit.SECONDS));
            client.module(PresenceKixmppClientModule.class).updatePresence(new Presence());

            Assert.assertNotNull(presences.poll(2, TimeUnit.SECONDS));

            client.module(MucKixmppClientModule.class).joinRoom(
                    KixmppJid.fromRawJid("someRoom@conference.testChat"), "testNick", 5, null, null, null);

            MucJoin mucJoin = mucJoins.poll(2, TimeUnit.SECONDS);

            Assert.assertNotNull(mucJoin);

            int count = 0;

            while (mucMessages.poll(2, TimeUnit.SECONDS) != null) {
                count++;
            }

            Assert.assertEquals(5, count);
        }
    }
}

From source file:com.xx_dev.port_forwared.HexDumpProxyBackendInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws SSLException {
    if (remoteSsl) {
        SslContext sslCtx = SslContext.newClientContext();
        ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
    }//from  w  w  w .  ja v a2s . c o  m
    ch.pipeline().addLast(new HexDumpProxyBackendHandler(inboundChannel));
}