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

The following are Jave code examples for showing how to use getBytes() 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: simulacron   File: ByteBufCodec.java   Source Code and License Vote up 6 votes
@Override
public ByteBuffer readBytes(ByteBuf source) {
  int len = readInt(source);
  if (len < 0) {
    return null;
  }

  ByteBuf slice = source.readSlice(len);
  // if direct byte buffer, return underlying nioBuffer.
  if (slice.isDirect()) {
    return slice.nioBuffer();
  }
  // otherwise copy to a byte array and wrap it.
  final byte[] out = new byte[slice.readableBytes()];
  source.getBytes(source.readerIndex(), out, 0, len);
  return ByteBuffer.wrap(out);
}
 
Example 2
Project: netto_rpc   File: NettoMessageDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, NettoFrame msg, List<Object> out) throws Exception {
    ByteBuf headerContent = msg.getHeaderContent();
    byte[] headerBytesBuf = new byte[msg.getHeaderContentSize()];
    headerContent.getBytes(headerContent.readerIndex(), headerBytesBuf);
    NettoMessage message = new NettoMessage();
    ByteBuf body = msg.getBody();
    byte[] bodyBytesBuf = new byte[msg.getBodySize()];        
    body.getBytes(body.readerIndex(), bodyBytesBuf);
    
    Map<String,String> headers = this.decoderHeader(new String(headerBytesBuf));

    message.setBody(bodyBytesBuf);
    message.setHeaders(headers);
    out.add(message);
    
    
}
 
Example 3
Project: netty-socks   File: SSocksAddressEncoder.java   Source Code and License Vote up 6 votes
public ByteBuf encode(ByteBufAllocator allocator, SocksCmdRequest msg) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("encode target address");
    }

    ByteBuf buf = allocator.directBuffer();
    msg.encodeAsByteBuf(buf);
    buf.skipBytes(3);

    if (LOG.isTraceEnabled()) {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.getBytes(buf.readerIndex(), bytes);
    }

    return buf;
}
 
Example 4
Project: wecard-server   File: ProtobufDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    final byte[] array;
    final int offset;
    final int length = msg.readableBytes();
    if (msg.hasArray()) {
        array = msg.array();
        offset = msg.arrayOffset() + msg.readerIndex();
    } else {
        array = new byte[length];
        msg.getBytes(msg.readerIndex(), array, 0, length);
        offset = 0;
    }

    if (extensionRegistry == null) {
        if (HAS_PARSER) {
            out.add(prototype.getParserForType().parseFrom(array, offset, length));
        } else {
            out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build());
        }
    } else {
        if (HAS_PARSER) {
            out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry));
        } else {
            out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build());
        }
    }
}
 
Example 5
Project: push   File: MsgPackDecode.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
	final int length = msg.readableBytes();
	final byte[] array = new byte[length];
	msg.getBytes(msg.readerIndex(), array, 0, length);
	out.add(new MessagePack().read(array, Packet.class));
}
 
Example 6
Project: NioSmtpClient   File: DotStuffingTest.java   Source Code and License Vote up 5 votes
private String dotStuffUsingByteBuf(String testString, boolean atStartOfLine, boolean appendCRLF) {
  ByteBuf sourceBuffer = ALLOCATOR.buffer();
  sourceBuffer.writeBytes(testString.getBytes(StandardCharsets.UTF_8));

  byte[] previousBytes = atStartOfLine ? null : new byte[] { 'x', 'y' };
  ByteBuf destBuffer = DotStuffing.createDotStuffedBuffer(ALLOCATOR, sourceBuffer, previousBytes,
      appendCRLF ? MessageTermination.ADD_CRLF : MessageTermination.DO_NOT_TERMINATE);

  byte[] bytes = new byte[destBuffer.readableBytes()];
  destBuffer.getBytes(0, bytes);
  return new String(bytes, CharsetUtil.UTF_8);
}
 
Example 7
Project: AgentX   File: Tcp2UdpHandler.java   Source Code and License Vote up 5 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    Channel udpChannel = XChannelMapper.getUdpChannel(udpSource);
    if (udpChannel == null) {
        log.warn("Bad Connection! (udp channel closed)");
        XChannelMapper.closeChannelGracefullyByTcpChannel(ctx.channel());
    } else if (udpChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                bytes = wrapper.unwrap(bytes);
                XRequest request = requestResolver.parse(bytes);
                String host = request.getHost();
                int port = request.getPort();
                byte[] content = Arrays.copyOfRange(bytes, bytes.length - request.getSubsequentDataLength(), bytes.length);
                log.info("\t          Proxy << Target \tFrom   {}:{}", host, port);

                // redirect tcp -> udp
                udpChannel.writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer(content), udpSource, new InetSocketAddress(host, port)));
                log.info("\tClient << Proxy           \tGet [{} bytes]", content.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 8
Project: NettyStudy   File: ByteBufExamples.java   Source Code and License Vote up 5 votes
/**
 * Listing 5.2
 */
public static void directBuffer(ByteBuf directBuf) {
    if (!directBuf.hasArray()) {
        int length = directBuf.readableBytes();
        byte[] array = new byte[length];
        directBuf.getBytes(directBuf.readerIndex(), array);
        handleArray(array, 0, length);
    }

}
 
Example 9
Project: nearenough   File: RtMessage.java   Source Code and License Vote up 5 votes
private Map<RtTag, byte[]> extractMultiMapping(ByteBuf msg) {
  // extractOffsets will leave the reader index positioned at the first tag
  int[] offsets = extractOffsets(msg);

  int startOfValues = msg.readerIndex() + (4 * numTags);
  Map<RtTag, byte[]> mapping = new LinkedHashMap<>(numTags);
  RtTag prevTag = null;

  for (int i = 0; i < offsets.length; i++) {
    long uintCurrTag = msg.readUnsignedInt();
    RtTag currTag = RtTag.fromUnsignedInt((int) uintCurrTag);

    if ((prevTag != null) && currTag.isLessThan(prevTag)) {
      String exMsg = String.format(
          "tags not strictly increasing: current '%s' (0x%08x), previous '%s' (0x%08x)",
          currTag, currTag.valueLE(), prevTag, prevTag.valueLE()
      );
      throw new TagsNotIncreasingException(exMsg);
    }

    int valueIdx = startOfValues + offsets[i];
    int valueLen = ((i + 1) == offsets.length) ? msg.readableBytes() - offsets[i]
                                               : offsets[i + 1] - offsets[i];
    byte[] valueBytes = new byte[valueLen];
    msg.getBytes(valueIdx, valueBytes);

    mapping.put(currTag, valueBytes);
    prevTag = currTag;
  }

  return mapping;
}
 
Example 10
Project: xitk   File: AbstractHttpServlet.java   Source Code and License Vote up 5 votes
protected static byte[] readContent(FullHttpRequest request) {
    ByteBuf buf = request.content();
    if (buf == null) {
        return null;
    }
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);
    return bytes;
}
 
Example 11
Project: dremio-oss   File: SpoolingRawBatchBuffer.java   Source Code and License Vote up 5 votes
public void writeToStream(FSDataOutputStream stream) throws IOException {
  Stopwatch watch = Stopwatch.createStarted();
  ByteBuf buf = null;
  try {
    check = ThreadLocalRandom.current().nextLong();
    start = stream.getPos();
    logger.debug("Writing check value {} at position {}", check, start);
    stream.writeLong(check);
    batch.getHeader().writeDelimitedTo(stream);
    buf = batch.getBody();
    if (buf != null) {
      bodyLength = buf.capacity();
    } else {
      bodyLength = 0;
    }
    if (bodyLength > 0) {
      buf.getBytes(0, stream, bodyLength);
    }
    stream.hsync();
    FileStatus status = spillFile.getFileStatus();
    long len = status.getLen();
    logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
    long t = watch.elapsed(TimeUnit.MICROSECONDS);
    logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
  } finally {
    // even if the try block throws an exception we still want to send an ACK and release the lock
    // the caller will add the exception to deferred attribute and it will be thrown when the poll() method is called
    try {
      batch.sendOk(); // this can also throw an exception
    } finally {
      state = BatchState.SPILLED;
      batch = null;
      if (buf != null) {
        buf.release();
      }
    }
  }
}
 
Example 12
Project: elegant-springboot   File: MsgEncoder.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, OutboundMsg msg, ByteBuf out) throws Exception {


    byte type = msg.getType();
    byte opt = msg.getOpt();
    String msgStr = msg.getMsgStr();
    byte[] data = msg.getData();

    byte[] msgBytes = msgStr.getBytes(Charset.forName("utf-8"));

    // 文本消息长度
    int msgLength = msgBytes.length;
    // 二进制数据长度
    int dataLength = data == null ? 0 : data.length;

    // 总消息长度
    int allDataLength = msgLength + dataLength + OTHER_INFO_LENGTH;

    out.writeBytes(OutboundMsg.getHEADER());//输出头部标识
    out.writeInt(allDataLength);//其后所有的数据长度(字节)
    out.writeByte(type);//数据类型
    out.writeByte(opt);//操作类型
    out.writeInt(msgLength);//信息数据长度(字节)
    out.writeBytes(msgBytes);//信息字符串内容(已加密,字节)
    if (data != null) {
        out.writeBytes(data);//二进制数据
    }
    byte[] bytesToCheck = new byte[allDataLength - 1];
    out.getBytes(7, bytesToCheck);
    byte check = calculate(bytesToCheck);
    out.writeByte(check);//冗余校验值
}
 
Example 13
Project: LibraSock   File: LibraMessage.java   Source Code and License Vote up 5 votes
/**
 * 解码
 * 
 * @param in
 * @return
 * @throws Exception
 */
public static LibraMessage decode(ByteBuf in) throws Exception {
	LibraMessage message = new LibraMessage();
	message.setHead(LibraHead.decode(in));
	short bodyLength = in.readShort();// 消息体的长度
	if (bodyLength != in.readableBytes()) {
		LibraLog.error("LibraMessage.decode is error! params:bodyLength:" + bodyLength + "\treadableLength:" + in.readableBytes());
		return null;
	}
	ByteBuf bodyByteBuf = in.readBytes(in.readableBytes());
	byte[] array;
	// 反序列化数据的起始点
	int offset;
	// 可读的数据字节长度
	int readableLen = bodyByteBuf.readableBytes();
	// 分为包含数组数据和不包含数组数据两种形式
	if (bodyByteBuf.hasArray()) {
		array = bodyByteBuf.array();
		offset = bodyByteBuf.arrayOffset() + bodyByteBuf.readerIndex();
	} else {
		array = new byte[readableLen];
		bodyByteBuf.getBytes(bodyByteBuf.readerIndex(), array, 0, readableLen);
		offset = 0;
	}
	// 反序列化
	message.setBody(decodeBody(message.getHead().getProtocolID(), array, offset, readableLen));
	return message;
}
 
Example 14
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 15
Project: NioSmtpClient   File: ByteBufMessageContentTest.java   Source Code and License Vote up 5 votes
private String extract(Object o) {
  assertThat(o).isInstanceOf(ByteBuf.class);

  ByteBuf buffer = (ByteBuf) o;

  byte[] bytes = new byte[buffer.readableBytes()];
  buffer.getBytes(0, bytes);
  return new String(bytes, CharsetUtil.UTF_8);
}
 
Example 16
Project: Proyecto-DASI   File: RewardForItemBase.java   Source Code and License Vote up 5 votes
protected static void sendItemStackToClient(EntityPlayerMP player, MalmoMessageType message, ItemStack is)
{
    ByteBuf buf = Unpooled.buffer();
    ByteBufUtils.writeItemStack(buf, is);
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(0, bytes);
    String data = DatatypeConverter.printBase64Binary(bytes);
    MalmoMod.MalmoMessage msg = new MalmoMod.MalmoMessage(message, data);
    MalmoMod.network.sendTo(msg, player);
}
 
Example 17
Project: aws-sdk-java-v2   File: ResponseHandler.java   Source Code and License Vote up 4 votes
private static ByteBuffer copyToByteBuffer(ByteBuf byteBuf) {
    ByteBuffer bb = ByteBuffer.allocate(byteBuf.readableBytes());
    byteBuf.getBytes(byteBuf.readerIndex(), bb);
    bb.flip();
    return bb;
}
 
Example 18
Project: netto_rpc   File: NettoFrameDecoder.java   Source Code and License Vote up 4 votes
@SuppressWarnings("unused")
@Override
   protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
       // 1.判断in.readerIndex
       int idx = in.readerIndex();
       int wrtIdx = in.writerIndex();

       if (wrtIdx > maxRequestSize) {
           // buffer size exceeded maxObjectLength; discarding the complete
           // buffer.
           in.skipBytes(in.readableBytes());
           throw new TooLongFrameException(
                   "object length exceeds " + maxRequestSize + ": " + wrtIdx + " bytes discarded");
       }

       for (; idx < wrtIdx; idx++) {
           byte c = in.getByte(idx);
           if (Character.isWhitespace(c)) {
               in.skipBytes(1);
           } else {
               break;
           }
       }

       if (in.readableBytes() >= NettoFrame.HEADER_LENGTH) {
           byte[] headerInfo = new byte[NettoFrame.HEADER_LENGTH];
           Arrays.fill(headerInfo, (byte) ' ');

           in.getBytes(in.readerIndex(), headerInfo);
           String headerStr = new String(headerInfo, "UTF-8");
           if (headerStr.startsWith(NettoFrame.NETTO_HEADER_START)) {

               try {
                   String headerInfoContent = headerStr.substring(NettoFrame.NETTO_HEADER_START.length());
                   String[] headerSections = headerInfoContent.split("/");
                   if (headerSections.length == 3) {
                       String version = headerSections[0];
                       String headerContentSizeAsString = headerSections[1].trim();
                       String bodySizeAsString = headerSections[2].trim();
                       int headerContentSize = Integer.parseInt(headerContentSizeAsString);
                       int bodySize = Integer.parseInt(bodySizeAsString);
                       if (in.readableBytes() >= bodySize + headerContentSize + NettoFrame.HEADER_LENGTH) {
                           ByteBuf headerContent = in.retainedSlice(NettoFrame.HEADER_LENGTH, headerContentSize);
                           ByteBuf body = in.retainedSlice(NettoFrame.HEADER_LENGTH + headerContentSize, bodySize);
                           NettoFrame nettoMessage = new NettoFrame();
                           nettoMessage.setBodySize(bodySize);
                           nettoMessage.setBody(body);
                           nettoMessage.setHeaderContent(headerContent);
                           nettoMessage.setHeaderContentSize(headerContentSize);
                           out.add(nettoMessage);
                           in.readerIndex(NettoFrame.HEADER_LENGTH + headerContentSize + bodySize);
                       }
                   } else {
                       in.skipBytes(in.readableBytes());
                       throw new NettoDecoderException("header parse error:" + headerStr);
                   }
               } catch (Throwable t) {
                   logger.error("decode error:"+headerStr,t);
                   in.skipBytes(in.readableBytes());
                   throw new NettoDecoderException("decode error:" + headerStr);
                   
               }

           } else {

               in.skipBytes(in.readableBytes());
               throw new NettoDecoderException("header start error:" + headerStr);
           }

       }

   }
 
Example 19
Project: elegant-springboot   File: MsgDecoder.java   Source Code and License Vote up 4 votes
@Override
protected InboundMsg decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    //数据还不可读
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }
    //全部数据已准备完毕,长度正确性已校验

    //解析数据头
    byte[] readHeader = new byte[LENGTH_FIELD_OFFSET];
    frame.readBytes(LENGTH_FIELD_OFFSET).readBytes(readHeader);
    //数据头有误
    if (!Arrays.equals(readHeader, InboundMsg.getHEADER())) {
        logger.debug("数据头有误");
        throw new IllegalArgumentException("数据头有误");
    }
    //数据长度部分
    int len = frame.readInt();
    //待校验信息
    byte[] data2check = new byte[len - 1];
    frame.getBytes(LENGTH_FIELD_OFFSET + LENGTH_FIELD_LENGTH,
            data2check, 0, len - 1);
    //解析数据体
    //消息类型
    byte type = frame.readByte();
    //操作类型
    byte opt = frame.readByte();
    //文本消息长度
    int msgLen = frame.readableBytes() - 1;
    //文本消息
    byte[] msg = new byte[msgLen];
    frame.readBytes(msgLen).readBytes(msg);
    //校验位
    byte check = frame.readByte();

    //冗余校验
    byte calValue = calculate(data2check);
    if (calValue != check){
        logger.debug("校验值不匹配");
        throw new IllegalArgumentException("校验值不匹配");
    }

    String msgStr = new String(msg, Charset.forName("utf-8"));
    return new InboundMsg(type, opt, msgStr);
}
 
Example 20
Project: L2J-Global   File: Crypt.java   Source Code and License Vote up 4 votes
private void onPacketSent(ByteBuf buf)
{
	final byte[] data = new byte[buf.writerIndex()];
	buf.getBytes(0, data);
	EventDispatcher.getInstance().notifyEvent(new OnPacketSent(_client, data));
}