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

The following examples show how to use io.netty.buffer.ByteBuf#readCharSequence() . 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: AuthMetadataCodec.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
/**
 * Read up to 129 bytes from the given metadata in order to get the custom Auth Type
 *
 * @param metadata
 * @return
 */
public static CharSequence readCustomAuthType(ByteBuf metadata) {
  if (metadata.readableBytes() < 2) {
    throw new IllegalStateException(
        "Unable to decode custom Auth type. Not enough readable bytes");
  }

  byte encodedLength = metadata.readByte();
  if (encodedLength < 0) {
    throw new IllegalStateException(
        "Unable to decode custom Auth type. Incorrect auth type length");
  }

  // encoded length is realLength - 1 in order to avoid intersection with 0x00 authtype
  int realLength = encodedLength + 1;
  if (metadata.readableBytes() < realLength) {
    throw new IllegalArgumentException(
        "Unable to decode custom Auth type. Malformed length or auth type string");
  }

  return metadata.readCharSequence(realLength, CharsetUtil.US_ASCII);
}
 
Example 2
Source File: AmqpDecoder.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
private void processProtocolInitFrame(ByteBuf buffer, List<Object> out) {
    if (buffer.readableBytes() >= 8) {
        CharSequence protocolName = buffer.readCharSequence(4, CharsetUtil.US_ASCII);
        buffer.skipBytes(1);
        byte majorVersion = buffer.readByte();
        byte minorVersion = buffer.readByte();
        byte revision = buffer.readByte();

        if (!AMQP_PROTOCOL_IDENTIFIER.equals(protocolName)) {
            out.add(new AmqpBadMessage(new IllegalArgumentException("Unknown protocol name " +
                                                                           protocolName.toString())));
            currentState = State.BAD_MESSAGE;
        }

        out.add(new ProtocolInitFrame(majorVersion, minorVersion, revision));
    }
}
 
Example 3
Source File: DapDecoder.java    From karate with MIT License 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (remaining > 0 && in.readableBytes() >= remaining) {
        out.add(encode(in, remaining));
        remaining = 0;
    }
    int pos;
    while ((pos = findCrLfCrLf(in)) != -1) {
        int delimiterPos = pos;
        while (in.getByte(--pos) != ':') {
            // skip backwards
        }
        in.readerIndex(++pos);
        CharSequence lengthString = in.readCharSequence(delimiterPos - pos, FileUtils.UTF8);
        int length = Integer.valueOf(lengthString.toString().trim());
        in.readerIndex(delimiterPos + 4);
        if (in.readableBytes() >= length) {
            out.add(encode(in, length));
            remaining = 0;
        } else {
            remaining = length;
        }
    }
}
 
Example 4
Source File: TcpTest.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public int onTcpRecvMsg(int requestId, DFTcpChannel channel, Object m) {
	ByteBuf msg = (ByteBuf) m;
	final int msgLen = msg.readableBytes();
	final String str = (String) msg.readCharSequence(msgLen, Charset.forName("utf-8"));
	log.debug("recv msg from svr: "+str);
	
	return MSG_AUTO_RELEASE;
}
 
Example 5
Source File: ArmeriaClientCall.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
private static HttpHeaders parseGrpcWebTrailers(ByteBuf buf) {
    final HttpHeadersBuilder trailers = HttpHeaders.builder();
    while (buf.readableBytes() > 0) {
        int start = buf.forEachByte(ByteProcessor.FIND_NON_LINEAR_WHITESPACE);
        if (start == -1) {
            return null;
        }
        int endExclusive;
        if (buf.getByte(start) == ':') {
            // We need to skip the pseudoheader colon when searching for the separator.
            buf.skipBytes(1);
            endExclusive = buf.forEachByte(FIND_COLON);
            buf.readerIndex(start);
        } else {
            endExclusive = buf.forEachByte(FIND_COLON);
        }
        if (endExclusive == -1) {
            return null;
        }
        final CharSequence name = buf.readCharSequence(endExclusive - start, StandardCharsets.UTF_8);
        buf.readerIndex(endExclusive + 1);
        start = buf.forEachByte(ByteProcessor.FIND_NON_LINEAR_WHITESPACE);
        buf.readerIndex(start);
        endExclusive = buf.forEachByte(ByteProcessor.FIND_CRLF);
        final CharSequence value = buf.readCharSequence(endExclusive - start, StandardCharsets.UTF_8);
        trailers.add(name, value.toString());
        start = buf.forEachByte(ByteProcessor.FIND_NON_CRLF);
        if (start != -1) {
            buf.readerIndex(start);
        } else {
            // Nothing but CRLF remaining, we're done.
            buf.skipBytes(buf.readableBytes());
        }
    }
    return trailers.build();
}
 
Example 6
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> byteBufToMap(ByteBuf byteBuf) {
  Map<String, String> map = new HashMap<>();

  while (byteBuf.readableBytes() > 0) {
    int keyLength = byteBuf.readShort();
    String key = (String) byteBuf.readCharSequence(keyLength, StandardCharsets.UTF_8);

    int valueLength = byteBuf.readShort();
    String value = (String) byteBuf.readCharSequence(valueLength, StandardCharsets.UTF_8);

    map.put(key, value);
  }

  return map;
}
 
Example 7
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> byteBufToMap(ByteBuf byteBuf) {
  Map<String, String> map = new HashMap<>();

  while (byteBuf.readableBytes() > 0) {
    int keyLength = byteBuf.readShort();
    String key = (String) byteBuf.readCharSequence(keyLength, StandardCharsets.UTF_8);

    int valueLength = byteBuf.readShort();
    String value = (String) byteBuf.readCharSequence(valueLength, StandardCharsets.UTF_8);

    map.put(key, value);
  }

  return map;
}
 
Example 8
Source File: TcpCustomDecAndEnc.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public int onTcpRecvMsg(int requestId, DFTcpChannel channel, Object m) {
	ByteBuf msg = (ByteBuf) m;
	final int msgLen = msg.readableBytes();
	final String str = (String) msg.readCharSequence(msgLen, Charset.forName("utf-8"));
	log.debug("recv msg from svr: "+str);
	
	return MSG_AUTO_RELEASE;
}
 
Example 9
Source File: ClientHandler.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
        ByteBuf buf =(ByteBuf)msg;
        CharSequence text = buf.readCharSequence(buf.readableBytes(),
                Charset.defaultCharset());
        System.out.println(text);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
 
Example 10
Source File: ClusterCustomMsg.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public int onDeserialize(ByteBuf buf) {
	this.id = buf.readInt();
	this.age = buf.readInt();
	if(buf.readableBytes() > 0){ //has more
		this.name = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
	}
	return 0;
}
 
Example 11
Source File: DFHttpSyncHandler.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	try{
		if(msg instanceof FullHttpResponse){
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			_recvData = dfRsp;
			if(!isString && buf != null){
       			buf.retain();
       		}
		}
	}finally{
		if(_recvPromise != null){
			_recvPromise.setSuccess();
		}
		ReferenceCountUtil.release(msg);
	}
}
 
Example 12
Source File: Kcp.java    From dfactor with MIT License 5 votes vote down vote up
public int onReceiveRaw(DatagramPacket pack){
	if(closed){
		pack.release();
		return 1;
	}
	_tmLastRecv = _tmNow;
	final ByteBuf buf = pack.content();
	final byte act = buf.readByte();
	if(act == ACT_ACK){  //ack packet
		_procAck(buf.readInt(), buf.readInt());
		pack.release();
	}else if(act == ACT_DATA){ //data packet
		final int packId = buf.readInt();
		if(packId < recvWndR){ //valid id
			if(!_recvWndPack(packId, pack)){	//pack duplicate	
				pack.release();
			}
			//send ack
			//flag(1byte) + connId(4byte) + act(1byte) + packId(4byte) + recvWndL(4byte) 
			final ByteBuf bufAck = PooledByteBufAllocator.DEFAULT.ioBuffer(14);
			bufAck.writeByte(FLAG).writeInt(_connId).writeByte(ACT_ACK)
				.writeInt(packId).writeInt(recvWndL);
			final DatagramPacket packAck = new DatagramPacket(bufAck, remoteAddr);
			listener.onOutput(packAck);  //notify logic new msg in
		}else{ //invalid pack id
			final ByteBuf bufTmp = pack.content();
			bufTmp.readLong();
			final String strTmp = (String) bufTmp.readCharSequence(bufTmp.readableBytes(), Charset.forName("utf-8"));
			System.out.println("Invalid packId="+packId+", recvWndR="+recvWndR
					+", data="+strTmp);
			pack.release();
		}
	}else{ //invalid pack
		pack.release();
	}
	return 0;
}
 
Example 13
Source File: SingletonClob.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
protected CharSequence convert(ByteBuf buf) {
    if (!buf.isReadable()) {
        return "";
    }

    return buf.readCharSequence(buf.readableBytes(), CharCollation.fromId(collationId, version).getCharset());
}
 
Example 14
Source File: MultiClob.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
protected CharSequence convert(ByteBuf buf) {
    if (!buf.isReadable()) {
        return "";
    }

    return buf.readCharSequence(buf.readableBytes(), CharCollation.fromId(collationId, version).getCharset());
}
 
Example 15
Source File: MessageMimeTypeMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public void load(ByteBuf byteBuf) {
    byte firstByte = byteBuf.readByte();
    if (firstByte < 0) {
        this.mimeTypeId = (byte) (firstByte & 0x7F);
        this.mimeType = WellKnownMimeType.fromIdentifier(mimeTypeId).getString();
    } else {
        byteBuf.readCharSequence(firstByte, StandardCharsets.US_ASCII);
    }
}
 
Example 16
Source File: MessageAcceptMimeTypesMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public void load(ByteBuf byteBuf) {
    this.byteBufLength = byteBuf.readableBytes();
    while (byteBuf.isReadable()) {
        byte firstByte = byteBuf.readByte();
        if (firstByte < 0) {
            byte mimeTypeId = (byte) (firstByte & 0x7F);
            this.mimeTypes.add(WellKnownMimeType.fromIdentifier(mimeTypeId).getString());
        } else {
            byteBuf.readCharSequence(firstByte, StandardCharsets.US_ASCII);
        }
    }
}
 
Example 17
Source File: SingletonClob.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
protected CharSequence convert(ByteBuf buf) {
    if (!buf.isReadable()) {
        return "";
    }

    return buf.readCharSequence(buf.readableBytes(), CharCollation.fromId(collationId, version).getCharset());
}
 
Example 18
Source File: DFHttpCliHandler.java    From dfactor with MIT License 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	hasRsp = true;
	try{
		if(msg instanceof FullHttpResponse){
			int actorId = 0;
			FullHttpResponse rsp = (FullHttpResponse) msg;
			HttpHeaders headers = rsp.headers();
			long contentLen = HttpUtil.getContentLength(rsp);
			String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
			//
			DFHttpCliRsp dfRsp = null;
			ByteBuf buf = rsp.content();
			//parse msg
			boolean isString = contentIsString(contentType);
			if(isString){  //String
				String str = null;
				if(buf != null){
					str = (String) buf.readCharSequence(buf.readableBytes(), CharsetUtil.UTF_8);
				}
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						null, str);
			}else{  //binary
				dfRsp = new DFHttpCliRspWrap(rsp.status().code(), headers,
						contentType, (int) contentLen, 
						buf, null);
			}
			//
			Object msgWrap = null;
			//decode
			if(decoder != null){
				Object tmp = decoder.onDecode(dfRsp);
				if(tmp != null){
           			msgWrap = tmp;
           		}
			}
			if(msgWrap == null){  //没有解码
           		msgWrap = dfRsp;
           		if(!isString && buf != null){
           			buf.retain();
           		}
           	}
			//检测分发
			if(dispatcher != null){
				actorId = dispatcher.onQueryMsgActorId(addrRemote.getPort(), addrRemote, msgWrap);
			}
			//
			if(actorId == 0){
            	actorId = actorIdDef;
            }
			//
			if(actorId != 0 && msgWrap != null){ //可以后续处理
				DFActorManager.get().send(requestId, actorId, 2, 
						DFActorDefine.SUBJECT_NET, 
						DFActorDefine.NET_TCP_MESSAGE,  
						msgWrap, true, session, actorId==actorIdDef?userHandler:null, false);
            }
		}
	}finally{
		ReferenceCountUtil.release(msg);
		ctx.close();
	}
}
 
Example 19
Source File: MSSQLDataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static CharSequence decodeVarchar(ByteBuf in) {
  int length = in.readUnsignedShortLE();
  return in.readCharSequence(length, StandardCharsets.UTF_8);
}
 
Example 20
Source File: CompositeMetadataCodec.java    From rsocket-java with Apache License 2.0 3 votes vote down vote up
/**
 * Decode a {@link CharSequence} custome mime type from a {@link ByteBuf}, assuming said buffer
 * properly contains such a mime type.
 *
 * <p>The buffer must at least have two readable bytes, which distinguishes it from the {@link
 * #decodeMimeIdFromMimeBuffer(ByteBuf) compressed id} case. The first byte is a size and the
 * remaining bytes must correspond to the {@link CharSequence}, encoded fully in US_ASCII. As a
 * result, the first byte can simply be skipped, and the remaining of the buffer be decoded to the
 * mime type.
 *
 * <p>If the mime header buffer is less than 2 bytes long, returns {@code null}.
 *
 * @param flyweightMimeBuffer the mime header {@link ByteBuf} that contains length + custom mime
 *     type
 * @return the decoded custom mime type, as a {@link CharSequence}, or null if the input is
 *     invalid
 * @see #decodeMimeIdFromMimeBuffer(ByteBuf)
 */
@Nullable
public static CharSequence decodeMimeTypeFromMimeBuffer(ByteBuf flyweightMimeBuffer) {
  if (flyweightMimeBuffer.readableBytes() < 2) {
    throw new IllegalStateException("unable to decode explicit MIME type");
  }
  // the encoded length is assumed to be kept at the start of the buffer
  // but also assumed to be irrelevant because the rest of the slice length
  // actually already matches _decoded_length
  flyweightMimeBuffer.skipBytes(1);
  int mimeStringLength = flyweightMimeBuffer.readableBytes();
  return flyweightMimeBuffer.readCharSequence(mimeStringLength, CharsetUtil.US_ASCII);
}