List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
From source file:com.witjit.game.client.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL.git final SslContext sslCtx; if (SSL) {/* ww w .j a v a 2 s .c om*/ sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.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 (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoClientHandler()); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); sendData(f.channel()); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.xsecret.chat.client.ChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();//from ww w .j ava 2 s. c o m EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChatClientInitializer(sslCtx)); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; DataManager dataManager = new DataManager("shengxinlei", "pangff"); dataManager.start(); for (;;) { System.out.println("================"); MsgProtocol.MsgContent baseMsg = msgLinkedBlockingQueue.take(); if (baseMsg == null) { break; } if (MsgProtocol.MsgType.LOGIN.equals(baseMsg.getMsgType())) { System.out.println("=======login========="); // If user typed the 'bye' command, wait until the server closes // the connection. } else if (MsgProtocol.MsgType.LOGOUT.equals(baseMsg.getMsgType())) { System.out.println("=======logout========="); ch.closeFuture().sync(); dataManager.stopThread(); break; } else { // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(baseMsg); System.out.println(baseMsg.getMsgType() + " to " + baseMsg.getToClientId() + ": " + baseMsg.getToClientMsg()); } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java
License:Apache License
public ConnectionPool(final PulsarClientImpl client, EventLoopGroup eventLoopGroup) { this.eventLoopGroup = eventLoopGroup; this.maxConnectionsPerHosts = client.getConfiguration().getConnectionsPerBroker(); pool = new ConcurrentHashMap<>(); bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup);/*from ww w . jav a 2 s . co m*/ if (SystemUtils.IS_OS_LINUX && eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollSocketChannel.class); } else { bootstrap.channel(NioSocketChannel.class); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); bootstrap.option(ChannelOption.TCP_NODELAY, client.getConfiguration().isUseTcpNoDelay()); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ClientConfiguration clientConfig = client.getConfiguration(); if (clientConfig.isUseTls()) { SslContextBuilder builder = SslContextBuilder.forClient(); if (clientConfig.isTlsAllowInsecureConnection()) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { if (clientConfig.getTlsTrustCertsFilePath().isEmpty()) { // Use system default builder.trustManager((File) null); } else { File trustCertCollection = new File(clientConfig.getTlsTrustCertsFilePath()); builder.trustManager(trustCertCollection); } } // Set client certificate if available AuthenticationDataProvider authData = clientConfig.getAuthentication().getAuthData(); if (authData.hasDataForTls()) { builder.keyManager(authData.getTlsPrivateKey(), (X509Certificate[]) authData.getTlsCertificates()); } SslContext sslCtx = builder.build(); ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast("frameDecoder", new PulsarLengthFieldFrameDecoder(MaxMessageSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new ClientCnx(client)); } }); }
From source file:com.yahoo.pulsar.common.util.SecurityUtility.java
License:Apache License
public static SslContext createNettySslContext(boolean allowInsecureConnection, String trustCertsFilePath, Certificate[] certificates, PrivateKey privateKey) throws GeneralSecurityException, SSLException, FileNotFoundException { SslContextBuilder builder = SslContextBuilder.forClient(); if (allowInsecureConnection) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else {//from w w w. j ava 2s . c o m if (trustCertsFilePath != null && trustCertsFilePath.length() != 0) { builder.trustManager(new FileInputStream(trustCertsFilePath)); } } builder.keyManager(privateKey, (X509Certificate[]) certificates); return builder.build(); }
From source file:com.yahoo.pulsar.discovery.service.DiscoveryServiceTest.java
License:Apache License
/** * creates ClientHandler channel to connect and communicate with server * //ww w .j a v a 2 s .com * @param serviceUrl * @param latch * @return * @throws URISyntaxException */ public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException { NioEventLoopGroup workerGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (tls) { SslContextBuilder builder = SslContextBuilder.forClient(); builder.trustManager(InsecureTrustManagerFactory.INSTANCE); X509Certificate[] certificates = SecurityUtility .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH); PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH); builder.keyManager(privateKey, (X509Certificate[]) certificates); SslContext sslCtx = builder.build(); ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast(new ClientHandler(latch)); } }); URI uri = new URI(serviceUrl); InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort()); b.connect(serviceAddress).addListener((ChannelFuture future) -> { if (!future.isSuccess()) { throw new IllegalStateException(future.cause()); } }); return workerGroup; }
From source file:de.codecentric.boot.admin.server.services.endpoints.QueryIndexEndpointStrategyTest.java
License:Apache License
private ReactorClientHttpConnector httpConnector() { SslContextBuilder sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE); HttpClient client = HttpClient.create().secure(ssl -> ssl.sslContext(sslCtx)); return new ReactorClientHttpConnector(client); }
From source file:demo.netty.discard.DiscardClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w w w . j av a 2 s . 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:dna.central.httpClient.HttpSnoopClient.java
License:Apache License
@SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { URI uri = new URI(URL); 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.ja va 2 s .c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. 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); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
From source file:dpfmanager.shell.modules.client.upload.HttpClient.java
License:Open Source License
public HttpClient(DpfContext context, String url) { this.context = context; files = new ArrayList<>(); tmpFiles = new ArrayList<>(); try {//w w w. j a va 2 s. co m uri = new URI(url); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } final boolean ssl = "https".equalsIgnoreCase(scheme); if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. DiskFileUpload.deleteOnExitTemporaryFile = true; DiskFileUpload.baseDirectory = null; DiskAttribute.deleteOnExitTemporaryFile = true; DiskAttribute.baseDirectory = null; error = false; } catch (Exception e) { error = true; } }
From source file:example.http.snoop.HttpSnoopClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "example/http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("example/http".equalsIgnoreCase(scheme)) { port = 80;//from w w w . j a v a2s. c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"example/http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. 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(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); // Set some example cookies. request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }