List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
From source file:com.gdut.Netty_testing.time_server.client.TimeClient.java
License:Apache License
/** * //w w w. j av a 2 s. c o m * @Title: main * @Description: TODO * @param @param args * @param @throws Exception * @return void * @throws */ public static void main(String[] args) throws Exception { // Configure SSL.git 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).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler(), new TimeOutBoundHandler(), new LoggingHandler(LogLevel.INFO)); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); // channel.connect(remoteAddress, promise); // ?connect()??OutboundHandler // ?InboundHandlerlogic??? // ?? // InboundHandler?writeAndFlush(Object // msg)??OutBoundHandler // ?? ctx.write(encoded, promise); // writeAndFlush(Object msg) // ?InboundHandler decoder? // ?TimeClientHandler()Handler, // ctx.close();?OutBoundHandler ? Thread.sleep(9000); // 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.github.ambry.rest.NettySslFactory.java
License:Open Source License
/** * @param config the {@link SSLConfig}//from w w w . j a v a 2s . c o m * @return a configured {@link SslContext} object for a server. * @throws GeneralSecurityException * @throws IOException */ private static SslContext getClientSslContext(SSLConfig config) throws GeneralSecurityException, IOException { logger.info("Using {} provider for client SslContext", SslContext.defaultClientProvider()); return SslContextBuilder.forClient().keyManager(getKeyManagerFactory(config)) .trustManager(getTrustManagerFactory(config)).ciphers(getCipherSuites(config)) .protocols(getEnabledProtocols(config)).build(); }
From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java
License:Apache License
ChannelHandler newSslInitiator() { return new ByteToMessageDecoder() { @Override// w w w . j ava2 s.c om protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 1) { return; } if ('S' != in.readByte()) { ctx.fireExceptionCaught( new IllegalStateException("SSL required but not supported by backend server")); return; } ctx.pipeline().remove(this); ctx.pipeline().addFirst(SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build().newHandler(ctx.alloc())); } }; }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception { boolean useTls = uri.getScheme().equals("https"); if (uri.getPort() == -1) { int port = useTls ? 443 : 80; uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment());/*from w w w. jav a 2s . com*/ } this.uri = uri; final SslContext sslCtx; if (useTls) { // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative // to be there which is not available on all platforms and environments. SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build(); } else { sslCtx = null; } Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop) .remoteAddress(uri.getHost(), uri.getPort()); downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) { ch.pipeline().remove("read-timeout-handler"); } @Override public void channelAcquired(Channel ch) { ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis)); } @Override public void channelCreated(Channel ch) { ChannelPipeline p = ch.pipeline(); p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis)); if (sslCtx != null) { SSLEngine engine = sslCtx.newEngine(ch.alloc()); engine.setUseClientMode(true); p.addFirst(new SslHandler(engine)); } p.addLast(new HttpClientCodec()); p.addLast(new HttpDownloadHandler(creds)); } }); uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) { } @Override public void channelAcquired(Channel ch) { } @Override public void channelCreated(Channel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { SSLEngine engine = sslCtx.newEngine(ch.alloc()); engine.setUseClientMode(true); p.addFirst(new SslHandler(engine)); } p.addLast(new HttpResponseDecoder()); // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with // an error message in the body and that should always be less than 10KiB. p.addLast(new HttpObjectAggregator(10 * 1024)); p.addLast(new HttpRequestEncoder()); p.addLast(new ChunkedWriteHandler()); p.addLast(new HttpUploadHandler(creds)); } }); this.creds = creds; }
From source file:com.hazelcast.openshift.TunnelServerConnector.java
License:Open Source License
protected Bootstrap createBootstrap(Channel socket, Promise promise) throws Exception { SslContext sslContext;//from w w w.j a v a 2 s.co m if (!ssl) { sslContext = null; } else { sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } return new Bootstrap().channel(NioSocketChannel.class).group(workerGroup) .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { System.out.println( "Configure plain-socket: (" + socket + ") => (" + httpHost + ":" + httpPort + ")"); ChannelPipeline pipeline = channel.pipeline(); if (sslContext != null) { pipeline.addLast("ssl", sslContext.newHandler(channel.alloc())); } pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast(new TunnelServerAcceptor(socket, promise)); } }); }
From source file:com.hipishare.chat.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();//from w w w .j ava2s .co m EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // channel.closeFuture().sync(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // 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. LOG.info("isActive=" + channel.isActive()); LOG.info("isOpen=" + channel.isOpen()); LOG.info("isWritable=" + channel.isWritable()); if (!channel.isOpen()) { reConnect(); } lastWriteFuture = channel.writeAndFlush("[channelId=" + channel.id() + "]" + line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.closeFuture().sync(); break; } } // 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.hipishare.chat.securetest.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();/*from w w w. ja va2 s .c o m*/ EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // 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. if (!channel.isOpen()) { reConnect(); } MsgObject msgObj = new MsgObject(); Gson gson = new Gson(); if ("1".equals(line)) { User user = new User(); user.setAccount("peter"); user.setPwd("666666"); msgObj.setC(CmdEnum.LOGIN.getCmd()); msgObj.setM(gson.toJson(user)); } else if ("2".equals(line)) { ChatObject co = new ChatObject(); co.setContent("hello,jack. I am peter."); co.setMsgType("text"); co.setMsgTo("jack"); co.setMsgFrom("peter"); co.setCreateTime(System.currentTimeMillis()); msgObj.setC(CmdEnum.CHAT.getCmd()); msgObj.setM(gson.toJson(co)); } else if ("3".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER_CODE.getCmd()); msgObj.setM(gson.toJson(rc)); } else if ("4".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setCode("3243"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER.getCmd()); msgObj.setM(gson.toJson(rc)); } String msg = gson.toJson(msgObj); ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes()); lastWriteFuture = channel.writeAndFlush(buf); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } channel.closeFuture().sync(); } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.hipishare.chat.test.EchoClient.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 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(); // 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.hop.hhxx.example.http.websocketx.client.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); 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;//from www .j ava 2 s.c o m } 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) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).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), WebSocketClientCompressionHandler.INSTANCE, handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame( Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:com.hop.hhxx.example.http2.helloworld.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*w ww . j a v a2s .c o 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; 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. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), 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().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), 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(); } }