Java Code Examples for io.netty.buffer.ByteBuf.release()

The following are Jave code examples for showing how to use release() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: wecard-server   File: NettyServerHandler.java   Source Code and License Vote up 6 votes
/**
 * 返回http信息
 * @param ctx
 * @param req
 * @param res
 */
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);
        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);
    }
}
 
Example 2
Project: nitmproxy   File: Http1FrontendHandlerTest.java   Source Code and License Vote up 6 votes
@Test
public void shouldHandleConnect() {
    Http1FrontendHandler handler = httpProxyHandler(true);
    inboundChannel.pipeline().addLast(handler);

    ByteBuf requestBytes = requestBytes(new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.CONNECT, "localhost:8000"));
    assertFalse(inboundChannel.writeInbound(requestBytes));

    assertNotNull(outboundChannel);
    assertTrue(outboundChannel.isActive());

    assertEquals(1, inboundChannel.outboundMessages().size());
    assertTrue(inboundChannel.outboundMessages().peek() instanceof ByteBuf);

    ByteBuf respByteBuf = (ByteBuf) inboundChannel.outboundMessages().poll();
    byte[] respBytes = new byte[respByteBuf.readableBytes()];
    respByteBuf.readBytes(respBytes);
    assertEquals("HTTP/1.1 200 OK\r\n\r\n", new String(respBytes));
    respByteBuf.release();
}
 
Example 3
Project: kcp-netty   File: UkcpServerChannel.java   Source Code and License Vote up 6 votes
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannel ch = javaChannel();
    UkcpServerChannelConfig config = config();
    RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();

    ByteBuf data = allocHandle.allocate(config.getAllocator());
    allocHandle.attemptedBytesRead(data.writableBytes());
    boolean free = true;
    try {
        ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
        int pos = nioData.position();
        InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
        if (remoteAddress == null) {
            return 0;
        }

        allocHandle.lastBytesRead(nioData.position() - pos);
        buf.add(UkcpPacket.newInstance(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()),
                remoteAddress));
        free = false;
        return 1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    } finally {
        if (free) {
            data.release();
        }
    }
}
 
Example 4
Project: TFWebSock   File: NettyHttpFileHandler.java   Source Code and License Vote up 6 votes
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
Example 5
Project: spark_deep   File: SparkSaslServer.java   Source Code and License Vote up 6 votes
/** Return a Base64-encoded string. */
private static String getBase64EncodedString(String str) {
  ByteBuf byteBuf = null;
  ByteBuf encodedByteBuf = null;
  try {
    byteBuf = Unpooled.wrappedBuffer(str.getBytes(StandardCharsets.UTF_8));
    encodedByteBuf = Base64.encode(byteBuf);
    return encodedByteBuf.toString(StandardCharsets.UTF_8);
  } finally {
    // The release is called to suppress the memory leak error messages raised by netty.
    if (byteBuf != null) {
      byteBuf.release();
      if (encodedByteBuf != null) {
        encodedByteBuf.release();
      }
    }
  }
}
 
Example 6
Project: JRediClients   File: RedissonExecutorService.java   Source Code and License Vote up 6 votes
private byte[] encode(Object task) {
    // erase RedissonClient field to avoid its serialization
    Injector.inject(task, null);
    
    ByteBuf buf = null;
    try {
        buf = codec.getValueEncoder().encode(task);
        byte[] dst = new byte[buf.readableBytes()];
        buf.readBytes(dst);
        return dst;
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        if (buf != null) {
            buf.release();
        }
    }
}
 
Example 7
Project: message-broker   File: MessageDaoImpl.java   Source Code and License Vote up 5 votes
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
private void populateMessageWithMetadata(Connection connection,
                                         String idListAsString, List<Long> idList,
                                         Map<Long, Message> messageMap) throws SQLException, BrokerException {
    String metadataSql = "SELECT MESSAGE_ID, EXCHANGE_NAME, ROUTING_KEY, CONTENT_LENGTH, MESSAGE_METADATA "
            + " FROM MB_METADATA WHERE MESSAGE_ID IN (" + idListAsString + ") ORDER BY MESSAGE_ID";


    PreparedStatement selectMetadata = null;
    ResultSet metadataResultSet = null;

    try {
        selectMetadata = connection.prepareStatement(metadataSql);
        for (int i = 0; i < idList.size(); i++) {
            selectMetadata.setLong(i + 1, idList.get(i));
        }

        metadataResultSet = selectMetadata.executeQuery();
        while (metadataResultSet.next()) {
            long messageId = metadataResultSet.getLong(1);
            String exchangeName = metadataResultSet.getString(2);
            String routingKey = metadataResultSet.getString(3);
            long contentLength = metadataResultSet.getLong(4);
            byte[] bytes = metadataResultSet.getBytes(5);
            ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
            try {
                Metadata metadata = new Metadata(messageId, routingKey, exchangeName, contentLength);
                metadata.setProperties(FieldTable.parse(buffer));
                metadata.setHeaders(FieldTable.parse(buffer));
                Message message = new Message(metadata);
                messageMap.put(messageId, message);
            } catch (Exception e) {
                throw new BrokerException("Error occurred while parsing metadata properties", e);
            } finally {
                buffer.release();
            }
        }
    } finally {
        close(metadataResultSet);
        close(selectMetadata);
    }
}
 
Example 8
Project: JRediClients   File: SnappyCodec.java   Source Code and License Vote up 5 votes
@Override
public Object decode(ByteBuf buf, State state) throws IOException {
    ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
    try {
        snappyDecoder.get().decode(buf, out);
        return innerCodec.getValueDecoder().decode(out, state);
    } finally {
        snappyDecoder.get().reset();
        out.release();
    }
}
 
Example 9
Project: angel   File: MatrixTransportClient.java   Source Code and License Vote up 5 votes
private void returnBuffer(Request item) {
  ByteBuf buf = item.getContext().getSerializedData();
  if(buf != null && buf.refCnt() > 0) {
    try {
      buf.release();
    } catch (Throwable x) {
      LOG.error("Release Buffer failed." , x);
    }
    item.getContext().setSerializedData(null);
  }
}
 
Example 10
Project: JRediClients   File: Hash.java   Source Code and License Vote up 5 votes
public static byte[] hash(ByteBuf objectState) {
    ByteBuffer b = objectState.internalNioBuffer(objectState.readerIndex(), objectState.readableBytes());
    long h1 = LongHashFunction.farmUo().hashBytes(b);
    long h2 = LongHashFunction.xx().hashBytes(b);

    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer((2 * Long.SIZE) / Byte.SIZE);
    try {
        buf.writeLong(h1).writeLong(h2);
        byte[] dst = new byte[buf.readableBytes()];
        buf.readBytes(dst);
        return dst;
    } finally {
        buf.release();
    }
}
 
Example 11
Project: CloudNet   File: ProtocolLengthDeserializer.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	in.markReaderIndex();
	byte[] lengthBytes = new byte[3];

	for (int i = 0; i < 3; i++)
	{
		if (!in.isReadable())
		{
			in.resetReaderIndex();
			return;
		}
		lengthBytes[i] = in.readByte();
		if (lengthBytes[i] >= 0)
		{
			ByteBuf buffer = Unpooled.wrappedBuffer(lengthBytes);

			try
			{
				int packetLength = readVarInt(buffer);
				if (in.readableBytes() < packetLength)
				{
					in.resetReaderIndex();
					return;
				}

				out.add(in.readBytes(packetLength));
			}
			finally
			{
				buffer.release();
			}

			return;
		}
	}
}
 
Example 12
Project: dremio-oss   File: TestBackwardsCompatibilityEncoder.java   Source Code and License Vote up 5 votes
private void testBuffers(ByteBuf[] buffers, SerializedField.Builder[] fields) {
  int i = 0;
  for (SerializedField.Builder field : fields) {
    i += fieldBuffersCount(field, buffers, i, buffers.length);
  }
  while (i < buffers.length && buffers[i].readableBytes() == 0) {
    ++ i;
  }
  assertEquals(buffers.length, i);
  for (ByteBuf byteBuf : buffers) {
    byteBuf.release();
  }
}
 
Example 13
Project: QDrill   File: SpoolingRawBatchBuffer.java   Source Code and License Vote up 5 votes
public void writeToStream(FSDataOutputStream stream) throws IOException {
  Stopwatch watch = new Stopwatch();
  watch.start();
  available = false;
  check = ThreadLocalRandom.current().nextLong();
  start = stream.getPos();
  logger.debug("Writing check value {} at position {}", check, start);
  stream.writeLong(check);
  batch.getHeader().writeDelimitedTo(stream);
  ByteBuf buf = batch.getBody();
  if (buf != null) {
    bodyLength = buf.capacity();
  } else {
    bodyLength = 0;
  }
  if (bodyLength > 0) {
    buf.getBytes(0, stream, bodyLength);
  }
  stream.hsync();
  FileStatus status = fs.getFileStatus(path);
  long len = status.getLen();
  logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
  batch.sendOk();
  latch.countDown();
  long t = watch.elapsed(TimeUnit.MICROSECONDS);
  logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
  if (buf != null) {
    buf.release();
  }
}
 
Example 14
Project: DecompiledMinecraft   File: MinecraftServer.java   Source Code and License Vote up 5 votes
private void addFaviconToStatusResponse(ServerStatusResponse response)
{
    File file1 = this.getFile("server-icon.png");

    if (file1.isFile())
    {
        ByteBuf bytebuf = Unpooled.buffer();

        try
        {
            BufferedImage bufferedimage = ImageIO.read(file1);
            Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
            Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
            ImageIO.write(bufferedimage, "PNG", (OutputStream)(new ByteBufOutputStream(bytebuf)));
            ByteBuf bytebuf1 = Base64.encode(bytebuf);
            response.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
        }
        catch (Exception exception)
        {
            logger.error((String)"Couldn\'t load server icon", (Throwable)exception);
        }
        finally
        {
            bytebuf.release();
        }
    }
}
 
Example 15
Project: FlexMC   File: MessageSplitter.java   Source Code and License Vote up 5 votes
@Override
protected void decode( ChannelHandlerContext channelHandlerContext, ByteBuf input, List<Object> output ) throws Exception {
    input.markReaderIndex();

    byte[] bytes = new byte[3];
    for ( int i = 0; i < bytes.length; i++ ) {
        if ( !input.isReadable() ) {
            input.resetReaderIndex();
            return;
        }
        bytes[i] = input.readByte();
        if ( bytes[i] >= 0 ) {
            ByteBuf buf = Unpooled.wrappedBuffer( bytes );
            try {
                int j = Message.readVarInt( buf );
                if ( input.readableBytes() < j ) {
                    input.resetReaderIndex();
                    return;
                }
                output.add( input.readBytes( j ) );
                return;
            } finally {
                buf.release();
            }
        }
    }
    throw new CorruptedFrameException( "length wider than 21-bit" );
}
 
Example 16
Project: neto   File: NetoByteToMessageEncoder.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext ctx, NetoOutboundByteMessage msg, ByteBuf out) throws Exception {
    ByteBuf buffer = msg.buildMessage(charset);
    out.writeBytes(buffer);
    logger.debug("encode - {}", buffer);
    buffer.release();
}
 
Example 17
Project: Backmemed   File: MinecraftServer.java   Source Code and License Vote up 5 votes
public void applyServerIconToResponse(ServerStatusResponse response)
{
    File file1 = this.getFile("server-icon.png");

    if (!file1.exists())
    {
        file1 = this.getActiveAnvilConverter().getFile(this.getFolderName(), "icon.png");
    }

    if (file1.isFile())
    {
        ByteBuf bytebuf = Unpooled.buffer();

        try
        {
            BufferedImage bufferedimage = ImageIO.read(file1);
            Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
            Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
            ImageIO.write(bufferedimage, "PNG", (OutputStream)(new ByteBufOutputStream(bytebuf)));
            ByteBuf bytebuf1 = Base64.encode(bytebuf);
            response.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
        }
        catch (Exception exception)
        {
            LOG.error((String)"Couldn\'t load server icon", (Throwable)exception);
        }
        finally
        {
            bytebuf.release();
        }
    }
}
 
Example 18
Project: CustomWorldGen   File: ServerListEntryNormal.java   Source Code and License Vote up 4 votes
private void prepareServerIcon()
{
    if (this.server.getBase64EncodedIconData() == null)
    {
        this.mc.getTextureManager().deleteTexture(this.serverIcon);
        this.icon = null;
    }
    else
    {
        ByteBuf bytebuf = Unpooled.copiedBuffer((CharSequence)this.server.getBase64EncodedIconData(), Charsets.UTF_8);
        ByteBuf bytebuf1 = Base64.decode(bytebuf);
        BufferedImage bufferedimage;
        label101:
        {
            try
            {
                bufferedimage = TextureUtil.readBufferedImage(new ByteBufInputStream(bytebuf1));
                Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
                Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
                break label101;
            }
            catch (Throwable throwable)
            {
                LOGGER.error("Invalid icon for server {} ({})", new Object[] {this.server.serverName, this.server.serverIP, throwable});
                this.server.setBase64EncodedIconData((String)null);
            }
            finally
            {
                bytebuf.release();
                bytebuf1.release();
            }

            return;
        }

        if (this.icon == null)
        {
            this.icon = new DynamicTexture(bufferedimage.getWidth(), bufferedimage.getHeight());
            this.mc.getTextureManager().loadTexture(this.serverIcon, this.icon);
        }

        bufferedimage.getRGB(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight(), this.icon.getTextureData(), 0, bufferedimage.getWidth());
        this.icon.updateDynamicTexture();
    }
}
 
Example 19
Project: BaseClient   File: ServerListEntryNormal.java   Source Code and License Vote up 4 votes
private void prepareServerIcon()
{
    if (this.field_148301_e.getBase64EncodedIconData() == null)
    {
        this.mc.getTextureManager().deleteTexture(this.field_148306_i);
        this.field_148305_h = null;
    }
    else
    {
        ByteBuf bytebuf = Unpooled.copiedBuffer((CharSequence)this.field_148301_e.getBase64EncodedIconData(), Charsets.UTF_8);
        ByteBuf bytebuf1 = Base64.decode(bytebuf);
        BufferedImage bufferedimage;
        label101:
        {
            try
            {
                bufferedimage = TextureUtil.readBufferedImage(new ByteBufInputStream(bytebuf1));
                Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
                Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
                break label101;
            }
            catch (Throwable throwable)
            {
                logger.error("Invalid icon for server " + this.field_148301_e.serverName + " (" + this.field_148301_e.serverIP + ")", throwable);
                this.field_148301_e.setBase64EncodedIconData((String)null);
            }
            finally
            {
                bytebuf.release();
                bytebuf1.release();
            }

            return;
        }

        if (this.field_148305_h == null)
        {
            this.field_148305_h = new DynamicTexture(bufferedimage.getWidth(), bufferedimage.getHeight());
            this.mc.getTextureManager().loadTexture(this.field_148306_i, this.field_148305_h);
        }

        bufferedimage.getRGB(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight(), this.field_148305_h.getTextureData(), 0, bufferedimage.getWidth());
        this.field_148305_h.updateDynamicTexture();
    }
}
 
Example 20
Project: CustomWorldGen   File: LegacyPingHandler.java   Source Code and License Vote up 4 votes
public void channelRead(ChannelHandlerContext p_channelRead_1_, Object p_channelRead_2_) throws Exception
{
    ByteBuf bytebuf = (ByteBuf)p_channelRead_2_;
    bytebuf.markReaderIndex();
    boolean flag = true;

    try
    {
        if (bytebuf.readUnsignedByte() == 254)
        {
            InetSocketAddress inetsocketaddress = (InetSocketAddress)p_channelRead_1_.channel().remoteAddress();
            MinecraftServer minecraftserver = this.networkSystem.getServer();
            int i = bytebuf.readableBytes();

            switch (i)
            {
                case 0:
                    LOGGER.debug("Ping: (<1.3.x) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s2 = String.format("%s\u00a7%d\u00a7%d", new Object[] {minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    this.writeAndFlush(p_channelRead_1_, this.getStringBuffer(s2));
                    break;
                case 1:

                    if (bytebuf.readUnsignedByte() != 1)
                    {
                        return;
                    }

                    LOGGER.debug("Ping: (1.4-1.5.x) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] {Integer.valueOf(127), minecraftserver.getMinecraftVersion(), minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    this.writeAndFlush(p_channelRead_1_, this.getStringBuffer(s));
                    break;
                default:
                    boolean flag1 = bytebuf.readUnsignedByte() == 1;
                    flag1 = flag1 & bytebuf.readUnsignedByte() == 250;
                    flag1 = flag1 & "MC|PingHost".equals(new String(bytebuf.readBytes(bytebuf.readShort() * 2).array(), Charsets.UTF_16BE));
                    int j = bytebuf.readUnsignedShort();
                    flag1 = flag1 & bytebuf.readUnsignedByte() >= 73;
                    flag1 = flag1 & 3 + bytebuf.readBytes(bytebuf.readShort() * 2).array().length + 4 == j;
                    flag1 = flag1 & bytebuf.readInt() <= 65535;
                    flag1 = flag1 & bytebuf.readableBytes() == 0;

                    if (!flag1)
                    {
                        return;
                    }

                    LOGGER.debug("Ping: (1.6) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s1 = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] {Integer.valueOf(127), minecraftserver.getMinecraftVersion(), minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    ByteBuf bytebuf1 = this.getStringBuffer(s1);

                    try
                    {
                        this.writeAndFlush(p_channelRead_1_, bytebuf1);
                    }
                    finally
                    {
                        bytebuf1.release();
                    }
            }

            bytebuf.release();
            flag = false;
            return;
        }
    }
    catch (RuntimeException var21)
    {
        return;
    }
    finally
    {
        if (flag)
        {
            bytebuf.resetReaderIndex();
            p_channelRead_1_.channel().pipeline().remove("legacy_query");
            p_channelRead_1_.fireChannelRead(p_channelRead_2_);
        }
    }
}