use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project pravega by pravega.
the class ConnectionFactoryImplTest method setUp.
@Before
public void setUp() throws Exception {
// Configure SSL.
port = TestUtils.getAvailableListenPort();
final SslContext sslCtx;
if (ssl) {
try {
sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
boolean nio = false;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
try {
bossGroup = new EpollEventLoopGroup(1);
workerGroup = new EpollEventLoopGroup();
} catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
nio = true;
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
}
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler handler = sslCtx.newHandler(ch.alloc());
SSLEngine sslEngine = handler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
sslEngine.setSSLParameters(sslParameters);
p.addLast(handler);
}
}
});
// Start the server.
serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project web3sdk by FISCO-BCOS.
the class ChannelConnections method startListen.
public void startListen(Integer port) {
if (running) {
logger.debug("服务已启动");
return;
}
logger.debug("初始化connections listen");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
final ChannelConnections selfService = this;
final ThreadPoolTaskExecutor selfThreadPool = threadPool;
try {
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource keystoreResource = resolver.getResource(getClientKeystorePath());
Resource caResource = resolver.getResource(getCaCertPath());
ks.load(keystoreResource.getInputStream(), getKeystorePassWord().toCharArray());
/*
* 每次连接使用新的handler
* 连接信息从socketChannel中获取
*/
ChannelHandler handler = new ChannelHandler();
handler.setConnections(selfService);
handler.setIsServer(true);
handler.setThreadPool(selfThreadPool);
SslContext sslCtx = SslContextBuilder.forServer((PrivateKey) ks.getKey("client", getClientCertPassWord().toCharArray()), (X509Certificate) ks.getCertificate("client")).trustManager(caResource.getFile()).build();
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
}
});
ChannelFuture future = serverBootstrap.bind(port);
future.get();
running = true;
} catch (Exception e) {
logger.error("系统错误", e);
}
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project transporter by wang4ever.
the class WSChildHandlerInitializer method initChannel.
@Override
public void initChannel(SocketChannel ch) throws Exception {
WSConfig conf = this.config.getWsConfig();
if (logger.isDebugEnabled())
logger.debug("Initital channel handler...\twebsocketPath={}", conf.getWebsocketPath());
ChannelPipeline p = ch.pipeline();
// Configure SSL.
if (conf.getSslEnable()) {
/*
* SelfSignedCertificate ssc = new SelfSignedCertificate();
* SslContext sslCtx =
* SslContextBuilder.forServer(ssc.certificate(),
* ssc.privateKey()).build();
*/
File keyCertChainFile = new File(Resources.getResource(conf.getKeyCertChainFile()).getFile());
File keyFile = new File(Resources.getResource(conf.getKeyFile()).getFile());
SslContext sslCtx = SslContextBuilder.forServer(keyCertChainFile, keyFile).build();
p.addLast(sslCtx.newHandler(ch.alloc()));
if (logger.isDebugEnabled())
logger.debug("The ssl(wss) handler has been enabled. sslCtx={}", sslCtx.toString());
}
// pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务
if (conf.getLoggingEnable()) {
p.addLast(new LoggingHandler(LogLevel.valueOf(conf.getLoggingLevel())));
if (logger.isInfoEnabled())
logger.info("Netty internal log has been used. (WS)level={}", conf.getLoggingLevel());
}
IdleStateHandler idleHandler = new IdleStateHandler(conf.getReadIdleSeconds(), conf.getWriteIdleSeconds(), conf.getAllIdleSeconds());
p.addLast(idleHandler);
// 将请求和应答消息解码为HTTP消息
p.addLast("http-codec", new HttpServerCodec());
// 将HTTP消息的多个部分合成一条完整的HTTP消息
p.addLast("aggregator", new HttpObjectAggregator(65536));
// 向客户端发送HTML5文件
p.addLast("http-chunked", new ChunkedWriteHandler());
p.addLast("ws-protocol", new WebSocketServerProtocolHandler(conf.getWebsocketPath(), null, true));
p.addLast("text-handler", SpringContextHolder.getBean("textWSFrameHandler"));
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project herddb by diennea.
the class NettyConnector method connect.
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 {
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 {
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("messageencoder", new DataMessageEncoder());
ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
ch.pipeline().addLast(new InboundMessageHandler(channel));
}
});
LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address });
b.connect(address).sync();
return result.get();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project swift by luastar.
the class HttpServer method start.
public void start() {
// 设置线程名称
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
EventLoopGroup bossGroup = new NioEventLoopGroup(HttpConstant.SWIFT_BOSS_THREADS, threadFactoryBuilder.setNameFormat("boss-group-%d").build());
EventLoopGroup workerGroup = new NioEventLoopGroup(HttpConstant.SWIFT_WORKER_THREADS, threadFactoryBuilder.setNameFormat("worker-group-%d").build());
// EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(HttpConstant.SWIFT_BUSINESS_THREADS, threadFactoryBuilder.setNameFormat("executor-group-%d").build());
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (ssl) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
pipeline.addLast(sslContext.newHandler(ch.alloc()));
}
// http request decode and response encode
pipeline.addLast(new HttpServerCodec());
// 将消息头和体聚合成FullHttpRequest和FullHttpResponse
pipeline.addLast(new HttpObjectAggregator(HttpConstant.SWIFT_MAX_CONTENT_LENGTH));
// 压缩处理
pipeline.addLast(new HttpContentCompressor(HttpConstant.SWIFT_COMPRESSION_LEVEL));
// 自定义http服务
// pipeline.addLast(executorGroup, "http-handler", new HttpChannelHandler(handlerMapping));
pipeline.addLast(new HttpChannelHandler(handlerMapping));
}
});
Channel channel = bootstrap.bind(port).sync().channel();
channel.closeFuture().sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
// executorGroup.shutdownGracefully();
HttpThreadPoolExecutor.shutdownGracefully();
}
}
Aggregations