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

The following examples show how to use io.netty.buffer.ByteBuf#array() . 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: Xtea.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public byte[] encrypt(byte[] data, int len)
{
	ByteBuf buf = Unpooled.wrappedBuffer(data, 0, len);
	ByteBuf out = Unpooled.buffer(len);
	int numBlocks = len / 8;
	for (int block = 0; block < numBlocks; ++block)
	{
		int v0 = buf.readInt();
		int v1 = buf.readInt();
		int sum = 0;
		for (int i = 0; i < ROUNDS; ++i)
		{
			v0 += (((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum + key[sum & 3]);
			sum += GOLDEN_RATIO;
			v1 += (((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum + key[(sum >>> 11) & 3]);
		}
		out.writeInt(v0);
		out.writeInt(v1);
	}
	out.writeBytes(buf);
	return out.array();
}
 
Example 2
Source File: MappedFile.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Writes a sequence of bytes to this file from the given buffer.
 * <p>
 * <p> Bytes are written starting at this file's current position,
 */
public void write(ByteBuf src, int srcStart, int srcLength) throws IOException {
   final int nextPosition = this.position + srcLength;
   checkCapacity(nextPosition);
   final long destAddress = this.address + this.position;
   if (src.hasMemoryAddress()) {
      final long srcAddress = src.memoryAddress() + srcStart;
      PlatformDependent.copyMemory(srcAddress, destAddress, srcLength);
   } else if (src.hasArray()) {
      final byte[] srcArray = src.array();
      PlatformDependent.copyMemory(srcArray, srcStart, destAddress, srcLength);
   } else {
      throw new IllegalArgumentException("unsupported byte buffer");
   }
   rawMovePositionAndLength(nextPosition);
}
 
Example 3
Source File: CommonTest.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
private byte[] encodeMetadata2(Map<String, String> metadata) throws IOException {
    if (metadata.size() == 0) {
        return new byte[]{};
    }

    ByteBuf buffer = Unpooled.buffer(20);

    for (Map.Entry<String, String> entry : metadata.entrySet()) {
        String key = entry.getKey();
        byte[] keyBytes = key.getBytes("UTF-8");
        buffer.writeInt(keyBytes.length);
        buffer.writeBytes(keyBytes);

        String v = entry.getValue();
        if (null == v) {
            v = "null";
        }
        byte[] vBytes = v.getBytes("UTF-8");
        buffer.writeInt(vBytes.length);
        buffer.writeBytes(vBytes);
    }


    return buffer.array();
}
 
Example 4
Source File: Xtea.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public byte[] decrypt(byte[] data, int len)
{
	ByteBuf buf = Unpooled.wrappedBuffer(data, 0, len);
	ByteBuf out = Unpooled.buffer(len);
	int numBlocks = len / 8;
	for (int block = 0; block < numBlocks; ++block)
	{
		int v0 = buf.readInt();
		int v1 = buf.readInt();
		int sum = GOLDEN_RATIO * ROUNDS;
		for (int i = 0; i < ROUNDS; ++i)
		{
			v1 -= (((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum + key[(sum >>> 11) & 3]);
			sum -= GOLDEN_RATIO;
			v0 -= (((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum + key[sum & 3]);
		}
		out.writeInt(v0);
		out.writeInt(v1);
	}
	out.writeBytes(buf);
	return out.array();
}
 
Example 5
Source File: CodecTest.java    From krpc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] bb = new byte[] {1,2,3};
        ByteBuf b = Unpooled.wrappedBuffer(bb);
        byte[] bb2 = b.array();
        System.out.println(b.writerIndex());
        System.out.println(b.readerIndex());
        ByteBuf b2 = Unpooled.copiedBuffer(b);
        b.readerIndex(1);
        bb[0] = 4;
        System.out.println(b.writerIndex());
        System.out.println(b.readerIndex());
        System.out.println(b2.writerIndex());
        System.out.println(b2.readerIndex());

    }
 
Example 6
Source File: NettyHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static String toString(ByteBuf byteBuf) {
    if (byteBuf == null) {
        return null;
    }
    byte[] bs;
    int readIndex = byteBuf.readerIndex();
    if (byteBuf.hasArray()) {
        bs = byteBuf.array();
    } else {
        bs = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bs);
    }
    // 恢复Index
    byteBuf.readerIndex(readIndex);
    return new String(bs, RpcConstants.DEFAULT_CHARSET);
}
 
Example 7
Source File: SpdyHeaderBlockJZlibEncoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private void setInput(ByteBuf decompressed) {
    int len = decompressed.readableBytes();

    byte[] in;
    int offset;
    if (decompressed.hasArray()) {
        in = decompressed.array();
        offset = decompressed.arrayOffset() + decompressed.readerIndex();
    } else {
        in = new byte[len];
        decompressed.getBytes(decompressed.readerIndex(), in);
        offset = 0;
    }
    z.next_in = in;
    z.next_in_index = offset;
    z.avail_in = len;
}
 
Example 8
Source File: ByteBufUtils.java    From Distributed-KV with Apache License 2.0 5 votes vote down vote up
/**
 * ByteBuf内容生成字符串
 * @param buf
 * @return
 */
public static String buf2Str(ByteBuf buf) {
    String str;
    // 处理堆缓冲区
    if(buf.hasArray()) {
        str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
    } else { 
    	// 处理直接缓冲区以及复合缓冲区
        byte[] bytes = new byte[buf.readableBytes()];
        buf.getBytes(buf.readerIndex(), bytes);
        str = new String(bytes, 0, buf.readableBytes());
    }
    return str;
}
 
Example 9
Source File: FileEventUtils.java    From mewbase with MIT License 5 votes vote down vote up
static byte[] eventToByteArray(final BsonObject event) {
    ByteBuf headedBuf = Unpooled.buffer();
    final byte [] bytes = BsonCodec.bsonObjectToBsonBytes(event);
    headedBuf.writeLong(Instant.now().toEpochMilli());
    headedBuf.writeLong(EventUtils.checksum(bytes));
    headedBuf.writeBytes(bytes);
    return headedBuf.array();
}
 
Example 10
Source File: TracingPropagationTest.java    From tchannel-java with MIT License 5 votes vote down vote up
@Override
public ThriftResponse<Example> handleImpl(ThriftRequest<Example> request) {
    String encodings = request.getBody(Example.class).getAString();
    TraceResponse response = observeSpanAndDownstream(encodings, request.getTrace());
    ByteBuf bytes = new JSONSerializer().encodeBody(response);
    Example thriftResponse = new Example(new String(bytes.array(), StandardCharsets.UTF_8), 0);
    bytes.release();
    return new ThriftResponse.Builder<Example>(request)
            .setTransportHeaders(request.getTransportHeaders())
            .setBody(thriftResponse)
            .build();
}
 
Example 11
Source File: CommandToBinaryByteBuf.java    From SynchronizeFX with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf msg, final List<Object> out) throws Exception {
    byte[] data;
    if (msg.hasArray()) {
        data = msg.array();
    } else {
        data = new byte[msg.readableBytes()];
        msg.readBytes(data);
    }

    out.add(serializer.deserialize(data));
}
 
Example 12
Source File: HttpClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private DefaultFullHttpRequest makeHttpMessage(String host, OneM2mRequest reqMessage) throws Exception {
	
	DefaultFullHttpRequest request = HttpRequestCodec.encode(reqMessage, HttpVersion.HTTP_1_1);
	request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
	request.headers().add(HttpHeaders.Names.HOST, host);
	
	//print log
	StringBuilder strBld = new StringBuilder();
	
	strBld.append("\n");
	strBld.append("######################## Client Request log  ###########################\n");
	strBld.append("== Make Request Message: ").append("\n");
	strBld.append("VERSION: ").append(request.getProtocolVersion()).append("\n");
	strBld.append("METHOD: ").append(request.getMethod()).append("\n");
	strBld.append("URI: ").append(request.getUri()).append("\n");
	
	for (Entry<String, String> entry : request.headers()) {
		strBld.append("HEADER: ").append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
	}
	
	if (request.content() != null) {
		if (request.content().isReadable()) {
			ByteBuf copyBuf = request.content().copy();
			String contentString = "CONTENTS: \n" + new String(copyBuf.array(), CharsetUtil.UTF_8);
			strBld.append(contentString).append("\n");
			copyBuf.release();
		}
	}
	log.debug(strBld.toString());
	
	return request;
}
 
Example 13
Source File: Http2ClearTextBadRequestTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void receiveHttpResponse(FullHttpResponse response) {
    this.response = response;
    if (response != null) {
        ByteBuf byteBuf = response.content();
        if (byteBuf.hasArray()) {
            content = byteBuf.array();
        } else {
            content = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(content);
        }
    }
    latch.countDown();
}
 
Example 14
Source File: VertxUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static byte[] getBytesFast(ByteBuf byteBuf) {
  if (byteBuf.hasArray()) {
    return byteBuf.array();
  }

  byte[] arr = new byte[byteBuf.writerIndex()];
  byteBuf.getBytes(0, arr);
  return arr;
}
 
Example 15
Source File: FrameDecoder.java    From nemo with Apache License 2.0 5 votes vote down vote up
/**
 * Try to emit the body of the control frame.
 *
 * @param in  the {@link ByteBuf} from which to read data
 * @param out the list to which the body of the control frame is added
 * @return {@code true} if the control frame body was emitted, {@code false} otherwise
 * @throws InvalidProtocolBufferException when failed to parse
 */
private boolean onControlBodyAdded(final ByteBuf in, final List out)
    throws InvalidProtocolBufferException {
  assert (controlBodyBytesToRead > 0);
  assert (dataBodyBytesToRead == 0);
  assert (inputContext == null);

  assert (controlBodyBytesToRead <= Integer.MAX_VALUE);

  if (in.readableBytes() < controlBodyBytesToRead) {
    // cannot read body now
    return false;
  }

  final byte[] bytes;
  final int offset;
  if (in.hasArray()) {
    bytes = in.array();
    offset = in.arrayOffset() + in.readerIndex();
  } else {
    bytes = new byte[(int) controlBodyBytesToRead];
    in.getBytes(in.readerIndex(), bytes, 0, (int) controlBodyBytesToRead);
    offset = 0;
  }
  final ByteTransferContextSetupMessage controlMessage
      = ByteTransferContextSetupMessage.PARSER.parseFrom(bytes, offset, (int) controlBodyBytesToRead);

  out.add(controlMessage);
  in.skipBytes((int) controlBodyBytesToRead);
  controlBodyBytesToRead = 0;
  return true;
}
 
Example 16
Source File: MessageIdImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
protected byte[] toByteArray(int batchIndex) {
    MessageIdData.Builder builder = MessageIdData.newBuilder();
    builder.setLedgerId(ledgerId);
    builder.setEntryId(entryId);
    if (partitionIndex >= 0) {
        builder.setPartition(partitionIndex);
    }

    if (batchIndex != -1) {
        builder.setBatchIndex(batchIndex);
    }

    MessageIdData msgId = builder.build();
    int size = msgId.getSerializedSize();
    ByteBuf serialized = Unpooled.buffer(size, size);
    ByteBufCodedOutputStream stream = ByteBufCodedOutputStream.get(serialized);
    try {
        msgId.writeTo(stream);
    } catch (IOException e) {
        // This is in-memory serialization, should not fail
        throw new RuntimeException(e);
    }

    msgId.recycle();
    builder.recycle();
    stream.recycle();
    return serialized.array();
}
 
Example 17
Source File: HttpClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private DefaultFullHttpRequest makeHttpMessage(String host, OneM2mRequest reqMessage) throws Exception {
	
	DefaultFullHttpRequest request = HttpRequestCodec.encode(reqMessage, HttpVersion.HTTP_1_1);
	request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
	request.headers().add(HttpHeaders.Names.HOST, host);
	
	//print log
	StringBuilder strBld = new StringBuilder();
	
	strBld.append("\n");
	strBld.append("######################## Client Request log  ###########################\n");
	strBld.append("== Make Request Message: ").append("\n");
	strBld.append("VERSION: ").append(request.getProtocolVersion()).append("\n");
	strBld.append("METHOD: ").append(request.getMethod()).append("\n");
	strBld.append("URI: ").append(request.getUri()).append("\n");
	
	for (Entry<String, String> entry : request.headers()) {
		strBld.append("HEADER: ").append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
	}
	
	if (request.content() != null) {
		if (request.content().isReadable()) {
			ByteBuf copyBuf = request.content().copy();
			String contentString = "CONTENTS: \n" + new String(copyBuf.array(), CharsetUtil.UTF_8);
			strBld.append(contentString).append("\n");
			copyBuf.release();
		}
	}
	log.debug(strBld.toString());
	
	return request;
}
 
Example 18
Source File: StrictBGPPeerRegistry.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
private static byte[] serializeAs4BytesCapability(final As4BytesCapability as4Capability) {
    final ByteBuf buffer = Unpooled.buffer(1 /*CODE*/ + 1 /*LENGTH*/ + Integer.BYTES /*4 byte value*/);
    final As4CapabilityHandler serializer = new As4CapabilityHandler();
    serializer.serializeCapability(new CParametersBuilder().setAs4BytesCapability(as4Capability).build(), buffer);
    return buffer.array();
}
 
Example 19
Source File: JdkZlibEncoder.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf uncompressed, ByteBuf out) throws Exception {
    if (finished) {
        out.writeBytes(uncompressed);
        return;
    }

    int len = uncompressed.readableBytes();
    if (len == 0) {
        return;
    }

    int offset;
    byte[] inAry;
    if (uncompressed.hasArray()) {
        // if it is backed by an array we not need to to do a copy at all
        inAry = uncompressed.array();
        offset = uncompressed.arrayOffset() + uncompressed.readerIndex();
        // skip all bytes as we will consume all of them
        uncompressed.skipBytes(len);
    } else {
        inAry = new byte[len];
        uncompressed.readBytes(inAry);
        offset = 0;
    }

    if (writeHeader) {
        writeHeader = false;
        if (wrapper == ZlibWrapper.GZIP) {
            out.writeBytes(gzipHeader);
        }
    }

    if (wrapper == ZlibWrapper.GZIP) {
        crc.update(inAry, offset, len);
    }

    deflater.setInput(inAry, offset, len);
    while (!deflater.needsInput()) {
        deflate(out);
    }
}
 
Example 20
Source File: JoinGroupCodec.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
@Override
public JoinGroupRequest decode(KafkaHeader header, ByteBuf buffer) throws Exception {
    JoinGroupRequest request = new JoinGroupRequest();
    List<JoinGroupRequest.ProtocolMetadata> groupProtocols = null;

    request.setGroupId(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    request.setSessionTimeout(buffer.readInt());

    if (header.getVersion() >= 1) {
        request.setRebalanceTimeout(buffer.readInt());
    }

    String memberId = StringUtils.defaultString(Serializer.readString(buffer, Serializer.SHORT_SIZE), StringUtils.EMPTY);
    request.setMemberId(memberId);
    request.setProtocolType(Serializer.readString(buffer, Serializer.SHORT_SIZE));

    int size = buffer.readInt();

    if (size > 0) {
        groupProtocols = Lists.newLinkedList();
    }
    for (int i = 0; i < size; i++) {
        String groupName = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int length = buffer.readInt();
        ByteBuf byteBuf = buffer.readBytes(length);
        byte[] bytes;
        if (byteBuf.hasArray()) {
            bytes = byteBuf.array();
        } else {
            bytes = new byte[length];
            byteBuf.getBytes(byteBuf.readerIndex(), bytes);
        }
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        byteBuffer.rewind();
        JoinGroupRequest.ProtocolMetadata protocolMetadata = new JoinGroupRequest.ProtocolMetadata(groupName, byteBuffer);
        groupProtocols.add(protocolMetadata);
    }

    request.setGroupProtocols(groupProtocols);
    return request;
}