Example usage for io.netty.channel ChannelPipeline get

List of usage examples for io.netty.channel ChannelPipeline get

Introduction

In this page you can find the example usage for io.netty.channel ChannelPipeline get.

Prototype

<T extends ChannelHandler> T get(Class<T> handlerType);

Source Link

Document

Returns the ChannelHandler of the specified type in this pipeline.

Usage

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }/* w w  w .j a v  a2 s .  com*/

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    ActiveMQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                ActiveMQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                // Send the HTTP request.
                ch.writeAndFlush(request);

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, protocolManager.getName());
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}

From source file:org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty.NettyConnectorTest.java

License:Apache License

@Test
public void testChannelHandlerRemovedWhileCreatingConnection() throws Exception {
    BufferHandler handler = (connectionID, buffer) -> {
    };/*from   www.jav  a  2  s  . c om*/
    Map<String, Object> params = new HashMap<>();
    final ExecutorService closeExecutor = Executors
            .newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());
    final ExecutorService threadPool = Executors
            .newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());
    final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5,
            ActiveMQThreadFactory.defaultThreadFactory());
    try {
        NettyConnector connector = new NettyConnector(params, handler, listener, closeExecutor, threadPool,
                scheduledThreadPool);
        connector.start();
        final Connection connection = connector.createConnection(future -> {
            future.awaitUninterruptibly();
            Assert.assertTrue(future.isSuccess());
            final ChannelPipeline pipeline = future.channel().pipeline();
            final ActiveMQChannelHandler activeMQChannelHandler = pipeline.get(ActiveMQChannelHandler.class);
            Assert.assertNotNull(activeMQChannelHandler);
            pipeline.remove(activeMQChannelHandler);
            Assert.assertNull(pipeline.get(ActiveMQChannelHandler.class));
        });
        Assert.assertNull(connection);
        connector.close();
    } finally {
        closeExecutor.shutdownNow();
        threadPool.shutdownNow();
        scheduledThreadPool.shutdownNow();
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsAndHttpChannelizerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) {
    final ChannelPipeline pipeline = ctx.pipeline();
    if (obj instanceof HttpMessage && !WebSocketHandlerUtil.isWebSocket((HttpMessage) obj)) {
        if (null != pipeline.get(PIPELINE_AUTHENTICATOR)) {
            pipeline.remove(PIPELINE_REQUEST_HANDLER);
            final ChannelHandler authenticator = pipeline.get(PIPELINE_AUTHENTICATOR);
            pipeline.remove(PIPELINE_AUTHENTICATOR);
            pipeline.addAfter(PIPELINE_HTTP_RESPONSE_ENCODER, PIPELINE_AUTHENTICATOR, authenticator);
            pipeline.addAfter(PIPELINE_AUTHENTICATOR, PIPELINE_REQUEST_HANDLER,
                    this.httpGremlinEndpointHandler);
        } else {//from w  w  w .ja  v a  2 s . co m
            pipeline.remove(PIPELINE_REQUEST_HANDLER);
            pipeline.addAfter(PIPELINE_HTTP_RESPONSE_ENCODER, PIPELINE_REQUEST_HANDLER,
                    this.httpGremlinEndpointHandler);
        }
    }
    ctx.fireChannelRead(obj);
}

From source file:org.asynchttpclient.netty.channel.ChannelManager.java

License:Open Source License

public static boolean isSslHandlerConfigured(ChannelPipeline pipeline) {
    return pipeline.get(SSL_HANDLER) != null;
}

From source file:org.asynchttpclient.netty.channel.ChannelManager.java

License:Open Source License

public void upgradeProtocol(ChannelPipeline pipeline, Uri requestUri) throws SSLException {
    if (pipeline.get(HTTP_CLIENT_CODEC) != null)
        pipeline.remove(HTTP_CLIENT_CODEC);

    if (requestUri.isSecured())
        if (isSslHandlerConfigured(pipeline)) {
            pipeline.addAfter(SSL_HANDLER, HTTP_CLIENT_CODEC, newHttpClientCodec());
        } else {/*from w  ww.j  av a  2 s .  c  o  m*/
            pipeline.addAfter(PINNED_ENTRY, HTTP_CLIENT_CODEC, newHttpClientCodec());
            pipeline.addAfter(PINNED_ENTRY, SSL_HANDLER,
                    createSslHandler(requestUri.getHost(), requestUri.getExplicitPort()));
        }

    else
        pipeline.addAfter(PINNED_ENTRY, HTTP_CLIENT_CODEC, newHttpClientCodec());

    if (requestUri.isWebSocket()) {
        pipeline.addAfter(AHC_HTTP_HANDLER, AHC_WS_HANDLER, wsHandler);
        pipeline.remove(AHC_HTTP_HANDLER);
    }
}

From source file:org.asynchttpclient.providers.netty.channel.ChannelManager.java

License:Open Source License

public static SslHandler getSslHandler(ChannelPipeline pipeline) {
    return (SslHandler) pipeline.get(SSL_HANDLER);
}

From source file:org.asynchttpclient.providers.netty.channel.ChannelManager.java

License:Open Source License

public void upgradeProtocol(ChannelPipeline pipeline, String scheme, String host, int port)
        throws IOException, GeneralSecurityException {
    if (pipeline.get(HTTP_HANDLER) != null)
        pipeline.remove(HTTP_HANDLER);/*from  www .j  a va  2s  .c  om*/

    if (isSecure(scheme))
        if (isSslHandlerConfigured(pipeline)) {
            pipeline.addAfter(SSL_HANDLER, HTTP_HANDLER, newHttpClientCodec());
        } else {
            pipeline.addFirst(HTTP_HANDLER, newHttpClientCodec());
            pipeline.addFirst(SSL_HANDLER, createSslHandler(host, port));
        }

    else
        pipeline.addFirst(HTTP_HANDLER, newHttpClientCodec());

    if (isWebSocket(scheme)) {
        pipeline.addAfter(HTTP_PROCESSOR, WS_PROCESSOR, wsProcessor);
        pipeline.remove(HTTP_PROCESSOR);
    }
}

From source file:org.asynchttpclient.providers.netty.channel.Channels.java

License:Apache License

/**
 * Always make sure the channel who got cached support the proper protocol. It could only occurs when a HttpMethod.
 * CONNECT is used against a proxy that requires upgrading from http to https.
 *//*from w w w  .  j  a va  2  s .  c o  m*/
public void verifyChannelPipeline(ChannelPipeline pipeline, String scheme)
        throws IOException, GeneralSecurityException {

    boolean isSecure = isSecure(scheme);
    if (pipeline.get(SSL_HANDLER) != null) {
        if (!isSecure)
            pipeline.remove(SSL_HANDLER);

    } else if (isSecure)
        pipeline.addFirst(SSL_HANDLER, new SslInitializer(Channels.this));
}

From source file:org.asynchttpclient.providers.netty.channel.Channels.java

License:Apache License

public void upgradeProtocol(ChannelPipeline p, String scheme, String host, int port)
        throws IOException, GeneralSecurityException {
    if (p.get(HTTP_HANDLER) != null) {
        p.remove(HTTP_HANDLER);//  w  w w  .  jav  a2 s  . co m
    }

    if (isSecure(scheme)) {
        if (p.get(SSL_HANDLER) == null) {
            p.addFirst(HTTP_HANDLER, newHttpClientCodec());
            p.addFirst(SSL_HANDLER, createSslHandler(host, port));
        } else {
            p.addAfter(SSL_HANDLER, HTTP_HANDLER, newHttpClientCodec());
        }

    } else {
        p.addFirst(HTTP_HANDLER, newHttpClientCodec());
    }

    if (isWebSocket(scheme)) {
        p.replace(HTTP_PROCESSOR, WS_PROCESSOR, wsProcessor);
    }
}

From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }/* w ww .j a  va 2s .  c  o m*/

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    HornetQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    HornetQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, HORNETQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_HORNETQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                HornetQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                // Send the HTTP request.
                ch.writeAndFlush(request);

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                HornetQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, HornetQClient.DEFAULT_CORE_PROTOCOL);
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            HornetQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}