List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
From source file:nenea.client.telnet.TelnetClient.java
License:Apache License
public void start() throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*ww w. j a v 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 TelnetClientInitializer(sslCtx)); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:net.anyflow.lannister.client.MqttClient.java
License:Apache License
public MqttConnectReturnCode connect() throws InterruptedException { group = new NioEventLoopGroup(1, new DefaultThreadFactory("lannister/client")); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w . j ava 2 s.co m*/ protected void initChannel(SocketChannel ch) throws Exception { if ("mqtts".equalsIgnoreCase(uri.getScheme())) { SslContext sslCtx = SslContextBuilder.forClient().trustManager(trustManagerFactory).build(); ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort())); } ch.pipeline().addLast(MqttDecoder.class.getName(), new MqttDecoder()); ch.pipeline().addLast(MqttEncoder.class.getName(), MqttEncoder.INSTANCE); ch.pipeline().addLast(MqttPacketReceiver.class.getName(), new MqttPacketReceiver(MqttClient.this, receiver, sharedObject)); } }); channel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel(); normalizeMessage(options.will()); send(MessageFactory.connect(options)); synchronized (sharedObject.locker()) { int timeout = Settings.SELF.getInt("lannister.client.responseTimeoutSeconds", 15); sharedObject.locker().wait(timeout * 1000); } if (sharedObject.receivedMessage() == null) { return null; } return ((MqttConnAckMessage) sharedObject.receivedMessage()).variableHeader().connectReturnCode(); }
From source file:net.anyflow.menton.http.HttpClient.java
License:Apache License
/** * request.//from w ww .jav a 2s .com * * @param receiver * @return if receiver is not null the request processed successfully, * returns HttpResponse instance, otherwise null. */ private HttpResponse request(final MessageReceiver receiver) { httpRequest().normalize(); setDefaultHeaders(httpRequest()); if (logger.isDebugEnabled()) { logger.debug(httpRequest().toString()); } final HttpClientHandler clientHandler = new HttpClientHandler(receiver, httpRequest); final EventLoopGroup group = new NioEventLoopGroup(1, new DefaultThreadFactory("client")); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if ("true".equalsIgnoreCase(Settings.SELF.getProperty("menton.logging.writelogOfNettyLogger"))) { ch.pipeline().addLast("log", new LoggingHandler("menton/server", LogLevel.DEBUG)); } if ("https".equalsIgnoreCase(httpRequest().uriObject().getScheme())) { SslContext sslCtx = SslContextBuilder.forClient().trustManager(trustManagerFactory).build(); ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), httpRequest().uriObject().getHost(), httpRequest().uriObject().getPort())); } ch.pipeline().addLast("codec", new HttpClientCodec()); ch.pipeline().addLast("inflater", new HttpContentDecompressor()); ch.pipeline().addLast("chunkAggregator", new HttpObjectAggregator(1048576)); ch.pipeline().addLast("handler", clientHandler); } }); try { Channel channel = bootstrap .connect(httpRequest().uriObject().getHost(), httpRequest().uriObject().getPort()).sync() .channel(); channel.writeAndFlush(httpRequest); if (receiver == null) { channel.closeFuture().sync(); group.shutdownGracefully(); return clientHandler.httpResponse(); } else { channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { group.shutdownGracefully(); } }); return null; } } catch (Exception e) { group.shutdownGracefully(); logger.error(e.getMessage(), e); return null; } }
From source file:netty.client.http.NettyHelloWorldClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL.git final SslContext sslCtx; if (SSL) {// w ww . j av a 2 s .c o m sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); NettyResponseLogger loggingHandler = new NettyResponseLogger(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .remoteAddress(HOST, PORT).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new HttpClientCodec()); p.addLast(loggingHandler); } }); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); channel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, GET, URL)).syncUninterruptibly(); Thread.sleep(5000); channel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, GET, URL)).syncUninterruptibly(); Thread.sleep(5000); channel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, GET, URL)).syncUninterruptibly(); // Wait until the connection is closed. System.err.println("Waiting for connection to be closed."); channel.closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:netty.http2.ConcurrentHttp2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w ww .ja va 2 s . c om*/ SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } EventLoopGroup workerGroup = new NioEventLoopGroup(); ConcurrentHttp2ClientInitializer initializer = new ConcurrentHttp2ClientInitializer(); try { // Configure the client. Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.remoteAddress(HOST, PORT); bootstrap.handler(initializer); // Start the client. Channel channel = bootstrap.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. for (int i = 0; i < 1; i++) { StreamRequest request = new StreamRequestBuilder(new URI(URL)).setMethod("GET") //.setMethod("POST") .setHeader(HttpHeaderNames.HOST.toString(), hostName.toString()) //.build(EntityStreams.emptyStream()); .build(EntityStreams .newEntityStream(new ByteStringWriter(ByteString.copy(new byte[0 * 1024])))); channel.writeAndFlush(request); System.err.println("Sent request #" + i); } } System.err.println("Finished HTTP/2 request(s)"); long start = System.currentTimeMillis(); // Wait until the connection is closed. channel.closeFuture().sync(); long end = System.currentTimeMillis(); System.err.println("Server Idled for: " + (end - start) + " milliseconds"); } finally { workerGroup.shutdownGracefully(); } }
From source file:Netty4.book.factorial.FactorialClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w w w . ja v a2 s.co 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 FactorialClientInitializer(sslCtx)); // Make a new connection. ChannelFuture f = b.connect(HOST, PORT).sync(); // Get the handler instance to retrieve the answer. FactorialClientHandler handler = (FactorialClientHandler) f.channel().pipeline().last(); // Print out the answer. // System.err.format("Factorial of %,d is: %,d", COUNT, handler.getFactorial()); System.out.println("?" + handler.getFactorial().toString()); } finally { group.shutdownGracefully(); } }
From source file:netty5.http.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w w w. j a v a 2 s . co m*/ SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE); try { // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS); HttpResponseHandler responseHandler = initializer.responseHandler(); int streamId = 3; URI hostName = URI.create((SSL ? "https" : "http") + "://" + HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().addObject(HttpHeaderNames.HOST, hostName); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); channel.writeAndFlush(request); responseHandler.put(streamId, channel.newPromise()); streamId += 2; } if (URL2 != null) { // Create a simple POST request with a body. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); request.headers().addObject(HttpHeaderNames.HOST, hostName); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); channel.writeAndFlush(request); responseHandler.put(streamId, channel.newPromise()); streamId += 2; } responseHandler.awaitResponses(5, TimeUnit.SECONDS); System.out.println("Finished HTTP/2 request(s)"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
From source file:nettyTest.httpSsl.oneWay.HttpsHelloWorldClient.java
License:Apache License
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;/* w w w .j a v a 2 s . com*/ } 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) { File certificate = new File( HttpsHelloWorldServer.class.getClassLoader().getResource("nettyca/google.crt").getFile()); //TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //TrustManagerFactory instance = SimpleTrustManagerFactory.getInstance(SimpleTrustManagerFactory.getDefaultAlgorithm()); TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); //TrustManagerFactory instance = FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = null; instance.init(keyStore); TrustManager[] tms = instance.getTrustManagers(); //instance.init(null); sslCtx = SslContextBuilder.forClient().trustManager(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 HttpsHelloWorldClientInitializer(sslCtx, host, port)); // 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.LAX .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:no.nb.nna.broprox.chrome.client.ws.WebsocketClient.java
License:Apache License
private void connect() { String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80;// www. j a v a2 s . c om } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { try { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } catch (SSLException ex) { throw new RuntimeException(ex); } } else { sslCtx = null; } workerGroup = new NioEventLoopGroup(); try { final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_PAYLOAD_LENGTH); // uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_PAYLOAD_LENGTH, true, true); final ResponseHandler handler = new ResponseHandler(); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker, false), handler); } }); channel = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); } catch (InterruptedException ex) { throw new RuntimeException(ex); } }
From source file:org.apache.activemq.artemis.core.remoting.impl.ssl.SSLSupport.java
License:Apache License
public SslContext createNettyClientContext() throws Exception { KeyStore keyStore = SSLSupport.loadKeystore(keystoreProvider, keystorePath, keystorePassword); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keystorePassword == null ? null : keystorePassword.toCharArray()); return SslContextBuilder.forClient().sslProvider(SslProvider.valueOf(sslProvider)) .keyManager(keyManagerFactory).trustManager(loadTrustManagerFactory()).build(); }