Java Code Examples for io.netty.buffer.ByteBuf#clear()

The following examples show how to use io.netty.buffer.ByteBuf#clear() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultipartParser.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(final PartHandler handler, final ByteBuf rawData) throws IOException {
    ByteBuf buf = bufferPool.allocateBuffer();
    try {
        do {
            buf.clear();
            try {
                decoder.decode(rawData, buf);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            handler.data(buf);
        } while (rawData.isReadable());
    } finally {
        buf.release();
    }
}
 
Example 2
Source File: MqttVariableByteIntegerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_encodeVariableByteInteger_3_bytes() {
    final ByteBuf byteBuf = Unpooled.buffer();
    for (int i = 0; i < 127; i++) {
        for (int j = 0; j < 127; j++) {
            for (int k = 1; k < 127; k++) {
                MqttVariableByteInteger.encode(i + j * 128 + k * 128 * 128, byteBuf);
                assertEquals(128 + i, byteBuf.readUnsignedByte());
                assertEquals(128 + j, byteBuf.readUnsignedByte());
                assertEquals(k, byteBuf.readUnsignedByte());
                assertFalse(byteBuf.isReadable());
                byteBuf.clear();
            }
        }
    }
    byteBuf.release();
}
 
Example 3
Source File: PortUnificationServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        return;
    }

    if (isSsl(in)) {
        enableSsl(ctx);
    } else {
        final int magic1 = in.getUnsignedByte(in.readerIndex());
        final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
        if (isGzip(magic1, magic2)) {
            enableGzip(ctx);
        } else if (isHttp(magic1, magic2)) {
            switchToHttp(ctx);
        } else if (isFactorial(magic1)) {
            switchToFactorial(ctx);
        } else {
            // Unknown protocol; discard everything and close the connection.
            in.clear();
            ctx.close();
        }
    }
}
 
Example 4
Source File: DB2Decoder.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
private void decodePayload(ByteBuf payload, int payloadLength) {
  CommandCodec<?, ?> ctx = inflight.peek();
  int startIndex = payload.readerIndex();
  try {
    if (LOG.isDebugEnabled())
      LOG.debug("<<< DECODE " + ctx + " (" + payloadLength + " bytes)");
    ctx.decodePayload(payload, payloadLength);
  } catch (DB2Exception connex) {
    // A common connection error occurred, so don't bother with a hex dump and
    // generic error message
    ctx.completionHandler.handle(CommandResponse.failure(connex));
  } catch (Throwable t) {
    int i = payload.readerIndex();
    payload.readerIndex(startIndex);
    StringBuilder sb = new StringBuilder(
        "FATAL: Error parsing buffer at index " + i + " / 0x" + Integer.toHexString(i) + "\n");
    ByteBufUtil.appendPrettyHexDump(sb, payload);
    LOG.error(sb.toString(), t);
    ctx.completionHandler.handle(CommandResponse.failure(t));
  } finally {
    payload.clear();
    payload.release();
  }
}
 
Example 5
Source File: NumericOperandParserTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testSerializeVariableByte() {
    final ByteBuf nlriByteBuf = Unpooled.buffer();
    // test with a operand with endOfList set to true, but override with false
    NumericOneByteOperandParser.INSTANCE.serialize(
            new NumericOperand(false, true, true, false, false),
            1,
            false,
            nlriByteBuf);
    assertArrayEquals(new byte[]{(byte) 0x01}, ByteArray.readAllBytes(nlriByteBuf));

    // test with a operand with endOfList set to false, but override with true
    nlriByteBuf.clear();
    NumericOneByteOperandParser.INSTANCE.serialize(
            new NumericOperand(false, true, true, false, false),
            1,
            true,
            nlriByteBuf);
    assertArrayEquals(new byte[]{(byte) 0x81}, ByteArray.readAllBytes(nlriByteBuf));
}
 
Example 6
Source File: Mqtt3DisconnectDecoder.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Override
public DISCONNECT decode(final Channel channel, final ByteBuf buf, final byte header) {

    if (ProtocolVersion.MQTTv3_1_1 == channel.attr(MQTT_VERSION).get()) {
        if (!validateHeader(header)) {
            if (log.isDebugEnabled()) {
                log.debug("A client (IP: {}) sent a disconnect message with an invalid fixed header. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
            }
            eventLog.clientWasDisconnected(channel, "Invalid DISCONNECT fixed header");
            channel.close();
            buf.clear();
            return null;
        }
    }

    return DISCONNECT;
}
 
Example 7
Source File: EntityRewrite.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 5 votes vote down vote up
public PacketWrapper rewrite(PacketWrapper packet, IntUnaryOperator rewritefunc) {
	ByteBuf buf = packet.buf;
	buf.markReaderIndex();
	int packetId = readPacketId(buf);
	EntityRewriteCommand[] chain = rewritechains[packetId];
	if (chain == null) {
		buf.resetReaderIndex();
		return packet;
	}
	ByteBuf tmpBuffer = Allocator.allocateBuffer();
	try {
		writePacketId(tmpBuffer, packetId);
		for (EntityRewriteCommand command : chain) {
			command.rewrite(buf, tmpBuffer, rewritefunc);
		}
		buf.clear();
		if (buf.maxWritableBytes() < tmpBuffer.readableBytes()) {
			packet.trySingleRelease();
			return new PacketWrapper(packet.packet, tmpBuffer);
		} else {
			buf.writeBytes(tmpBuffer);
			tmpBuffer.release();
			return packet;
		}
	} catch (Exception e) {
		tmpBuffer.release();
		throw new RuntimeException("Entity remap error in packet ID " + packetId, e);
	}
}
 
Example 8
Source File: BSTIndex.java    From tajo with Apache License 2.0 5 votes vote down vote up
private int flushBuffer(ByteBuf byteBuf, FileChannel channel, FSDataOutputStream out) throws IOException {
  // write buffer to file
  int readableBytes = byteBuf.readableBytes();
  if (readableBytes > 0) {
    if (isLocal) {
      byteBuf.readBytes(channel, readableBytes);
    } else {
      byteBuf.readBytes(out, readableBytes);
    }
    byteBuf.clear();
  }
  return readableBytes;
}
 
Example 9
Source File: NulsMessageDecoder.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    long readMagicNumber = in.getUnsignedIntLE(0);
    if (NodeGroupManager.getInstance().validMagicNumber(readMagicNumber)) {
        Object decoded = newDecoder.decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
    } else {
        LoggerUtil.COMMON_LOG.error("readMagicNumber={} illegal message REC", readMagicNumber);
        in.clear();
        ctx.close();

    }
}
 
Example 10
Source File: Mqtt3SubackDecoder.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
public SUBACK decode(final Channel channel, final ByteBuf buf, final byte header) {
    if (ProtocolVersion.MQTTv3_1_1 == channel.attr(MQTT_VERSION).get()) {
        if (!validateHeader(header)) {
            log.error("A client (IP: {}) sent a Suback with an invalid fixed header. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
            eventLog.clientWasDisconnected(channel, "Invalid SUBACK fixed header");
            channel.close();
            buf.clear();
            return null;
        }
    }

    final int messageId = buf.readUnsignedShort();
    final List<Mqtt5SubAckReasonCode> returnCodes = new ArrayList<>();
    while (buf.isReadable()) {
        final byte qos = buf.readByte();
        if (qos < 0 || qos > 2) {
            log.error("A client (IP: {}) sent a suback which contained an invalid QoS. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
            eventLog.clientWasDisconnected(channel, "Invalid SUBACK qos");
            channel.close();
            buf.clear();
            return null;
        }
        returnCodes.add(Mqtt5SubAckReasonCode.fromCode(qos));
    }
    return new SUBACK(messageId, returnCodes);
}
 
Example 11
Source File: Mqtt3PubrecDecoder.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
public PUBREC decode(final Channel channel, final ByteBuf buf, final byte header) {

    if (ProtocolVersion.MQTTv3_1_1 == channel.attr(MQTT_VERSION).get()) {
        if (!validateHeader(header)) {
            if (log.isDebugEnabled()) {
                log.debug("A client (IP: {}) sent a Pubrec with an invalid fixed header. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
            }
            eventLog.clientWasDisconnected(channel, "Invalid pubrec fixed header");
            channel.close();
            buf.clear();
            return null;
        }
    }

    if (buf.readableBytes() < 2) {
        if (log.isDebugEnabled()) {
            log.debug("A client (IP: {}) sent a Pubrec without a message id. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
        }
        eventLog.clientWasDisconnected(channel, "Sent pubrec without message id");
        channel.close();
        buf.clear();
        return null;
    }
    final int messageId = buf.readUnsignedShort();

    return new PUBREC(messageId);
}
 
Example 12
Source File: Ipv6UtilTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testWriteIpv6Prefix() {
    final byte[] result = { 0x20, (byte) 0x01, 0x0d, (byte) 0xb8, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x40 };
    final ByteBuf output = Unpooled.buffer(Ipv6Util.PREFIX_BYTE_LENGTH);
    writeIpv6Prefix(new Ipv6Prefix("2001:db8:1:2::/64"), output);
    assertArrayEquals(result, output.array());

    output.clear();
    final byte[] zeroResult = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    writeIpv6Prefix(null, output);
    assertArrayEquals(zeroResult, output.array());
}
 
Example 13
Source File: Mqtt3PubcompDecoder.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
public PUBCOMP decode(final Channel channel, final ByteBuf buf, final byte header) {

    if (ProtocolVersion.MQTTv3_1_1 == channel.attr(MQTT_VERSION).get()) {
        if (!validateHeader(header)) {
            if (log.isDebugEnabled()) {
                log.debug("A client (IP: {}) sent a Pubcomp with an invalid fixed header. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
            }
            eventLog.clientWasDisconnected(channel, "Invalid PUBCOMP fixed header");
            channel.close();
            buf.clear();
            return null;
        }
    }

    if (buf.readableBytes() < 2) {
        if (log.isDebugEnabled()) {
            log.debug("A client (IP: {}) sent a Pubcomp without a message id. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
        }
        eventLog.clientWasDisconnected(channel, "Sent PUBCOMP without message id");
        channel.close();
        buf.clear();
        return null;
    }
    final int messageId = buf.readUnsignedShort();

    return new PUBCOMP(messageId);
}
 
Example 14
Source File: ClientChannelHandler.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        String remoteIP = socketChannel.remoteAddress().getHostString();
        int port = socketChannel.remoteAddress().getPort();
        ByteBuf buf = (ByteBuf) msg;
        NulsByteBuffer byteBuffer = null;
        Node node = null;
        try {
            Attribute<Node> nodeAttribute = ctx.channel().attr(key);
            node = nodeAttribute.get();
            if (node != null) {
                byte[] bytes = new byte[buf.readableBytes()];
                buf.readBytes(bytes);
                byteBuffer = new NulsByteBuffer(bytes);
            } else {
                Log.error("-----------------client channelRead  node is null -----------------" + remoteIP + ":" + port);
                ctx.channel().close();
            }
        } catch (Exception e) {
            Log.error(e);
//            throw e;
        } finally {
            buf.clear();
        }
        MessageManager.getInstance().receiveMessage(byteBuffer, node);
    }
 
Example 15
Source File: MuChannelHandler.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	ByteBuf buff = (msg instanceof ByteBuffer) ? ctx.alloc().buffer().writeBytes((ByteBuffer)msg) : (ByteBuf)msg;

	buff.readerIndex(2);
	
	int opcode = buff.readUnsignedByte();
	switch (opcode) { // double opcode
		case 0xf1:
		case 0xf3:
		case 0x0e:
		case 0x03:
			buff.readerIndex(buff.readerIndex() - 1);
			opcode = buff.readUnsignedShort(); // ex 0xF1_03
			break;
		default:
			break;
	}
	
	if(opcode == 0xe00) { // Time packet?
		buff.clear();
		buff.release();
		return;
	}

	ReadPacket packet = clientpackets.get(opcode);
	
	if(packet != null) {
		MuClient client = ctx.channel().attr(MuClient.ClientKey).get();
		//System.out.println("Got opcode: 0x"+PrintData.fillHex(opcode, 2)+ " packet = \n"+packet.getClass().getSimpleName());
		packet.read(client, buff);
	}
	else {
		log.warn("Unknown packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]. Dump: ");
		log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
	}
	
	//log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
	
	if(buff.refCnt() > 0) {
		//System.out.println("Handler Release when packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]");
		buff.release();
	}
}
 
Example 16
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
		List<Object> out) throws Exception {
	if (in.readableBytes() < RemotingConstants.THREE) {
		return;
	}
	final int magic1 = in.getUnsignedByte(in.readerIndex());
	final int magic2 = in.getUnsignedByte(in.readerIndex()+1);
	final int magic3 = in.getUnsignedByte(in.readerIndex()+2);
	if (isJar(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarReceiveHandler(ctx);
	} else if (isJas(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarSendHandler(ctx);
	} else if (isTxr(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesReceiveHandler(ctx);
	} else if (isTxs(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesSendHandler(ctx);
	} else if (isCmd(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndForgetCommandHandler(ctx);
	} else if(isCma(magic1, magic2, magic3)){
		throwAwayReadUnsignedBytes(in);
		invokeAsyncFireAndForgetCommandHandler(ctx);
	}/*else if (isCmg(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndGetCommandHandler(ctx);
	}*/ else if (isCmo(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndGetObjectResponseCommandHandler(ctx);
	} else if (isCmoHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndGetObjectResponseCommandHandlerForHA(ctx);
	} else if (isCmdHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndForgetCommandHandlerForHA(ctx);
	} else if (isTxrHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesReceiveHandlerForHA(ctx);
	} else if (isTxsHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesSendHandlerForHA(ctx);
	} else if (isJarHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarReceiveHandlerForHA(ctx);
	} else if (isJasHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarSendHandlerForHA(ctx);
	}else if (isSdaHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeAgentShutdownHandler(ctx);
	} else {
        // Unknown protocol; discard everything and close the connection.
        in.clear();
        ctx.close();
	}

	if (haEnabled) {
		syncExecutor.sync();
	}
}
 
Example 17
Source File: CachedResource.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void serveRangeAsync(OutputChannel sender, HttpServerExchange exchange, long start, long end) {
    final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
    if (dataCache == null) {
        ((RangeAwareResource) underlyingResource).serveRangeAsync(sender, exchange, start, end);
        return;
    }

    final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
    final Long length = getContentLength();
    //if it is not eligible to be served from the cache
    if (length == null || length > cachingResourceManager.getMaxFileSize()) {
        ((RangeAwareResource) underlyingResource).serveRangeAsync(sender, exchange, start, end);
        return;
    }
    //it is not cached yet, just serve it directly
    if (existing == null || !existing.enabled() || !existing.reference()) {
        //it is not cached yet, we can't use a range request to establish the cached item
        //so we just serve it
        ((RangeAwareResource) underlyingResource).serveRangeAsync(sender, exchange, start, end);
    } else {
        //serve straight from the cache
        ByteBuf[] buffers;
        boolean ok = false;
        try {
            LimitedBufferSlicePool.PooledByteBuffer[] pooled = existing.buffers();
            buffers = new ByteBuf[pooled.length];
            for (int i = 0; i < buffers.length; i++) {
                // Keep position from mutating
                buffers[i] = pooled[i].getBuffer().duplicate();
            }
            ok = true;
        } finally {
            if (!ok) {
                existing.dereference();
            }
        }
        if (start > 0) {
            long startDec = start;
            long endCount = 0;
            //handle the start of the range
            for (ByteBuf b : buffers) {
                if (endCount == end) {
                    b.clear();
                    continue;
                } else if (endCount + b.readableBytes() < end) {
                    endCount += b.readableBytes();
                } else {
                    b.writerIndex((int) (b.readerIndex() + (end - endCount)));
                    endCount = end;
                }
                if (b.readableBytes() >= startDec) {
                    startDec = 0;
                    b.readerIndex((int) (b.readerIndex() + startDec));
                } else {
                    startDec -= b.readableBytes();
                    b.clear();
                }
            }
        }
        sender.writeAsync(Unpooled.wrappedBuffer(buffers), true, new DereferenceCallback(existing, IoCallback.END_EXCHANGE), null);
    }
}
 
Example 18
Source File: MultipartParser.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(final PartHandler handler, final ByteBuf rawData) throws IOException {
    boolean equalsSeen = this.equalsSeen;
    byte firstCharacter = this.firstCharacter;
    ByteBuf buf = bufferPool.allocateBuffer();
    try {
        while (rawData.isReadable()) {
            byte b = rawData.readByte();
            if (equalsSeen) {
                if (firstCharacter == 0) {
                    if (b == '\n' || b == '\r') {
                        //soft line break
                        //ignore
                        equalsSeen = false;
                    } else {
                        firstCharacter = b;
                    }
                } else {
                    int result = Character.digit((char) firstCharacter, 16);
                    result <<= 4; //shift it 4 bytes and then add the next value to the end
                    result += Character.digit((char) b, 16);
                    buf.writeByte((byte) result);
                    equalsSeen = false;
                    firstCharacter = 0;
                }
            } else if (b == '=') {
                equalsSeen = true;
            } else {
                buf.writeByte(b);
                if (!buf.isWritable()) {
                    handler.data(buf);
                    buf.clear();
                }
            }
        }
        handler.data(buf);
    } finally {
        buf.release();
        this.equalsSeen = equalsSeen;
        this.firstCharacter = firstCharacter;
    }
}
 
Example 19
Source File: MultipartParser.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(final PartHandler handler, final ByteBuf rawData) throws IOException {
    handler.data(rawData);
    rawData.clear();
}
 
Example 20
Source File: ProtostuffSerializerTest.java    From turbo-rpc with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws IOException {
	ProtostuffSerializer serializer = new ProtostuffSerializer();

	UserService userService = new UserServiceServerImpl();

	ByteBufAllocator allocator = new UnpooledByteBufAllocator(true);
	ByteBuf byteBuf = allocator.directBuffer(16, 1024 * 1024 * 8);

	Request request = new Request();
	request.setRequestId(123);
	request.setServiceId(8);
	//request.setParams(new Object[] { Integer.valueOf(1), LocalDate.now(), userService.getUser(999).join() });

	serializer.writeRequest(byteBuf, request);

	byteBuf.readerIndex(4);
	System.out.println(serializer.readRequest(byteBuf));

	byteBuf.clear();

	Response response = new Response();
	response.setRequestId(321);
	response.setStatusCode((byte) 1);
	response.setResult(userService.listUser(0).join());

	serializer.writeResponse(byteBuf, response);

	byteBuf.readerIndex(4);
	System.out.println(serializer.readResponse(byteBuf));

}