Example usage for io.netty.handler.ssl SslContextBuilder forClient

List of usage examples for io.netty.handler.ssl SslContextBuilder forClient

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder forClient.

Prototype

public static SslContextBuilder forClient() 

Source Link

Document

Creates a builder for new client-side SslContext .

Usage

From source file:org.betawares.jorre.Client.java

License:Open Source License

/**
 * Connect to a {@link Server} using the specified {@link Connection} settings.  This call
 * will block until successful or an exception is thrown.
 * /*  w  w w  . j a va  2s.  c om*/
 * @param connection    a {@link Connection} instance specifying the connection settings
 * @return true if the connection was successful, false otherwise
 */
public boolean connect(Connection connection) {

    clientMessageHandler = new ClientMessageHandler(this, connection.getMaxResponseAge());
    group = new NioEventLoopGroup();
    try {
        if (connection.isSSL()) {
            sslCtx = SslContextBuilder.forClient().build();
        } else {
            sslCtx = null;
        }
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                if (sslCtx != null) {
                    ch.pipeline()
                            .addLast(sslCtx.newHandler(ch.alloc(), connection.getHost(), connection.getPort()));
                }
                ch.pipeline().addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null)));
                ch.pipeline().addLast(new ObjectEncoder());
                //                        ch.pipeline().addLast("messageInspector", new ClientMessageInspector());
                ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(connection.getIdleTimeout(),
                        connection.getIdlePingTime(), 0, TimeUnit.MILLISECONDS));
                ch.pipeline().addLast("heartbeatHandler", new ClientHeartbeatHandler(Client.this));
                ch.pipeline().addLast("pingMessageHandler", new PingMessageHandler());
                ch.pipeline().addLast("pongMessageHandler", new PongMessageHandler());

                ch.pipeline().addLast("clientMessageHandler", clientMessageHandler);

                ch.pipeline().addLast("exceptionHandler", new ChannelHandlerAdapter() {
                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        logger.error("Communications error", cause);
                        Client.this.disconnect(DisconnectReason.IOError, true);
                    }
                });
            }
        });

        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connection.getConnectionTimeout());
        ChannelFuture future = bootstrap.connect(connection.getHost(), connection.getPort());
        channel = future.sync().channel();
        return true;
    } catch (SSLException | InterruptedException ex) {
        logger.fatal("Error connecting", ex);
        disconnect(DisconnectReason.IOError, true);
    }
    return false;
}

From source file:org.ch24.networking.game.client.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    //CLIENT_NUMBER = Integer.parseInt(args[0]);
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  www .  j a  v a 2s.  c o m*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new DiscardClientHandler());
            }
        });

        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:org.conscrypt.OpenJdkEngineFactoryConfig.java

License:Apache License

private static SslContext newNettyClientContext(io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) {
    try {//from  www  .j a va 2  s .c  om
        TestKeyStore server = TestKeyStore.getServer();
        SslContextBuilder ctx = SslContextBuilder.forClient().sslProvider(sslProvider)
                .trustManager((X509Certificate[]) server.getPrivateKey("RSA", "RSA").getCertificateChain());
        if (useAlpn) {
            ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG);
        }
        return ctx.build();
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.conscrypt.testing.TestUtil.java

License:Apache License

public static SslContext newNettyClientContext(String cipher) {
    try {/*from  w w w.  j a  v  a2s  .  co  m*/
        TestKeyStore server = TestKeyStore.getServer();
        SslContextBuilder ctx = SslContextBuilder.forClient()
                .sslProvider(io.netty.handler.ssl.SslProvider.OPENSSL)
                .trustManager((X509Certificate[]) server.getPrivateKey("RSA", "RSA").getCertificateChain());
        if (cipher != null) {
            ctx.ciphers(Collections.singletonList(cipher));
        }
        return ctx.build();
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.milo.opcua.stack.client.transport.http.OpcHttpTransport.java

License:Open Source License

private static ChannelPool createChannelPool(UaStackClientConfig config) {
    final String endpointUrl = config.getEndpoint().getEndpointUrl();

    String host = EndpointUtil.getHost(endpointUrl);
    if (host == null)
        host = "";

    int port = EndpointUtil.getPort(endpointUrl);

    LOGGER.debug("createChannelPool() host={} port={}", host, port);

    Bootstrap bootstrap = new Bootstrap().channelFactory(NioSocketChannel::new).group(config.getEventLoop())
            .remoteAddress(host, port);//from  w ww  .  j ava  2s  .  c  om

    return new SimpleChannelPool(bootstrap, new AbstractChannelPoolHandler() {
        @Override
        public void channelCreated(Channel channel) throws Exception {
            String scheme = EndpointUtil.getScheme(endpointUrl);

            if ("https".equalsIgnoreCase(scheme) || "opc.https".equalsIgnoreCase(scheme)) {
                SslContext sslContext = SslContextBuilder.forClient()
                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();

                channel.pipeline().addLast(sslContext.newHandler(channel.alloc()));
            }

            int maxMessageSize = config.getMessageLimits().getMaxMessageSize();

            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            channel.pipeline().addLast(new HttpClientCodec());
            channel.pipeline().addLast(new HttpObjectAggregator(maxMessageSize));
            channel.pipeline().addLast(new OpcClientHttpCodec(config));

            LOGGER.debug("channelCreated(): " + channel);
        }

        @Override
        public void channelAcquired(Channel channel) {
            LOGGER.debug("channelAcquired(): " + channel);
        }

        @Override
        public void channelReleased(Channel channel) {
            LOGGER.debug("channelReleased(): " + channel);
        }
    });
}

From source file:org.eclipse.milo.opcua.stack.client.transport.websocket.OpcClientWebSocketChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel channel) throws Exception {
    String endpointUrl = config.getEndpoint().getEndpointUrl();
    String scheme = EndpointUtil.getScheme(endpointUrl);

    TransportProfile transportProfile = TransportProfile.fromUri(config.getEndpoint().getTransportProfileUri());

    String subprotocol;//from w  w  w  .j a  v a  2s  .com
    if (transportProfile == TransportProfile.WSS_UASC_UABINARY) {
        subprotocol = "opcua+cp";
    } else if (transportProfile == TransportProfile.WSS_UAJSON) {
        subprotocol = "opcua+uajson";
    } else {
        throw new UaException(StatusCodes.Bad_InternalError,
                "unexpected TransportProfile: " + transportProfile);
    }

    if ("opc.wss".equalsIgnoreCase(scheme)) {
        SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                .build();

        channel.pipeline().addLast(sslContext.newHandler(channel.alloc()));
    }

    int maxMessageSize = config.getMessageLimits().getMaxMessageSize();

    channel.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
    channel.pipeline().addLast(new HttpClientCodec());
    channel.pipeline().addLast(new HttpObjectAggregator(maxMessageSize));

    channel.pipeline()
            .addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(
                    new URI(endpointUrl), WebSocketVersion.V13, subprotocol, true, new DefaultHttpHeaders(),
                    config.getMessageLimits().getMaxChunkSize())));

    channel.pipeline().addLast(new WebSocketFrameAggregator(config.getMessageLimits().getMaxMessageSize()));

    // OpcClientWebSocketFrameCodec adds UascClientAcknowledgeHandler when the WS upgrade is done.
    channel.pipeline().addLast(new OpcClientWebSocketBinaryFrameCodec(config, handshake));
}

From source file:org.glowroot.central.SyntheticMonitorService.java

License:Apache License

private static ListenableFuture<HttpResponseStatus> runPing(String url) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new IllegalStateException("URI missing scheme");
    }//from  w  w  w.  j  a v  a2  s .  c om
    final boolean ssl = uri.getScheme().equalsIgnoreCase("https");
    final String host = uri.getHost();
    if (host == null) {
        throw new IllegalStateException("URI missing host");
    }
    final int port;
    if (uri.getPort() == -1) {
        port = ssl ? 443 : 80;
    } else {
        port = uri.getPort();
    }
    final EventLoopGroup group = new NioEventLoopGroup();
    final HttpClientHandler httpClientHandler = new HttpClientHandler();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (ssl) {
                SslContext sslContext = SslContextBuilder.forClient().build();
                p.addLast(sslContext.newHandler(ch.alloc(), host, port));
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpObjectAggregator(1048576));
            p.addLast(httpClientHandler);
        }
    });
    final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    request.headers().set("Glowroot-Transaction-Type", "Synthetic");
    ChannelFuture future = bootstrap.connect(host, port);
    final SettableFuture<HttpResponseStatus> settableFuture = SettableFuture.create();
    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            Channel ch = future.channel();
            if (future.isSuccess()) {
                ch.writeAndFlush(request);
            }
            ch.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {
                        HttpResponseStatus responseStatus = httpClientHandler.responseStatus;
                        if (HttpResponseStatus.OK.equals(responseStatus)) {
                            settableFuture.set(responseStatus);
                        } else {
                            settableFuture.setException(
                                    new Exception("Unexpected http response status: " + responseStatus));
                        }
                    } else {
                        settableFuture.setException(future.cause());
                    }
                    group.shutdownGracefully();
                }
            });
        }
    });
    return settableFuture;
}

From source file:org.glowroot.common2.repo.util.HttpClient.java

License:Apache License

private String postOrGet(String url, byte /*@Nullable*/ [] content, @Nullable String contentType,
        final HttpProxyConfig httpProxyConfig, final @Nullable String passwordOverride) throws Exception {
    URI uri = new URI(url);
    String scheme = checkNotNull(uri.getScheme());
    final boolean ssl = scheme.equalsIgnoreCase("https");
    final String host = checkNotNull(uri.getHost());
    final int port;
    if (uri.getPort() == -1) {
        port = ssl ? 443 : 80;/*  w ww  .  j av  a 2 s .c  o m*/
    } else {
        port = uri.getPort();
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        // TODO follow netty proxy support at https://github.com/netty/netty/issues/1133
        final HttpProxyHandler httpProxyHandler = newHttpProxyHandlerIfNeeded(httpProxyConfig,
                passwordOverride);
        final HttpClientHandler handler = new HttpClientHandler();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (httpProxyHandler != null) {
                    p.addLast(httpProxyHandler);
                }
                if (ssl) {
                    SslContext sslContext = SslContextBuilder.forClient().build();
                    p.addLast(sslContext.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new HttpObjectAggregator(1048576));
                p.addLast(handler);
            }
        });
        if (!httpProxyConfig.host().isEmpty()) {
            // name resolution should be performed by the proxy server in case some proxy rules
            // depend on the remote hostname
            bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
        }
        HttpRequest request;
        if (content == null) {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
        } else {
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(),
                    Unpooled.wrappedBuffer(content));
            request.headers().set(HttpHeaderNames.CONTENT_TYPE, checkNotNull(contentType));
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length);
        }
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        Channel ch = bootstrap.connect(host, port).sync().channel();
        if (httpProxyHandler != null) {
            // this line is needed to capture and throw connection exception properly
            httpProxyHandler.connectFuture().get();
        }
        ch.writeAndFlush(request).get();
        ch.closeFuture().sync().get();
        Throwable exception = handler.exception;
        if (exception != null) {
            Throwables.propagateIfPossible(exception, Exception.class);
            throw new Exception(exception);
        }
        HttpResponseStatus responseStatus = checkNotNull(handler.responseStatus);
        int statusCode = responseStatus.code();
        if (statusCode == 429) {
            throw new TooManyRequestsHttpResponseException();
        } else if (statusCode < 200 || statusCode >= 300) {
            throw new IOException("Unexpected response status code: " + statusCode);
        }
        return checkNotNull(handler.responseContent);
    } finally {
        group.shutdownGracefully(0, 10, SECONDS).get();
    }
}

From source file:org.hyperledger.fabric.sdk.security.TLSCertGenTest.java

License:Open Source License

private SslContextBuilder getSslContextBuilder(File clientCertFile, File clientKeyFile, File serverCertFile) {
    SslProvider sslprovider = SslProvider.OPENSSL;
    SslContextBuilder ctxBuilder = SslContextBuilder.forClient().protocols(TLS_PROTOCOL)
            .trustManager(serverCertFile);
    SslContextBuilder clientContextBuilder = GrpcSslContexts.configure(ctxBuilder, sslprovider);
    clientContextBuilder = clientContextBuilder.keyManager(clientCertFile, clientKeyFile);
    return clientContextBuilder;
}

From source file:org.iotivity.cloud.base.HttpClient.java

License:Open Source License

public void connect(String strUrl) throws URISyntaxException, InterruptedException, SSLException {
    URI uri = new URI(strUrl);

    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();

    int port = uri.getPort();

    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//from w w w  .j a va2 s . co  m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        return;
    }

    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;

    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new HttpClientInitializer(sslCtx));

        Channel ch = b.connect(host, port).sync().channel();

        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        ch.writeAndFlush(request);

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}