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:alluxio.worker.netty.DataServerUFSFileReadHandler.java

License:Apache License

@Override
protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException {
    ByteBuf buf = channel.alloc().buffer(len, len);
    try {//www.  j av a2  s .  co m
        InputStream in = ((FileReadRequestInternal) mRequest).mInputStream;
        if (in != null) { // if we have not reached the end of the file
            while (buf.writableBytes() > 0 && buf.writeBytes(in, buf.writableBytes()) != -1) {
            }
        }
        if (buf.readableBytes() == 0) {
            buf.release();
            return null;
        }
        return new DataNettyBufferV2(buf);
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}

From source file:alluxio.worker.netty.ReadHandlerTest.java

License:Apache License

/**
 * Checks all the read responses./*from  w w  w  . j a v  a  2 s  .  c  o  m*/
 */
protected void checkAllReadResponses(EmbeddedChannel channel, long checksumExpected) {
    boolean eof = false;
    long checksumActual = 0;
    while (!eof) {
        Object readResponse = waitForOneResponse(channel);
        if (readResponse == null) {
            Assert.fail();
            break;
        }
        DataBuffer buffer = checkReadResponse(readResponse, PStatus.OK);
        eof = buffer == null;
        if (buffer != null) {
            if (buffer instanceof DataNettyBufferV2) {
                ByteBuf buf = (ByteBuf) buffer.getNettyOutput();
                while (buf.readableBytes() > 0) {
                    checksumActual += BufferUtils.byteToInt(buf.readByte());
                }
                buf.release();
            } else {
                Assert.assertTrue(buffer instanceof DataFileChannel);
                final ByteBuffer byteBuffer = ByteBuffer.allocate((int) buffer.getLength());
                WritableByteChannel writableByteChannel = new WritableByteChannel() {
                    @Override
                    public boolean isOpen() {
                        return true;
                    }

                    @Override
                    public void close() throws IOException {
                    }

                    @Override
                    public int write(ByteBuffer src) throws IOException {
                        int sz = src.remaining();
                        byteBuffer.put(src);
                        return sz;
                    }
                };
                try {
                    ((FileRegion) buffer.getNettyOutput()).transferTo(writableByteChannel, 0);
                } catch (IOException e) {
                    Assert.fail();
                }
                byteBuffer.flip();
                while (byteBuffer.remaining() > 0) {
                    checksumActual += BufferUtils.byteToInt(byteBuffer.get());
                }
            }
        }
    }
    Assert.assertEquals(checksumExpected, checksumActual);
    Assert.assertTrue(eof);
}

From source file:app.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//  w  ww. ja v  a 2s  .  c o m
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:arekkuusu.grimoireOfAlice.client.gui.GuiScreenYoukaiBook.java

License:Open Source License

private void sendBookToServer(boolean p_146462_1_) {
    if (bookIsUnsigned && field_146481_r) {
        if (bookPages != null) {
            String s;//from ww w.j  a va  2  s.  c o  m

            while (bookPages.tagCount() > 1) {
                s = bookPages.getStringTagAt(bookPages.tagCount() - 1);

                if (s.length() != 0) {
                    break;
                }

                bookPages.removeTag(bookPages.tagCount() - 1);
            }

            if (bookObj.hasTagCompound()) {
                NBTTagCompound nbttagcompound = bookObj.getTagCompound();
                nbttagcompound.setTag("pages", bookPages);
            } else {
                bookObj.setTagInfo("pages", bookPages);
            }

            s = "MC|BEdit";

            if (p_146462_1_) {
                s = "MC|BSign";
                bookObj.setTagInfo("author", new NBTTagString(editingPlayer.getCommandSenderName()));
                bookObj.setTagInfo("title", new NBTTagString(bookTitle.trim().replace("k", "").substring(2)));
                bookObj.func_150996_a(GOAItem.enchantedBook);
            }

            ByteBuf bytebuf = Unpooled.buffer();

            try {
                new PacketBuffer(bytebuf).writeItemStackToBuffer(bookObj);
                mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload(s, bytebuf));
            } catch (Exception exception) {
                LOGGER.error("Couldn\'t send book info", exception);
            } finally {
                bytebuf.release();
            }
        }
    }
}

From source file:at.yawk.dbus.protocol.object.ArrayObject.java

@Override
public void serialize(AlignableByteBuf buf) {
    ByteBuf tempBuffer = serializeValues(ArrayObject.allocateBufferForWrite(buf.getBuffer()));

    buf.alignWrite(4);//  w  ww  .ja  v  a  2s . co  m
    buf.getBuffer().writeInt(tempBuffer.writerIndex());
    if (tempBuffer.isReadable()) {
        buf.getBuffer().writeBytes(tempBuffer);
    }
    tempBuffer.release();
}

From source file:bean.lee.demo.netty.learn.http.file.HttpStaticFileServerHandler.java

License:Apache License

private static void sendListing(ChannelHandlerContext ctx, File dir) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");

    StringBuilder buf = new StringBuilder();
    String dirPath = dir.getPath();

    buf.append("<!DOCTYPE html>\r\n");
    buf.append("<html><head><title>");
    buf.append("Listing of: ");
    buf.append(dirPath);/*  w w  w  . jav  a  2  s .c  o m*/
    buf.append("</title></head><body>\r\n");

    buf.append("<h3>Listing of: ");
    buf.append(dirPath);
    buf.append("</h3>\r\n");

    buf.append("<ul>");
    buf.append("<li><a href=\"../\">..</a></li>\r\n");

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }

        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }

        buf.append("<li><a href=\"");
        buf.append(name);
        buf.append("\">");
        buf.append(name);
        buf.append("</a></li>\r\n");
    }

    buf.append("</ul></body></html>\r\n");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:books.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

private static void sendListing(ChannelHandlerContext ctx, File dir) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    StringBuilder buf = new StringBuilder();
    String dirPath = dir.getPath();
    buf.append("<!DOCTYPE html>\r\n");
    buf.append("<html><head><title>");
    buf.append(dirPath);//from w  w  w  .  j ava  2s. c om
    buf.append(" ");
    buf.append("</title></head><body>\r\n");
    buf.append("<h3>");
    buf.append(dirPath).append(" ");
    buf.append("</h3>\r\n");
    buf.append("<ul>");
    buf.append("<li><a href=\"../\">..</a></li>\r\n");
    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }
        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }
        buf.append("<li><a href=\"");
        buf.append(name);
        buf.append("\">");
        buf.append(name);
        buf.append("</a></li>\r\n");
    }
    buf.append("</ul></body></html>\r\n");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // /*ww w . j a  v a2  s.  c  om*/
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // ?Keep-Alive
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // 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.  j  a v a  2 s . c  o m*/
        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:ch.ethz.globis.distindex.middleware.net.MiddlewareChannelHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    String clientHost = ctx.channel().remoteAddress().toString();
    ByteBuffer response = ioHandler.handle(clientHost, buf.nioBuffer());
    ByteBuf nettyBuf = Unpooled.wrappedBuffer(response);
    ByteBuf sizeBuf = Unpooled.copyInt(nettyBuf.readableBytes());

    ctx.write(sizeBuf);/*from   ww  w  .j  a va 2  s.  c  o  m*/
    ctx.write(nettyBuf);
    ctx.flush();
    buf.release();
}