Example usage for io.netty.buffer ByteBuf getBytes

List of usage examples for io.netty.buffer ByteBuf getBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf getBytes.

Prototype

public abstract ByteBuf getBytes(int index, ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the specified absolute index until the destination's position reaches its limit.

Usage

From source file:TestTCP.java

License:Open Source License

public static void main(String... args) throws Throwable {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTP test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);//from   ww w. j a v a 2  s.c  o  m
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final TCPSocket socket = new TCPSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("http://") ? "" : "http://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:TestSSL.java

License:Open Source License

public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTPS test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);//  w ww  .  j a  v  a 2s  .  c  o  m
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final SSLSocket socket = new SSLSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("https://") ? "" : "https://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:at.yawk.dbus.protocol.DbusUtil.java

public static String printHex(ByteBuf buf) {
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);
    return printHex(bytes);
}

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override//from w w w. j  a  v a2s. com
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:cc.agentx.client.net.nio.XRelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {//from  w ww  .  jav a 2  s.co m
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                } else {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                    }
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:cc.agentx.server.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {/*w w w  . j  a  v a2  s .c om*/
        ByteBuf byteBuf = (ByteBuf) msg;
        if (!byteBuf.hasArray()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, bytes);

            if (!requestParsed) {
                if (!exposedRequest) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes == null) {
                        log.info("\tClient -> Proxy           \tHalf Request");
                        return;
                    }
                }
                XRequest xRequest = requestWrapper.parse(bytes);
                String host = xRequest.getHost();
                int port = xRequest.getPort();
                int dataLength = xRequest.getSubsequentDataLength();
                if (dataLength > 0) {
                    byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length);
                    if (exposedRequest) {
                        tailData = wrapper.unwrap(tailData);
                        if (tailData != null) {
                            tailDataBuffer.write(tailData, 0, tailData.length);
                        }
                    } else {
                        tailDataBuffer.write(tailData, 0, tailData.length);
                    }
                }
                log.info("\tClient -> Proxy           \tTarget {}:{}{}", host, port,
                        DnsCache.isCached(host) ? " [Cached]" : "");
                if (xRequest.getAtyp() == XRequest.Type.DOMAIN) {
                    try {
                        host = DnsCache.get(host);
                        if (host == null) {
                            host = xRequest.getHost();
                        }
                    } catch (UnknownHostException e) {
                        log.warn("\tClient <- Proxy           \tBad DNS! ({})", e.getMessage());
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        return;
                    }
                }

                Promise<Channel> promise = ctx.executor().newPromise();
                promise.addListener(new FutureListener<Channel>() {
                    @Override
                    public void operationComplete(final Future<Channel> future) throws Exception {
                        final Channel outboundChannel = future.getNow();
                        if (future.isSuccess()) {
                            // handle tail
                            byte[] tailData = tailDataBuffer.toByteArray();
                            tailDataBuffer.close();
                            if (tailData.length > 0) {
                                log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length);
                            }
                            outboundChannel
                                    .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData)
                                            : Unpooled.EMPTY_BUFFER)
                                    .addListener(channelFuture -> {
                                        // task handover
                                        outboundChannel.pipeline()
                                                .addLast(new XRelayHandler(ctx.channel(), wrapper, false));
                                        ctx.pipeline()
                                                .addLast(new XRelayHandler(outboundChannel, wrapper, true));
                                        ctx.pipeline().remove(XConnectHandler.this);
                                    });

                        } else {
                            if (ctx.channel().isActive()) {
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

                final String finalHost = host;
                bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    if (ctx.channel().isActive()) {
                                        log.warn("\tClient <- Proxy           \tBad Ping! ({}:{})", finalHost,
                                                port);
                                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                                .addListener(ChannelFutureListener.CLOSE);
                                    }
                                }
                            }
                        });

                requestParsed = true;
            } else {
                bytes = wrapper.unwrap(bytes);
                if (bytes != null)
                    tailDataBuffer.write(bytes, 0, bytes.length);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:cc.agentx.server.net.nio.XRelayHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {//from www  .  j  a  v  a  2  s.  co  m
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                    }
                } else {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}

From source file:com.chiorichan.util.ServerFunc.java

License:Mozilla Public License

public static byte[] byteBuf2Bytes(ByteBuf buf) {
    byte[] bytes = new byte[buf.readableBytes()];
    int readerIndex = buf.readerIndex();
    buf.getBytes(readerIndex, bytes);
    return bytes;
}

From source file:com.cloudhopper.smpp.pdu.BufferHelper.java

License:Apache License

static public byte[] createByteArray(ByteBuf buffer) throws Exception {
    byte[] bytes = new byte[buffer.readableBytes()];
    // temporarily read bytes from the buffer
    buffer.getBytes(buffer.readerIndex(), bytes);
    return bytes;
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyByteBufAdapter.java

License:Open Source License

@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
    byte[] buffer = new byte[length];
    src.getBytes(srcIndex, buffer);

    try {/*from w  w w.  ja  v a2s  .c o  m*/
        output.write(buffer);
        return this;
    } catch (IOException e) {
        throw new RuntimeException("Cannot write output.", e);
    }
}