Example usage for io.netty.buffer ByteBuf release

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

Introduction

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

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

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 w  w w .j  a v  a 2 s  . com*/
    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);/*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 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:adalightserver.http.HttpServer.java

License:Apache License

@SuppressWarnings("unused")
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, String response) {
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK);
    ByteBuf buf = Unpooled.copiedBuffer(response, CharsetUtil.US_ASCII);
    res.content().writeBytes(buf);//from   ww w . j a  v a2s  .  c o  m
    buf.release();
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, res.content().readableBytes());
    sendHttpResponse(ctx, req, res);
}

From source file:adalightserver.http.HttpServer.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // res.headers().set("Access-Control-Allow-Methods", "POST, OPTIONS, GET");
    // res.headers().set("Access-Control-Allow-Origin", "*");
    // res.headers().set("Access-Control-Allow-Headers", "*");

    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*  ww  w  . java2  s  . c om*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }
    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:alluxio.client.block.stream.FailingTestDataWriter.java

License:Apache License

@Override
public void writeChunk(ByteBuf chunk) throws IOException {
    chunk.release();
    throw new IOException();
}

From source file:alluxio.client.block.stream.FailingTestPacketWriter.java

License:Apache License

@Override
public void writePacket(ByteBuf packet) throws IOException {
    packet.release();
    throw new IOException();
}

From source file:alluxio.client.block.stream.GrpcDataWriter.java

License:Apache License

@Override
public void writeChunk(final ByteBuf buf) throws IOException {
    mPosToQueue += buf.readableBytes();/*from   w  ww  .ja  v a2  s .c om*/
    try {
        WriteRequest request = WriteRequest.newBuilder().setCommand(mPartialRequest)
                .setChunk(Chunk.newBuilder().setData(UnsafeByteOperations.unsafeWrap(buf.nioBuffer())).build())
                .build();
        if (mStream instanceof GrpcDataMessageBlockingStream) {
            ((GrpcDataMessageBlockingStream<WriteRequest, WriteResponse>) mStream)
                    .sendDataMessage(new DataMessage<>(request, new NettyDataBuffer(buf)), mDataTimeoutMs);
        } else {
            mStream.send(request, mDataTimeoutMs);
        }
    } finally {
        buf.release();
    }
}

From source file:alluxio.client.block.stream.LocalFileDataWriter.java

License:Apache License

@Override
public void writeChunk(final ByteBuf buf) throws IOException {
    try {/*from w  w  w  .  java 2  s .  c om*/
        Preconditions.checkState(!mStream.isCanceled() && !mStream.isClosed(),
                "DataWriter is closed while writing chunks.");
        int sz = buf.readableBytes();
        ensureReserved(mPos + sz);
        mPos += sz;
        Preconditions.checkState(mWriter.append(buf) == sz);
    } finally {
        buf.release();
    }
}

From source file:alluxio.client.block.stream.LocalFilePacketWriter.java

License:Apache License

@Override
public void writePacket(final ByteBuf buf) throws IOException {
    try {/*from  ww w.j a  va2  s .c  o  m*/
        Preconditions.checkState(!mClosed, "PacketWriter is closed while writing packets.");
        int sz = buf.readableBytes();
        ensureReserved(mPos + sz);
        mPos += sz;
        Preconditions.checkState(buf.readBytes(mWriter.getChannel(), sz) == sz);
    } finally {
        buf.release();
    }
}

From source file:alluxio.client.block.stream.NettyPacketWriter.java

License:Apache License

@Override
public void writePacket(final ByteBuf buf) throws IOException {
    final long len;
    final long offset;
    try (LockResource lr = new LockResource(mLock)) {
        Preconditions.checkState(!mClosed && !mEOFSent && !mCancelSent);
        Preconditions.checkArgument(buf.readableBytes() <= PACKET_SIZE);
        while (true) {
            if (mPacketWriteException != null) {
                throw new IOException(mPacketWriteException);
            }/*from   w  ww .j ava2s .c  om*/
            if (!tooManyPacketsInFlight()) {
                offset = mPosToQueue;
                mPosToQueue += buf.readableBytes();
                len = buf.readableBytes();
                break;
            }
            try {
                if (!mBufferNotFullOrFailed.await(WRITE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                    throw new IOException(String.format("Timeout to write packet to %d @ %s.", mId, mAddress));
                }
            } catch (InterruptedException e) {
                throw Throwables.propagate(e);
            }
        }
    } catch (Throwable e) {
        buf.release();
        throw e;
    }

    Protocol.WriteRequest writeRequest = Protocol.WriteRequest.newBuilder().setId(mId).setOffset(offset)
            .setSessionId(mSessionId).setTier(mTier).setType(mRequestType).build();
    DataBuffer dataBuffer = new DataNettyBufferV2(buf);
    mChannel.writeAndFlush(new RPCProtoMessage(new ProtoMessage(writeRequest), dataBuffer))
            .addListener(new WriteListener(offset + len));
}