Search in sources :

Example 11 with HttpClientCodec

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpClientCodec in project autobahn-java by crossbario.

the class NettyWebSocket method connect.

@Override
public void connect(ITransportHandler transportHandler, TransportOptions options) throws Exception {
    if (options == null) {
        if (mOptions == null) {
            options = new TransportOptions();
        } else {
            options = new TransportOptions();
            options.setAutoPingInterval(mOptions.getAutoPingInterval());
            options.setAutoPingTimeout(mOptions.getAutoPingTimeout());
            options.setMaxFramePayloadSize(mOptions.getMaxFramePayloadSize());
        }
    }
    URI uri;
    uri = new URI(mUri);
    int port = validateURIAndGetPort(uri);
    String scheme = uri.getScheme();
    String host = uri.getHost();
    final SslContext sslContext = getSSLContext(scheme);
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, mSerializers, true, new DefaultHttpHeaders(), options.getMaxFramePayloadSize());
    mHandler = new NettyWebSocketClientHandler(handshaker, this, transportHandler);
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    TransportOptions opt = options;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline channelPipeline = ch.pipeline();
            if (sslContext != null) {
                channelPipeline.addLast(sslContext.newHandler(ch.alloc(), host, port));
            }
            channelPipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, new IdleStateHandler(opt.getAutoPingInterval() + opt.getAutoPingTimeout(), opt.getAutoPingInterval(), 0, TimeUnit.SECONDS), mHandler);
        }
    });
    mChannel = bootstrap.connect(uri.getHost(), port).sync().channel();
    mHandler.getHandshakeFuture().sync();
}
Also used : WebSocketClientHandshaker(io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) TransportOptions(io.crossbar.autobahn.wamp.types.TransportOptions) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 12 with HttpClientCodec

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpClientCodec in project activemq-artemis by apache.

the class NettyConnector method start.

@Override
public synchronized void start() {
    if (channelClazz != null) {
        return;
    }
    if (remotingThreads == -1) {
        // Default to number of cores * 3
        remotingThreads = Runtime.getRuntime().availableProcessors() * 3;
    }
    String connectorType;
    if (useEpoll && Epoll.isAvailable()) {
        if (useGlobalWorkerPool) {
            group = SharedEventLoopGroup.getInstance((threadFactory -> new EpollEventLoopGroup(remotingThreads, threadFactory)));
        } else {
            group = new EpollEventLoopGroup(remotingThreads);
        }
        connectorType = EPOLL_CONNECTOR_TYPE;
        channelClazz = EpollSocketChannel.class;
        logger.debug("Connector " + this + " using native epoll");
    } else if (useKQueue && KQueue.isAvailable()) {
        if (useGlobalWorkerPool) {
            group = SharedEventLoopGroup.getInstance((threadFactory -> new KQueueEventLoopGroup(remotingThreads, threadFactory)));
        } else {
            group = new KQueueEventLoopGroup(remotingThreads);
        }
        connectorType = KQUEUE_CONNECTOR_TYPE;
        channelClazz = KQueueSocketChannel.class;
        logger.debug("Connector " + this + " using native kqueue");
    } else {
        if (useGlobalWorkerPool) {
            channelClazz = NioSocketChannel.class;
            group = SharedEventLoopGroup.getInstance((threadFactory -> new NioEventLoopGroup(remotingThreads, threadFactory)));
        } else {
            channelClazz = NioSocketChannel.class;
            group = new NioEventLoopGroup(remotingThreads);
        }
        connectorType = NIO_CONNECTOR_TYPE;
        channelClazz = NioSocketChannel.class;
        logger.debug("Connector + " + this + " using nio");
    }
    // if we are a servlet wrap the socketChannelFactory
    bootstrap = new Bootstrap();
    bootstrap.channel(channelClazz);
    bootstrap.group(group);
    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (connectTimeoutMillis != -1) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    final int writeBufferLowWaterMark = this.writeBufferLowWaterMark != -1 ? this.writeBufferLowWaterMark : WriteBufferWaterMark.DEFAULT.low();
    final int writeBufferHighWaterMark = this.writeBufferHighWaterMark != -1 ? this.writeBufferHighWaterMark : WriteBufferWaterMark.DEFAULT.high();
    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(writeBufferLowWaterMark, writeBufferHighWaterMark);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE);
    final String realKeyStorePath;
    final String realKeyStoreProvider;
    final String realKeyStorePassword;
    final String realTrustStorePath;
    final String realTrustStoreProvider;
    final String realTrustStorePassword;
    if (sslEnabled) {
        // HORNETQ-680 - override the server-side config if client-side system properties are set
        realKeyStorePath = Stream.of(System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME), System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME), keyStorePath).map(v -> useDefaultSslContext ? keyStorePath : v).filter(Objects::nonNull).findFirst().orElse(null);
        realKeyStorePassword = Stream.of(System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME), System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME), keyStorePassword).map(v -> useDefaultSslContext ? keyStorePassword : v).filter(Objects::nonNull).findFirst().orElse(null);
        realKeyStoreProvider = Stream.of(System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME), keyStoreProvider).map(v -> useDefaultSslContext ? keyStoreProvider : v).filter(Objects::nonNull).findFirst().orElse(null);
        realTrustStorePath = Stream.of(System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME), System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME), trustStorePath).map(v -> useDefaultSslContext ? trustStorePath : v).filter(Objects::nonNull).findFirst().orElse(null);
        realTrustStorePassword = Stream.of(System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME), System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME), trustStorePassword).map(v -> useDefaultSslContext ? trustStorePassword : v).filter(Objects::nonNull).findFirst().orElse(null);
        realTrustStoreProvider = Stream.of(System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME), trustStoreProvider).map(v -> useDefaultSslContext ? trustStoreProvider : v).filter(Objects::nonNull).findFirst().orElse(null);
    } else {
        realKeyStorePath = null;
        realKeyStoreProvider = null;
        realKeyStorePassword = null;
        realTrustStorePath = null;
        realTrustStoreProvider = null;
        realTrustStorePassword = null;
    }
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(Channel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled && !useServlet) {
                SSLEngine engine;
                if (sslProvider.equals(TransportConstants.OPENSSL_PROVIDER)) {
                    engine = loadOpenSslEngine(channel.alloc(), realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
                } else {
                    engine = loadJdkSslEngine(useDefaultSslContext, realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
                }
                engine.setUseClientMode(true);
                engine.setWantClientAuth(true);
                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();
                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }
                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidProtocol(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }
                if (verifyHost) {
                    SSLParameters sslParameters = engine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    engine.setSSLParameters(sslParameters);
                }
                SslHandler handler = new SslHandler(engine);
                pipeline.addLast("ssl", handler);
            }
            if (httpEnabled) {
                pipeline.addLast(new HttpRequestEncoder());
                pipeline.addLast(new HttpResponseDecoder());
                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                pipeline.addLast(new HttpHandler());
            }
            if (httpUpgradeEnabled) {
                // prepare to handle a HTTP 101 response to upgrade the protocol.
                final HttpClientCodec httpClientCodec = new HttpClientCodec();
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
            }
            protocolManager.addChannelHandlers(pipeline);
            pipeline.addLast(new ActiveMQClientChannelHandler(channelGroup, handler, new Listener()));
        }
    });
    if (batchDelay > 0) {
        flusher = new BatchFlusher();
        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS);
    }
    ActiveMQClientLogger.LOGGER.startedNettyConnector(connectorType, TransportConstants.NETTY_VERSION, host, port);
}
Also used : AttributeKey(io.netty.util.AttributeKey) SSLContext(javax.net.ssl.SSLContext) HttpResponseDecoder(io.netty.handler.codec.http.HttpResponseDecoder) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) HttpObject(io.netty.handler.codec.http.HttpObject) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) Base64(io.netty.handler.codec.base64.Base64) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InetAddress(java.net.InetAddress) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ActiveMQClientProtocolManager(org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQClientProtocolManager) ActiveMQComponent(org.apache.activemq.artemis.core.server.ActiveMQComponent) ActiveMQClientLogger(org.apache.activemq.artemis.core.client.ActiveMQClientLogger) ClientProtocolManager(org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManager) Map(java.util.Map) Level(io.netty.util.ResourceLeakDetector.Level) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelPipeline(io.netty.channel.ChannelPipeline) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Cookie(io.netty.handler.codec.http.cookie.Cookie) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) SslHandler(io.netty.handler.ssl.SslHandler) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder) ActiveMQClientMessageBundle(org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle) ActiveMQDefaultConfiguration(org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration) ChannelOption(io.netty.channel.ChannelOption) SSLParameters(javax.net.ssl.SSLParameters) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) ConfigurationHelper(org.apache.activemq.artemis.utils.ConfigurationHelper) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ConnectException(java.net.ConnectException) BufferHandler(org.apache.activemq.artemis.spi.core.remoting.BufferHandler) SslContext(io.netty.handler.ssl.SslContext) Executor(java.util.concurrent.Executor) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Future(io.netty.util.concurrent.Future) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ScheduledFuture(java.util.concurrent.ScheduledFuture) SocketAddress(java.net.SocketAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) FutureLatch(org.apache.activemq.artemis.utils.FutureLatch) SSLSupport(org.apache.activemq.artemis.core.remoting.impl.ssl.SSLSupport) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelPromise(io.netty.channel.ChannelPromise) URI(java.net.URI) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelGroup(io.netty.channel.group.ChannelGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ResourceLeakDetector(io.netty.util.ResourceLeakDetector) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Objects(java.util.Objects) AbstractConnector(org.apache.activemq.artemis.spi.core.remoting.AbstractConnector) List(java.util.List) HttpResponse(io.netty.handler.codec.http.HttpResponse) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) HttpVersion(io.netty.handler.codec.http.HttpVersion) MessageDigest(java.security.MessageDigest) IPV6Util(org.apache.activemq.artemis.utils.IPV6Util) Logger(org.jboss.logging.Logger) HashMap(java.util.HashMap) Base64.encodeBytes(org.apache.activemq.artemis.utils.Base64.encodeBytes) LoginContext(javax.security.auth.login.LoginContext) ConcurrentMap(java.util.concurrent.ConcurrentMap) SSLEngine(javax.net.ssl.SSLEngine) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Connection(org.apache.activemq.artemis.spi.core.remoting.Connection) KQueueEventLoopGroup(io.netty.channel.kqueue.KQueueEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) HttpMethod(io.netty.handler.codec.http.HttpMethod) Subject(javax.security.auth.Subject) ChannelFuture(io.netty.channel.ChannelFuture) Epoll(io.netty.channel.epoll.Epoll) TimeUnit(java.util.concurrent.TimeUnit) Inet6Address(java.net.Inet6Address) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) KQueue(io.netty.channel.kqueue.KQueue) Collections(java.util.Collections) ClientCookieDecoder(io.netty.handler.codec.http.cookie.ClientCookieDecoder) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) SSLEngine(javax.net.ssl.SSLEngine) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) SSLParameters(javax.net.ssl.SSLParameters) Bootstrap(io.netty.bootstrap.Bootstrap) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) HttpResponseDecoder(io.netty.handler.codec.http.HttpResponseDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) URISyntaxException(java.net.URISyntaxException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) KQueueEventLoopGroup(io.netty.channel.kqueue.KQueueEventLoopGroup) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder)

Example 13 with HttpClientCodec

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpClientCodec in project alien4cloud by alien4cloud.

the class StompConnection method init.

@SneakyThrows({ InterruptedException.class, URISyntaxException.class })
private void init() {
    if (this.stompChannel != null) {
        throw new IllegalStateException("The stomp connection has already been started");
    }
    String wsUrl = "ws://" + host + ":" + port + endPoint + "/websocket";
    if (log.isDebugEnabled()) {
        log.debug("Web socket url {}", wsUrl);
    }
    String loginUrl = null;
    if (user != null && password != null && loginPath != null) {
        loginUrl = "http://" + host + ":" + port + loginPath;
        if (log.isDebugEnabled()) {
            log.debug("Authentication url {}", loginUrl);
        }
    }
    this.eventLoopGroup = new NioEventLoopGroup();
    this.stompClientHandler = new StompClientHandler();
    DefaultHttpHeaders handshakeHeaders = new DefaultHttpHeaders();
    if (this.headers != null) {
        for (Map.Entry<String, String> header : this.headers.entrySet()) {
            handshakeHeaders.add(header.getKey(), header.getValue());
        }
    }
    final WebSocketClientHandler webSocketHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(new URI(wsUrl), WebSocketVersion.V13, null, false, handshakeHeaders), host, user, password, loginUrl);
    Bootstrap b = new Bootstrap();
    b.group(eventLoopGroup).channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(HttpClientCodec.class.getName(), new HttpClientCodec());
            pipeline.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(8192));
            pipeline.addLast(WebSocketClientCompressionHandler.class.getName(), new WebSocketClientCompressionHandler());
            pipeline.addLast(WebSocketClientHandler.class.getName(), webSocketHandler);
            pipeline.addLast(StompSubframeDecoder.class.getName(), new StompSubframeDecoder());
            pipeline.addLast(StompSubframeEncoder.class.getName(), new StompSubframeEncoder());
            pipeline.addLast(StompSubframeAggregator.class.getName(), new StompSubframeAggregator(1048576));
            pipeline.addLast(StompClientHandler.class.getName(), stompClientHandler);
        }
    });
    this.stompChannel = b.connect(host, port).sync().channel();
    this.stompClientHandler.connectFuture(this.stompChannel.newPromise());
    webSocketHandler.handshakeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            stompClientHandler.beginStomp(stompChannel);
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) WebSocketClientCompressionHandler(io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler) StompSubframeAggregator(io.netty.handler.codec.stomp.StompSubframeAggregator) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) StompSubframeEncoder(io.netty.handler.codec.stomp.StompSubframeEncoder) URI(java.net.URI) ChannelFutureListener(io.netty.channel.ChannelFutureListener) URISyntaxException(java.net.URISyntaxException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) StompSubframeDecoder(io.netty.handler.codec.stomp.StompSubframeDecoder) Bootstrap(io.netty.bootstrap.Bootstrap) Map(java.util.Map) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SneakyThrows(lombok.SneakyThrows)

Example 14 with HttpClientCodec

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpClientCodec in project activemq-artemis by apache.

the class WebServerComponentTest method simpleSecureServer.

@Test
public void simpleSecureServer() throws Exception {
    WebServerDTO webServerDTO = new WebServerDTO();
    webServerDTO.bind = "https://localhost:0";
    webServerDTO.path = "webapps";
    webServerDTO.keyStorePath = "./src/test/resources/server.keystore";
    webServerDTO.setKeyStorePassword("password");
    WebServerComponent webServerComponent = new WebServerComponent();
    Assert.assertFalse(webServerComponent.isStarted());
    webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/");
    testedComponents.add(webServerComponent);
    webServerComponent.start();
    final int port = webServerComponent.getPort();
    // Make the connection attempt.
    String keyStoreProvider = "JKS";
    SSLContext context = SSLSupport.createContext(keyStoreProvider, webServerDTO.keyStorePath, webServerDTO.getKeyStorePassword(), keyStoreProvider, webServerDTO.keyStorePath, webServerDTO.getKeyStorePassword());
    SSLEngine engine = context.createSSLEngine();
    engine.setUseClientMode(true);
    engine.setWantClientAuth(true);
    final SslHandler sslHandler = new SslHandler(engine);
    CountDownLatch latch = new CountDownLatch(1);
    final ClientHandler clientHandler = new ClientHandler(latch);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(sslHandler);
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(clientHandler);
        }
    });
    Channel ch = bootstrap.connect("localhost", port).sync().channel();
    URI uri = new URI(SECURE_URL);
    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, "localhost");
    // Send the HTTP request.
    ch.writeAndFlush(request);
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(clientHandler.body, "12345");
    // Wait for the server to close the connection.
    ch.close();
    Assert.assertTrue(webServerComponent.isStarted());
    webServerComponent.stop(true);
    Assert.assertFalse(webServerComponent.isStarted());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) SSLEngine(javax.net.ssl.SSLEngine) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SSLContext(javax.net.ssl.SSLContext) WebServerDTO(org.apache.activemq.artemis.dto.WebServerDTO) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) SslHandler(io.netty.handler.ssl.SslHandler) URISyntaxException(java.net.URISyntaxException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WebServerComponent(org.apache.activemq.artemis.component.WebServerComponent) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Example 15 with HttpClientCodec

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpClientCodec in project activemq-artemis by apache.

the class WebServerComponentTest method testComponentStopBehavior.

@Test
public void testComponentStopBehavior() throws Exception {
    WebServerDTO webServerDTO = new WebServerDTO();
    webServerDTO.bind = "http://localhost:0";
    webServerDTO.path = "webapps";
    WebServerComponent webServerComponent = new WebServerComponent();
    Assert.assertFalse(webServerComponent.isStarted());
    webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/");
    webServerComponent.start();
    final int port = webServerComponent.getPort();
    // Make the connection attempt.
    CountDownLatch latch = new CountDownLatch(1);
    final ClientHandler clientHandler = new ClientHandler(latch);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(clientHandler);
        }
    });
    Channel ch = bootstrap.connect("localhost", port).sync().channel();
    URI uri = new URI(URL);
    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, "localhost");
    // Send the HTTP request.
    ch.writeAndFlush(request);
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(clientHandler.body, "12345");
    // Wait for the server to close the connection.
    ch.close();
    Assert.assertTrue(webServerComponent.isStarted());
    // usual stop won't actually stop it
    webServerComponent.stop();
    assertTrue(webServerComponent.isStarted());
    webServerComponent.stop(true);
    Assert.assertFalse(webServerComponent.isStarted());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) WebServerDTO(org.apache.activemq.artemis.dto.WebServerDTO) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WebServerComponent(org.apache.activemq.artemis.component.WebServerComponent) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Aggregations

HttpClientCodec (io.netty.handler.codec.http.HttpClientCodec)61 ChannelPipeline (io.netty.channel.ChannelPipeline)30 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)26 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)25 Bootstrap (io.netty.bootstrap.Bootstrap)19 Channel (io.netty.channel.Channel)19 SocketChannel (io.netty.channel.socket.SocketChannel)17 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)16 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)15 IOException (java.io.IOException)13 HttpContentDecompressor (io.netty.handler.codec.http.HttpContentDecompressor)12 HttpRequest (io.netty.handler.codec.http.HttpRequest)12 SslContext (io.netty.handler.ssl.SslContext)12 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)11 URISyntaxException (java.net.URISyntaxException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ChannelInitializer (io.netty.channel.ChannelInitializer)9 URI (java.net.URI)9 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)8 InetSocketAddress (java.net.InetSocketAddress)8