List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClient.java
License:Open Source License
/** * @return true if the handshake is done properly. * @throws java.net.URISyntaxException throws if there is an error in the URI syntax. * @throws InterruptedException throws if the connecting the server is interrupted. *//*w w w . java 2 s. c o m*/ public boolean handhshake() 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.error("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; } group = new NioEventLoopGroup(); // 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. try { handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders().add(AUTHORIZATION_HEADER, "Bearer " + accessToken)), this); 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 ex) { LOGGER.error("Fail to connect Identity Cloud.", ex); isDone = false; } LOGGER.info("Connecting to Identity Cloud... Please wait."); Thread.sleep(5000); return isDone; }
From source file:org.wso2.carbon.transport.http.netty.sender.websocket.WebSocketClient.java
License:Open Source License
/** * Handle the handshake with the server. * * @return handshake future for connection. *//*from www .j a v a 2 s. c o m*/ public HandshakeFuture handshake() { HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl(); try { 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)) { log.error("Only WS(S) is supported."); throw new SSLException(""); } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } group = new NioEventLoopGroup(); HttpHeaders httpHeaders = new DefaultHttpHeaders(); // Adding custom headers to the handshake request. if (headers != null) { headers.entrySet().forEach(entry -> httpHeaders.add(entry.getKey(), entry.getValue())); } WebSocketClientHandshaker websocketHandshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, subProtocols, true, httpHeaders); handler = new WebSocketTargetHandler(websocketHandshaker, ssl, url, target, connectorListener); 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()); p.addLast(new HttpObjectAggregator(8192)); p.addLast(WebSocketClientCompressionHandler.INSTANCE); if (idleTimeout > 0) { p.addLast( new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS)); } p.addLast(handler); } }); b.connect(uri.getHost(), port).sync(); ChannelFuture future = handler.handshakeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { Throwable cause = future.cause(); if (future.isSuccess() && cause == null) { WebSocketSessionImpl session = (WebSocketSessionImpl) handler.getChannelSession(); String actualSubProtocol = websocketHandshaker.actualSubprotocol(); handler.setActualSubProtocol(actualSubProtocol); session.setNegotiatedSubProtocol(actualSubProtocol); session.setIsOpen(true); handshakeFuture.notifySuccess(session); } else { handshakeFuture.notifyError(cause); } } }).sync(); handshakeFuture.setChannelFuture(future); } catch (Throwable t) { handshakeFuture.notifyError(t); } return handshakeFuture; }
From source file:org.wso2.carbon.transport.http.netty.util.client.http2.HTTP2Client.java
License:Open Source License
public HTTP2Client(boolean ssl, String host, int port) throws Exception { try {/*from ww w .ja v a 2s. c o m*/ 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(); HTTP2ClientInitializer initializer = new HTTP2ClientInitializer(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. HTTP2SettingsHandler 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:org.wso2.carbon.transport.http.netty.util.client.websocket.WebSocketClient.java
License:Open Source License
/** * @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. *//* ww w . j a v a2 s .c om*/ public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException { boolean isDone = false; 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.error("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; } 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. handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, 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 = b.connect(uri.getHost(), port).sync().channel(); isDone = handler.handshakeFuture().sync().isSuccess(); } catch (Exception e) { logger.error("Handshake unsuccessful : " + e.getMessage(), e); return false; } logger.info("WebSocket Handshake successful : " + isDone); Thread.sleep(5000); return isDone; }
From source file:org.wso2.carbon.transport.http.netty.util.client.websocket.WebSocketTestClient.java
License:Open Source License
/** * @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 .ja v a 2 s . c o m*/ public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException, ProtocolException { boolean isSuccess; 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.error("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; } group = new NioEventLoopGroup(); HttpHeaders headers = new DefaultHttpHeaders(); customHeaders.entrySet().forEach(header -> headers.add(header.getKey(), header.getValue())); 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, subProtocol, true, headers), latch); 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(); isSuccess = handler.handshakeFuture().sync().isSuccess(); logger.debug("WebSocket Handshake successful : " + isSuccess); return isSuccess; } catch (Exception e) { logger.error("Handshake unsuccessful : " + e.getMessage()); throw new ProtocolException("Protocol exception: " + e.getMessage()); } }
From source file:org.wso2.carbon.websocket.transport.WebsocketConnectionFactory.java
License:Open Source License
public WebSocketClientHandler cacheNewConnection(final URI uri, final String sourceIdentifier, String dispatchSequence, String dispatchErrorSequence, String contentType) { if (log.isDebugEnabled()) { log.debug("Creating a Connection for the specified WS endpoint."); }//from www. j a va 2 s.co m final WebSocketClientHandler handler; try { String scheme = uri.getScheme() == null ? WebsocketConstants.WS : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port = uri.getPort(); if (!WebsocketConstants.WS.equalsIgnoreCase(scheme) && !WebsocketConstants.WSS.equalsIgnoreCase(scheme)) { return null; } final boolean ssl = WebsocketConstants.WSS.equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { Parameter trustParam = transportOut.getParameter(WebsocketConstants.TRUST_STORE_CONFIG_ELEMENT); OMElement tsEle = null; if (trustParam != null) { tsEle = trustParam.getParameterElement().getFirstElement(); } final String location = tsEle .getFirstChildWithName(new QName(WebsocketConstants.TRUST_STORE_LOCATION)).getText(); final String storePassword = tsEle .getFirstChildWithName(new QName(WebsocketConstants.TRUST_STORE_PASSWORD)).getText(); sslCtx = SslContextBuilder.forClient() .trustManager(SSLUtil.createTrustmanager(location, storePassword)).build(); } else { sslCtx = null; } if (sourceIdentifier.equals(WebsocketConstants.UNIVERSAL_SOURCE_IDENTIFIER)) { Parameter dispatchParam = transportOut .getParameter(WebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_SEQUENCE); if (dispatchParam != null) { dispatchSequence = dispatchParam.getParameterElement().getText(); } Parameter errorParam = transportOut .getParameter(WebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_FAULT_SEQUENCE); if (errorParam != null) { dispatchErrorSequence = errorParam.getParameterElement().getText(); } } final EventLoopGroup group = new NioEventLoopGroup(); handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, contentType != null ? SubprotocolBuilderUtil.contentTypeToSyanapeSubprotocol(contentType) : 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), new WebSocketFrameAggregator(Integer.MAX_VALUE), handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { group.shutdownGracefully(); removeChannelHandler(sourceIdentifier, getClientHandlerIdentifier(uri)); } }); handler.setDispatchSequence(dispatchSequence); handler.setDispatchErrorSequence(dispatchErrorSequence); addChannelHandler(sourceIdentifier, getClientHandlerIdentifier(uri), handler); return handler; } catch (InterruptedException e) { log.error("Interruption occured while connecting to the remote WS endpoint", e); } catch (SSLException e) { log.error("Error occurred while building the SSL context fo WSS endpoint", e); } return null; }
From source file:org.wso2.esb.integration.common.utils.clients.Http2Client.java
License:Open Source License
private SslContext generateSSLContext(TrustManagerFactory trustManager) throws SSLException { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; return SslContextBuilder.forClient().sslProvider(provider).trustManager(trustManager) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build();/*from w w w .ja v a 2 s . c om*/ }
From source file:org.wso2.gw.emulator.http.client.HttpClientInitializer.java
License:Open Source License
public void initialize() throws Exception { final boolean ssl = "https".equalsIgnoreCase(null); final SslContext sslCtx; if (ssl) {/* www . ja v a 2 s . c o m*/ sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); ChannelPipelineInitializer channelPipelineInitializer = new ChannelPipelineInitializer(sslCtx, EmulatorType.HTTP_CLIENT); channelPipelineInitializer.setClientInformationContext(clientInformationContext); bootstrap.group(group).channel(NioSocketChannel.class).handler(channelPipelineInitializer); for (Map.Entry<HttpClientRequestBuilderContext, HttpClientResponseBuilderContext> entry : clientInformationContext .getRequestResponseCorrelation().entrySet()) { clientInformationContext.setExpectedResponse(entry.getValue()); HttpClientRequestProcessorContext httpClientRequestProcessorContext = new HttpClientRequestProcessorContext(); httpClientRequestProcessorContext.setRequestBuilderContext(entry.getKey()); sendMessage(httpClientRequestProcessorContext); } }
From source file:org.wso2.gw.emulator.http.client.HttpEmulatorProducerInitializer.java
License:Open Source License
private void sendMessage(IncomingMessage incomingMessage, OutgoingMessage outgoingMessage) throws Exception { final boolean ssl = "https".equalsIgnoreCase(null); final SslContext sslCtx; if (ssl) {//from w w w.j a va2 s . com sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } HttpRequest httpRequest = new HttpRequestInformationProcessor().populateHttpRequest(producerContext, incomingMessage); group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); ChannelPipelineInitializer channelPipelineInitializer = new ChannelPipelineInitializer(sslCtx, EmulatorType.HTTP_PRODUCER); channelPipelineInitializer.setProducerOutgoingMessage(outgoingMessage); b.group(group).channel(NioSocketChannel.class).handler(channelPipelineInitializer); Channel ch = b.connect(producerContext.getHost(), producerContext.getPort()).sync().channel(); ch.writeAndFlush(httpRequest); ch.closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:org.wso2.msf4j.util.client.websocket.WebSocketClient.java
License:Open Source License
/** * @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. */// ww w.ja v a 2 s . co m public boolean handhshake() 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.error("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; } group = new NioEventLoopGroup(); HttpHeaders headers = new DefaultHttpHeaders(); customHeaders.entrySet().forEach(header -> headers.add(header.getKey(), header.getValue())); 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, subProtocol, true, headers)); 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(); logger.debug("WebSocket Handshake successful : " + isDone); return isDone; } catch (Exception e) { logger.error("Handshake unsuccessful : " + e.getMessage(), e); return false; } }