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:com.celeral.netlet.benchmark.netty.BenchmarkTcpClient.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;
    long timestamp = byteBuf.getLong(0);
    byteBuf.release();

    if (timestamp < -2) {
        logger.error("Received bad timestamp {}", timestamp);
        ctx.close();/*from ww w  . ja va 2  s .co m*/
        return;
    } else if (timestamp != this.timestamp) {
        logger.error("Received bad timestamp {}. Sent timestamp {}", timestamp, this.timestamp);
        ctx.close();
        return;
    } else if (timestamp > 0) {
        benchmarkResults.addResult(System.nanoTime() - timestamp);
    }
    send(ctx);
}

From source file:com.cmz.http.file.HttpStaticFileServerHandler.java

License:Apache License

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

    StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n")
            .append("<html><head><meta charset='utf-8' /><title>").append("Listing of: ").append(dirPath)
            .append("</title></head><body>\r\n")

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

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

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }//from  w w  w .  j  a va  2  s .co  m

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

        buf.append("<li><a href=\"").append(name).append("\">").append(name).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:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest req,
        final FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != HttpResponseStatus.OK.code()) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/* w w w .j av a  2  s .  com*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

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

From source file:com.codnos.dbgp.internal.handlers.DBGpCommandDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception {
    int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL);
    if (nullPosition < 0)
        return;//  w  w  w .  ja v  a 2s  . c  o m
    int length = nullPosition - in.readerIndex();
    ByteBuf msgBuffer = in.readBytes(length);
    in.readByte();
    objects.add(msgBuffer.toString(UTF_8));
    msgBuffer.release();
}

From source file:com.codnos.dbgp.internal.handlers.DBGpResponseDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception {
    final int length = in.readableBytes();
    LOGGER.fine("got something from engine (" + length + " bytes)");
    int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL);
    int readerIndex = in.readerIndex();
    int numberOfBytes = nullPosition - readerIndex;
    LOGGER.fine("found nullposition on " + nullPosition + " and readerIndex is " + readerIndex
            + " calculated number of bytes " + numberOfBytes);
    if (numberOfBytes <= 0) {
        LOGGER.fine("not enough to read, finishing");
        in.resetReaderIndex();// w  ww.j a v  a  2  s  . c  o  m
        return;
    }
    if (nullPosition > length) {
        LOGGER.fine("have null position further than length, finishing");
        in.resetReaderIndex();
        return;
    }
    ByteBuf sizeBuf = in.readBytes(numberOfBytes);
    in.readByte();
    String sizeBufAsString = sizeBuf.toString(UTF_8);
    int size = Integer.parseInt(sizeBufAsString);
    int expectedSize = sizeBuf.readableBytes() + NULL_BYTE_SIZE + size + NULL_BYTE_SIZE;
    if (length < expectedSize) {
        LOGGER.fine("don't have the whole message yet (expected " + expectedSize + "), finishing");
        in.resetReaderIndex();
        sizeBuf.release();
        return;
    }
    ByteBuf messageBuf = in.readBytes(size);
    in.readByte();
    objects.add(messageBuf.toString(UTF_8));
    sizeBuf.release();
    messageBuf.release();
}

From source file:com.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, HttpResponse res) {
    channel.write(res);/*from  ww w  .j av  a2 s . com*/

    if (log.isTraceEnabled()) {
        log.trace("Out message: {} - sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
    }

    if (out.isReadable()) {
        channel.write(out);
    } else {
        out.release();
    }

    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException {
    while (true) {
        Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
        Packet packet = queue.poll();/*from  w ww .j  a va2  s .  co  m*/
        if (packet == null) {
            break;
        }

        final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
        encoder.encodePacket(packet, out, ctx.alloc(), true);

        WebSocketFrame res = new TextWebSocketFrame(out);
        if (log.isTraceEnabled()) {
            log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
        }
        if (out.isReadable()) {
            ctx.channel().writeAndFlush(res);
        } else {
            out.release();
        }

        for (ByteBuf buf : packet.getAttachments()) {
            ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
            outBuf.writeByte(4);
            outBuf.writeBytes(buf);
            if (log.isTraceEnabled()) {
                log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
            }
            ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
        }
    }
}

From source file:com.corundumstudio.socketio.parser.Decoder.java

License:Apache License

public Packet decodePacket(String string, UUID uuid) throws IOException {
    ByteBuf buf = Unpooled.copiedBuffer(string, CharsetUtil.UTF_8);
    try {//from  www  .  j  a  va  2 s .co  m
        Packet packet = decodePacket(buf, uuid);
        return packet;
    } finally {
        buf.release();
    }
}

From source file:com.corundumstudio.socketio.parser.Encoder.java

License:Apache License

public void encodePackets(Queue<Packet> packets, ByteBuf buffer, ByteBufAllocator allocator)
        throws IOException {
    if (packets.size() == 1) {
        Packet packet = packets.poll();//from w ww  . j a  va 2 s  . co  m
        encodePacket(packet, buffer);
    } else {
        int counter = 0;
        while (true) {
            Packet packet = packets.poll();
            if (packet == null) {
                break;
            }
            counter++;
            // to prevent infinity out message
            if (counter == 100) {
                return;
            }

            ByteBuf packetBuffer = allocateBuffer(allocator);
            try {
                int len = encodePacket(packet, packetBuffer);
                byte[] lenBytes = toChars(len);

                buffer.writeBytes(Packet.DELIMITER_BYTES);
                buffer.writeBytes(lenBytes);
                buffer.writeBytes(Packet.DELIMITER_BYTES);
                buffer.writeBytes(packetBuffer);
            } finally {
                packetBuffer.release();
            }
        }
    }
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

@Deprecated
public Packet decodePacket(String string, UUID uuid) throws IOException {
    ByteBuf buf = Unpooled.copiedBuffer(string, CharsetUtil.UTF_8);
    try {//from w ww. j a v a 2 s  . c o  m
        return null;
    } finally {
        buf.release();
    }
}