List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
From source file:example.http.upload.HttpUploadClient.java
License:Apache License
public static void main(String[] args) throws Exception { String postSimple, postFile, get; if (BASE_URL.endsWith("/")) { postSimple = BASE_URL + "formpost"; postFile = BASE_URL + "formpostmultipart"; get = BASE_URL + "formget"; } else {/*from w w w .j a v a 2 s . c o m*/ postSimple = BASE_URL + "/formpost"; postFile = BASE_URL + "/formpostmultipart"; get = BASE_URL + "/formget"; } URI uriSimple = new URI(postSimple); String scheme = uriSimple.getScheme() == null ? "example/http" : uriSimple.getScheme(); String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost(); int port = uriSimple.getPort(); if (port == -1) { if ("example/http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"example/http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } URI uriFile = new URI(postFile); File file = new File(FILE); if (!file.canRead()) { throw new FileNotFoundException(FILE); } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); // setup the factory: here using a mixed memory/disk based on size threshold HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskFileUpload.baseDirectory = null; // system temp directory DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskAttribute.baseDirectory = null; // system temp directory try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientInitializer(sslCtx)); // Simple Get form: no factory used (not usable) List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple); if (headers == null) { factory.cleanAllHttpData(); return; } // Simple Post form: factory used for big attributes List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers); if (bodylist == null) { factory.cleanAllHttpData(); return; } // Multipart Post form: factory used formpostmultipart(b, host, port, uriFile, factory, headers, bodylist); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); // Really clean all temporary files if they still exist factory.cleanAllHttpData(); } }
From source file:herddb.network.netty.NettyConnector.java
License:Apache License
public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout, ChannelEventListener receiver, final ExecutorService callbackExecutor, final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup) throws IOException { try {/*from w w w . j av a 2s . c om*/ final SslContext sslCtx = !ssl ? null : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); Class<? extends Channel> channelType; InetSocketAddress inet = new InetSocketAddress(host, port); SocketAddress address; String hostAddress = NetworkUtils.getAddress(inet); MultithreadEventLoopGroup group; if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) { channelType = LocalChannel.class; address = new LocalAddress(hostAddress + ":" + port + ":" + ssl); group = localEventsGroup; } else { channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class; address = inet; group = networkGroup; } Bootstrap b = new Bootstrap(); AtomicReference<NettyChannel> result = new AtomicReference<>(); b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .handler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel ch) throws Exception { try { NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor); result.set(channel); channel.setMessagesReceiver(receiver); if (ssl) { ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port)); } if (socketTimeout > 0) { ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout)); } ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4)); ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); // ch.pipeline().addLast("messagedecoder", new ProtocolMessageDecoder()); ch.pipeline().addLast(new ClientInboundMessageHandler(channel)); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "error connecting", t); ch.close(); } } }); LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address }); b.connect(address).sync(); NettyChannel nettyChannel = result.get(); if (!nettyChannel.isValid()) { throw new IOException("returned channel is not valid"); } return nettyChannel; } catch (InterruptedException ex) { throw new IOException(ex); } }
From source file:http.HTTPClient.java
License:Open Source License
public HTTPClient(boolean ssl, String host, int port) throws Exception { try {//from w w w . j ava 2 s .c om final SslContext sslCtx; if (ssl) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) .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; } workerGroup = new NioEventLoopGroup(); HTTPClientInitializer initializer = new HTTPClientInitializer(sslCtx, Integer.MAX_VALUE); // 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 = b.connect().syncUninterruptibly().channel(); log.info("Connected to [" + host + ':' + port + ']'); // Wait for the HTTP/2 upgrade to occur. // HTTPSettingsHandler http2SettingsHandler = initializer.settingsHandler(); // http2SettingsHandler.awaitSettings(TestUtil.HTTP2_RESPONSE_TIME_OUT, TestUtil.HTTP2_RESPONSE_TIME_UNIT); // responseHandler = initializer.responseHandler(); scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP; hostName = new AsciiString(host + ':' + port); } catch (Exception ex) { log.error("Error while initializing http2 client " + ex); this.close(); } }
From source file:http.HTTPClient2.java
License:Open Source License
public HTTPClient2(boolean ssl, String host, int port) throws Exception { try {// w ww .j a v a2 s . com final SslContext sslCtx; if (ssl) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) .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; } workerGroup = new NioEventLoopGroup(); HTTPClientInitializer initializer = new HTTPClientInitializer(sslCtx, Integer.MAX_VALUE); // 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 = b.connect().syncUninterruptibly().channel(); log.info("Connected to [" + host + ':' + port + ']'); // Wait for the HTTP/2 upgrade to occur. HTTPSettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(TestUtil.HTTP2_RESPONSE_TIME_OUT, TestUtil.HTTP2_RESPONSE_TIME_UNIT); responseHandler = initializer.responseHandler(); scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP; hostName = new AsciiString(host + ':' + port); } catch (Exception ex) { log.error("Error while initializing http2 client " + ex); this.close(); } }
From source file:http2.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from ww w . j ava2 s. 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 (URL2 != null) { logger.info("send url2"); // 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(); } }
From source file:io.airlift.drift.transport.netty.DriftNettyMethodInvokerFactory.java
License:Apache License
@Override public MethodInvoker createMethodInvoker(AddressSelector addressSelector, I clientIdentity) { DriftNettyClientConfig clientConfig = clientConfigurationProvider.apply(clientIdentity); TProtocolFactory protocolFactory;/*from www .jav a2 s . c om*/ switch (clientConfig.getProtocol()) { case BINARY: protocolFactory = new TBinaryProtocol.Factory(false, true, -1, clientConfig.getMaxFrameSize().toBytes()); break; case COMPACT: // Header transport uses the FB fork of the compact protocol if (clientConfig.getTransport() == Transport.HEADER) { protocolFactory = new TFacebookCompactProtocol.Factory( toIntExact(clientConfig.getMaxFrameSize().toBytes())); } else { protocolFactory = new TCompactProtocol.Factory(-1, clientConfig.getMaxFrameSize().toBytes()); } break; default: throw new IllegalArgumentException("Unknown protocol: " + clientConfig.getProtocol()); } MessageFraming messageFraming; MessageEncoding messageEncoding; switch (clientConfig.getTransport()) { case UNFRAMED: messageFraming = new NoMessageFraming(protocolFactory, clientConfig.getMaxFrameSize()); messageEncoding = new SimpleMessageEncoding(protocolFactory); break; case FRAMED: messageFraming = new LengthPrefixedMessageFraming(clientConfig.getMaxFrameSize()); messageEncoding = new SimpleMessageEncoding(protocolFactory); break; case HEADER: messageFraming = new LengthPrefixedMessageFraming(clientConfig.getMaxFrameSize()); messageEncoding = new HeaderMessageEncoding(protocolFactory); break; default: throw new IllegalArgumentException("Unknown transport: " + clientConfig.getTransport()); } Optional<SslContext> sslContext; if (clientConfig.isSslEnabled()) { try { SslContextBuilder sslContextBuilder = SslContextBuilder.forClient() .trustManager(clientConfig.getTrustCertificate()) .keyManager(clientConfig.getKey(), null, clientConfig.getKeyPassword()) .sessionCacheSize(clientConfig.getSessionCacheSize()) .sessionTimeout(clientConfig.getSessionTimeout().roundTo(SECONDS)); if (!clientConfig.getCiphers().isEmpty()) { sslContextBuilder.ciphers(clientConfig.getCiphers()); } sslContext = Optional.of(sslContextBuilder.build()); } catch (SSLException e) { throw new RuntimeException("Invalid SSL configuration", e); } } else { sslContext = Optional.empty(); } ConnectionManager connectionManager = new ConnectionFactory(group, messageFraming, messageEncoding, sslContext, clientConfig); if (clientConfig.isPoolEnabled()) { connectionManager = new ConnectionPool(connectionManager, group, clientConfig); } return new DriftNettyMethodInvoker(connectionManager, addressSelector); }
From source file:io.airlift.drift.transport.netty.ssl.ReloadableSslContext.java
License:Apache License
public synchronized void reload() { try {//from w w w . ja v a 2s .c om // every watch must be called each time to update status boolean trustCertificateModified = trustCertificatesFileWatch.updateState(); boolean clientCertificateModified = false; if (clientCertificatesFileWatch.isPresent()) { clientCertificateModified = clientCertificatesFileWatch.get().updateState(); } boolean privateKeyModified = false; if (privateKeyFileWatch.isPresent()) { privateKeyModified = privateKeyFileWatch.get().updateState(); } if (trustCertificateModified || clientCertificateModified || privateKeyModified) { PrivateKey privateKey = null; if (privateKeyFileWatch.isPresent()) { privateKey = loadPrivateKey(privateKeyFileWatch.get().getFile(), privateKeyPassword); } X509Certificate[] certificateChain = null; if (clientCertificatesFileWatch.isPresent()) { certificateChain = readCertificateChain(clientCertificatesFileWatch.get().getFile()) .toArray(new X509Certificate[0]); } SslContextBuilder sslContextBuilder; if (forClient) { sslContextBuilder = SslContextBuilder.forClient().keyManager(privateKey, certificateChain); } else { sslContextBuilder = SslContextBuilder.forServer(privateKey, certificateChain); } X509Certificate[] trustChain = readCertificateChain(trustCertificatesFileWatch.getFile()) .toArray(new X509Certificate[0]); sslContextBuilder.trustManager(trustChain).sessionCacheSize(sessionCacheSize) .sessionTimeout(sessionTimeout.roundTo(SECONDS)); if (!ciphers.isEmpty()) { sslContextBuilder.ciphers(ciphers); } sslContext.set(new SslContextHolder(sslContextBuilder.build())); } } catch (GeneralSecurityException e) { sslContext.set(new SslContextHolder(new UncheckedIOException(new IOException(e)))); } catch (IOException e) { sslContext.set(new SslContextHolder(new UncheckedIOException(e))); } }
From source file:io.ballerina.plugins.idea.debugger.client.WebSocketClient.java
License:Open Source License
/** * @param callback callback which should be called when a response is received. * @return true if the handshake is done properly. * @throws URISyntaxException throws if there is an error in the URI syntax. * @throws InterruptedException throws if the connecting the server is interrupted. *//* w w w . j av a 2 s.c o m*/ public boolean handshake(Callback callback) throws InterruptedException, URISyntaxException, SSLException { boolean isDone; 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; } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { LOGGER.debug("Only WS(S) is supported."); return false; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders(); headers.forEach(httpHeaders::add); 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. handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, httpHeaders), callback); 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 = b.connect(uri.getHost(), port).sync().channel(); isDone = handler.handshakeFuture().sync().isSuccess(); } catch (Exception e) { LOGGER.debug("Handshake unsuccessful : " + e.getMessage(), e); group.shutdownGracefully(); return false; } LOGGER.debug("WebSocket Handshake successful: {}", isDone); return isDone; }
From source file:io.crossbar.autobahn.wamp.transports.NettyWebSocket.java
License:MIT License
private SslContext getSSLContext(String scheme) throws SSLException { return "wss".equalsIgnoreCase(scheme) ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build() : null;/*from w w w . j a v a 2 s .co m*/ }
From source file:io.engineblock.util.SSLKsFactory.java
License:Apache License
public Object getContext(ActivityDef def) { Optional<String> sslParam = def.getParams().getOptionalString("ssl"); if (sslParam.isPresent()) { if (sslParam.get().equals("jdk") || sslParam.get().equals("true")) { if (sslParam.get().equals("true")) { logger.warn("Please update your 'ssl=true' parameter to 'ssl=jdk'"); }// w ww . j a v a2 s . c om String keystorePath = def.getParams().getOptionalString("keystore").orElse("JKS"); String keystorePass = def.getParams().getOptionalString("kspass").orElse("NONE"); String tlsVersion = def.getParams().getOptionalString("tlsversion").orElse("TLSv1.2"); try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystorePath), keystorePass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keystorePass.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); SSLContext sc = SSLContext.getInstance(tlsVersion); sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return sc; } catch (Exception e) { throw new RuntimeException(e); } } else if (sslParam.get().equals("openssl")) { logger.info("Cluster builder proceeding with SSL and Client Auth"); String keyPassword = def.getParams().getOptionalString("keyPassword").orElse(null); String caCertFileLocation = def.getParams().getOptionalString("caCertFilePath").orElse(null); String certFileLocation = def.getParams().getOptionalString("certFilePath").orElse(null); String keyFileLocation = def.getParams().getOptionalString("keyFilePath").orElse(null); try { KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, keyPassword.toCharArray()); X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509") .generateCertificate(new FileInputStream(caCertFileLocation)); //set alias to cert ks.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); TrustManagerFactory tMF = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tMF.init(ks); SslContext sslContext = SslContextBuilder.forClient() /* configured with the TrustManagerFactory that has the cert from the ca.cert * This tells the driver to trust the server during the SSL handshake */ .trustManager(tMF) /* These are needed because the server is configured with require_client_auth * In this case the client's public key must be in the truststore on each DSE * server node and the CA configured */ .keyManager(new File(certFileLocation), new File(keyFileLocation)).build(); return sslContext; } catch (Exception e) { throw new RuntimeException(e); } } else { throw new RuntimeException("The 'ssl' parameter must have one of jdk, or openssl"); } } else { return null; } }