use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project cdap by caskdata.
the class NettyRouterPipelineTest method testHttpPipelining.
@Test
public void testHttpPipelining() throws Exception {
final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
EventLoopGroup eventGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse) {
responseStatuses.add(((HttpResponse) msg).status());
}
ReferenceCountUtil.release(msg);
}
});
}
});
// Create a connection and make five consecutive HTTP call without waiting for the first to respond
Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
for (int i = 0; i < 5; i++) {
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
channel.writeAndFlush(request);
}
// Should get the first response as normal one
HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
Assert.assertEquals(HttpResponseStatus.OK, status);
// The rest four should be failure responses
for (int i = 0; i < 4; i++) {
Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
}
eventGroup.shutdownGracefully();
channel.close();
Assert.assertTrue(responseStatuses.isEmpty());
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project bgpcep by opendaylight.
the class PCCDispatcherImpl method createClient.
@Override
@SuppressWarnings("unchecked")
public Future<PCEPSession> createClient(final InetSocketAddress remoteAddress, final long reconnectTime, final PCEPSessionListenerFactory listenerFactory, final PCEPSessionNegotiatorFactory negotiatorFactory, final KeyMapping keys, final InetSocketAddress localAddress, final BigInteger dbVersion) {
final Bootstrap b = new Bootstrap();
b.group(this.workerGroup);
b.localAddress(localAddress);
setChannelFactory(b, keys);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.SO_REUSEADDR, true);
b.option(ChannelOption.RCVBUF_ALLOCATOR, new io.netty.channel.FixedRecvByteBufAllocator(1));
final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer, CONNECT_TIMEOUT, b);
final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(new PCEPSessionNegotiatorFactoryDependencies() {
@Override
public PCEPSessionListenerFactory getListenerFactory() {
return listenerFactory;
}
@Override
public PCEPPeerProposal getPeerProposal() {
return new PCCPeerProposal(dbVersion);
}
}, ch, promise));
ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelInactive(final ChannelHandlerContext ctx) {
if (promise.isCancelled()) {
return;
}
if (!promise.isInitialConnectFinished()) {
LOG.debug("Connection to {} was dropped during negotiation, reattempting", remoteAddress);
return;
}
LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory, negotiatorFactory, keys, localAddress, dbVersion);
}
});
}
};
b.handler(channelInitializer);
promise.connect();
return promise;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project scalecube by scalecube.
the class NettyStreamChannelInitializer method initChannel.
@Override
protected void initChannel(Channel channel) {
ChannelPipeline pipeline = channel.pipeline();
// contexs contexts contexs
channel.pipeline().addLast(channelContextHandler);
// frame codecs
pipeline.addLast(new LengthFieldPrepender(LENGTH_FIELD_LENGTH));
pipeline.addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_LENGTH));
// message acceptor
pipeline.addLast(messageHandler);
// at-least-something exception handler
pipeline.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
// Hint: at this point one can look at throwable, make some exception translation, and via channelContext post
// ChannelContextError event, and hence give business layer ability to react on low level system error events
LOGGER.warn("Exception caught for channel {}, {}", ctx.channel(), throwable);
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project redisson by redisson.
the class RedisChannelInitializer method initSsl.
private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
if (!config.getAddress().isSsl()) {
return;
}
io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
if (config.getSslProvider() == SslProvider.OPENSSL) {
provided = io.netty.handler.ssl.SslProvider.OPENSSL;
}
SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
sslContextBuilder.protocols(config.getSslProtocols());
if (config.getSslTruststore() != null) {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream stream = config.getSslTruststore().openStream();
try {
char[] password = null;
if (config.getSslTruststorePassword() != null) {
password = config.getSslTruststorePassword().toCharArray();
}
keyStore.load(stream, password);
} finally {
stream.close();
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContextBuilder.trustManager(trustManagerFactory);
}
if (config.getSslKeystore() != null) {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream stream = config.getSslKeystore().openStream();
char[] password = null;
if (config.getSslKeystorePassword() != null) {
password = config.getSslKeystorePassword().toCharArray();
}
try {
keyStore.load(stream, password);
} finally {
stream.close();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
sslContextBuilder.keyManager(keyManagerFactory);
}
SSLParameters sslParams = new SSLParameters();
if (config.isSslEnableEndpointIdentification()) {
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
} else {
if (config.getSslTruststore() == null) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
}
}
SslContext sslContext = sslContextBuilder.build();
String hostname = config.getSslHostname();
if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
hostname = config.getAddress().getHost();
}
SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
sslEngine.setSSLParameters(sslParams);
SslHandler sslHandler = new SslHandler(sslEngine);
ch.pipeline().addLast(sslHandler);
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
volatile boolean sslInitDone;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
if (sslInitDone) {
super.channelActive(ctx);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
if (e.isSuccess()) {
sslInitDone = true;
ctx.fireChannelActive();
} else {
RedisConnection connection = RedisConnection.getFrom(ctx.channel());
connection.closeAsync();
connection.getConnectionPromise().completeExceptionally(e.cause());
}
}
super.userEventTriggered(ctx, evt);
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project flink by apache.
the class Prio0InboundChannelHandlerFactory method createHandler.
@Override
public Optional<ChannelHandler> createHandler(Configuration configuration, Map<String, String> responseHeaders) throws ConfigurationException {
String redirectFromUrl = configuration.getString(REDIRECT_FROM_URL);
String redirectToUrl = configuration.getString(REDIRECT_TO_URL);
if (!redirectFromUrl.isEmpty() && !redirectToUrl.isEmpty()) {
return Optional.of(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) msg;
if (httpRequest.uri().equals(redirectFromUrl)) {
httpRequest.setUri(redirectToUrl);
}
}
ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
}
});
}
return Optional.empty();
}
Aggregations