Package io.netty.channel

Examples of io.netty.channel.Channel


    private Channel doGetConnection() throws ConnectionFailedException
    {
        ChannelWithIdleTime cwi;
        while ((cwi = available.poll()) != null)
        {
            Channel channel = cwi.getChannel();
            // If the channel from available is closed, try again. This will result in
            // the caller always getting a connection or an exception. If closed
            // the channel is simply discarded so this also acts as a purge
            // for dead channels during a health check.
            if (channel.isOpen())
            {
                return channel;
            }
        }

        ChannelFuture f = bootstrap.connect();
       
        try
        {
            f.await();
        }
        catch (InterruptedException ex)
        {
            logger.error("Thread interrupted waiting for new connection to be made; {}",
                remoteAddress);
            Thread.currentThread().interrupt();
            throw new ConnectionFailedException(ex);
        }
       
        if (!f.isSuccess())
        {
            logger.error("Connection attempt failed: {}:{}; {}",
                remoteAddress, port, f.cause());
            consecutiveFailedConnectionAttempts.incrementAndGet();
            throw new ConnectionFailedException(f.cause());
        }
       
        consecutiveFailedConnectionAttempts.set(0);
        Channel c = f.channel();
       
        if (trustStore != null)
        {
            SSLContext context;
            try
            {
                context = SSLContext.getInstance("TLS");
                TrustManagerFactory tmf =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(trustStore);

                context.init(null, tmf.getTrustManagers(), null);
               
            }
            catch (Exception ex)
            {
                c.close();
                logger.error("Failure configuring SSL; {}:{} {}", remoteAddress, port, ex);
                throw new ConnectionFailedException(ex);
            }
            
            SSLEngine engine = context.createSSLEngine();

            Set<String> protocols = new HashSet<String>(Arrays.asList(engine.getSupportedProtocols()));

            if (protocols.contains("TLSv1.2"))
            {
                engine.setEnabledProtocols(new String[] {"TLSv1.2"});
                logger.debug("Using TLSv1.2");
            }
            else if (protocols.contains("TLSv1.1"))
            {
                engine.setEnabledProtocols(new String[] {"TLSv1.1"});
                logger.debug("Using TLSv1.1");
            }

            engine.setUseClientMode(true);
            RiakSecurityDecoder decoder = new RiakSecurityDecoder(engine, username, password);
            c.pipeline().addFirst(decoder);
               
            try
            {
                DefaultPromise<Void> promise = decoder.getPromise();
                promise.await();
               
                if (promise.isSuccess())
                {
                    logger.debug("Auth succeeded; {}:{}", remoteAddress, port);
                }
                else
                {
                    c.close();
                    logger.error("Failure during Auth; {}:{} {}",remoteAddress, port, promise.cause());
                    throw new ConnectionFailedException(promise.cause());
                }
               
           
            }
            catch (InterruptedException e)
            {
                c.close();
                logger.error("Thread interrupted during Auth; {}:{}",
                    remoteAddress, port);
                Thread.currentThread().interrupt();
                throw new ConnectionFailedException(e);
            }
View Full Code Here


                if (cwi.getIdleStart() + idleTimeoutInNanos < System.nanoTime())
                {
                    boolean removed = available.remove(cwi);
                    if (removed)
                    {
                        Channel c = cwi.getChannel();
                        logger.debug("Idle channel closed; {}:{}", remoteAddress, port);
                        closeConnection(c);
                        currentNum--;
                    }
                }
View Full Code Here

            HealthCheckDecoder healthCheck = healthCheckFactory.makeDecoder();
            // See: doGetConnection() - this will purge closed
            // connections from the available queue and either
            // return/create a new one (meaning the node is up) or throw
            // an exception if a connection can't be made.
            Channel c = doGetConnection();

            Promise<RiakMessage> promise;
           
            if (c.pipeline().names().contains(Constants.SSL_HANDLER))
            {
                c.pipeline().addAfter(Constants.SSL_HANDLER, Constants.HEALTHCHECK_CODEC, healthCheck);
            }
            else
            {
                c.pipeline().addBefore(Constants.MESSAGE_CODEC, Constants.HEALTHCHECK_CODEC, healthCheck);
            }
            logger.debug("healthCheck added to pipeline.");
           
            try
            {
View Full Code Here

     **/
    private static List<Entry<String, String>> formget(
            Bootstrap bootstrap, String host, int port, String get, URI uriSimple) throws Exception {
        // XXX /formget
        // No use of HttpPostRequestEncoder since not a POST
        Channel channel = bootstrap.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        QueryStringEncoder encoder = new QueryStringEncoder(get);
        // add Form attribute
        encoder.addParam("getform", "GET");
        encoder.addParam("info", "first value");
        encoder.addParam("secondinfo", "secondvalue ���&");
        // not the big one since it is not compatible with GET size
        // encoder.addParam("thirdinfo", textArea);
        encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
        encoder.addParam("Send", "Send");

        URI uriGet = new URI(encoder.toString());
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uriGet.toASCIIString());
        HttpHeaders headers = request.headers();
        headers.set(HttpHeaders.Names.HOST, host);
        headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE);

        headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr");
        headers.set(HttpHeaders.Names.REFERER, uriSimple.toString());
        headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side");
        headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        //connection will not close but needed
        // headers.set("Connection","keep-alive");
        // headers.set("Keep-Alive","300");

        headers.set(
                HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(
                        new DefaultCookie("my-cookie", "foo"),
                        new DefaultCookie("another-cookie", "bar"))
        );

        // send request
        List<Entry<String, String>> entries = headers.entries();
        channel.writeAndFlush(request);

        // Wait for the server to close the connection.
        channel.closeFuture().sync();

        return entries;
    }
View Full Code Here

            List<Entry<String, String>> headers) throws Exception {
        // XXX /formpost
        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        // Wait until the connection attempt succeeds or fails.
        Channel channel = future.sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString());

        // Use the PostBody encoder
        HttpPostRequestEncoder bodyRequestEncoder =
                new HttpPostRequestEncoder(factory, request, false)// false => not multipart

        // it is legal to add directly header or cookie into the request until finalize
        for (Entry<String, String> entry : headers) {
            request.headers().set(entry.getKey(), entry.getValue());
        }

        // add Form attribute
        bodyRequestEncoder.addBodyAttribute("getform", "POST");
        bodyRequestEncoder.addBodyAttribute("info", "first value");
        bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue ���&");
        bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
        bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
        bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

        // finalize request
        request = bodyRequestEncoder.finalizeRequest();

        // Create the bodylist to be reused on the last version with Multipart support
        List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

        // send request
        channel.write(request);

        // test if request was chunked and if so, finish the write
        if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
            // either do it through ChunkedWriteHandler
            channel.write(bodyRequestEncoder);
        }
        channel.flush();

        // Do not clear here since we will reuse the InterfaceHttpData on the next request
        // for the example (limit action on client side). Take this as a broadcast of the same
        // request on both Post actions.
        //
        // On standard program, it is clearly recommended to clean all files after each request
        // bodyRequestEncoder.cleanFiles();

        // Wait for the server to close the connection.
        channel.closeFuture().sync();
        return bodylist;
    }
View Full Code Here

            List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception {
        // XXX /formpostmultipart
        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        // Wait until the connection attempt succeeds or fails.
        Channel channel = future.sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString());

        // Use the PostBody encoder
        HttpPostRequestEncoder bodyRequestEncoder =
                new HttpPostRequestEncoder(factory, request, true); // true => multipart

        // it is legal to add directly header or cookie into the request until finalize
        for (Entry<String, String> entry : headers) {
            request.headers().set(entry.getKey(), entry.getValue());
        }

        // add Form attribute from previous request in formpost()
        bodyRequestEncoder.setBodyHttpDatas(bodylist);

        // finalize request
        bodyRequestEncoder.finalizeRequest();

        // send request
        channel.write(request);

        // test if request was chunked and if so, finish the write
        if (bodyRequestEncoder.isChunked()) {
            channel.write(bodyRequestEncoder);
        }
        channel.flush();

        // Now no more use of file representation (and list of HttpData)
        bodyRequestEncoder.cleanFiles();

        // Wait for the server to close the connection.
        channel.closeFuture().sync();
    }
View Full Code Here

                             new HttpObjectAggregator(8192),
                             handler);
                 }
             });

            Channel ch = b.connect(uri.getHost(), port).sync().channel();
            handler.handshakeFuture().sync();

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                    ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
View Full Code Here

       
        LOG.log(Level.SEVERE, "Unexpected exception from downstream.", cause);

        interceptOnRequestFailed(ctx, cause);

        Channel ch = ctx.channel();
        if (cause instanceof IllegalArgumentException) {

            ch.close();

        } else {

            if (cause instanceof TooLongFrameException) {
                sendError(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }

            if (ch.isActive()) {
                sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
            }

        }
        ctx.close();
View Full Code Here

            pipelineFactory = new DefaultClientInitializerFactory(this);
        }

        if (!configuration.isLazyChannelCreation()) {
            // ensure the connection can be established when we start up
            Channel channel = pool.borrowObject();
            pool.returnObject(channel);
        }
    }
View Full Code Here

        if (LOG.isTraceEnabled()) {
            LOG.trace("Pool[active={}, idle={}]", pool.getNumActive(), pool.getNumIdle());
        }

        // get a channel from the pool
        Channel existing;
        try {
            existing = pool.borrowObject();
            if (existing != null) {
                LOG.trace("Got channel from pool {}", existing);
            }
        } catch (Exception e) {
            exchange.setException(e);
            callback.done(true);
            return true;
        }

        // we must have a channel
        if (existing == null) {
            exchange.setException(new CamelExchangeException("Cannot get channel from pool", exchange));
            callback.done(true);
            return true;
        }

        // need to declare as final
        final Channel channel = existing;
        final AsyncCallback producerCallback = new NettyProducerCallback(channel, callback);

        // setup state as attachment on the channel, so we can access the state later when needed
        putState(channel, new NettyCamelState(producerCallback, exchange));
        // here we need to setup the remote address information here
View Full Code Here

TOP

Related Classes of io.netty.channel.Channel

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.