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

The following are Jave code examples for showing how to use hasArray() 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: AgentX   File: XRelayHandler.java   Source Code and License Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                } else {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                    }
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 2
Project: AgentX   File: XRelayHandler.java   Source Code and License Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                    }
                } else {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 3
Project: NSS   File: OutRelayHandler.java   Source Code and License Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	try {
		if (relayChannel.isActive()) {
			ByteBuf bytebuff = (ByteBuf) msg;
			if (!bytebuff.hasArray()) {
				int len = bytebuff.readableBytes();
				byte[] arr = new byte[len];
				bytebuff.getBytes(0, arr);
				connectHandler.sendRemote(arr, arr.length, relayChannel);
			}
		}
	} catch (Exception e) {
		logger.error("send data to remoteServer error",e);
	} finally {
		ReferenceCountUtil.release(msg);
	}
}
 
Example 4
Project: NSS   File: InRelayHandler.java   Source Code and License Vote up 6 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	try {
		if (relayChannel.isActive()) {
			logger.debug("get remote message" + relayChannel);
			ByteBuf bytebuff = (ByteBuf) msg;
			if (!bytebuff.hasArray()) {
				int len = bytebuff.readableBytes();
				byte[] arr = new byte[len];
				bytebuff.getBytes(0, arr);
				connectHandler.sendLocal(arr, arr.length, relayChannel);
			}
		}
	} catch (Exception e) {
		logger.error("receive remoteServer data error", e);
	} finally {
		ReferenceCountUtil.release(msg);
	}
}
 
Example 5
Project: spark_deep   File: SaslEncryption.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
  throws Exception {

  byte[] data;
  int offset;
  int length = msg.readableBytes();
  if (msg.hasArray()) {
    data = msg.array();
    offset = msg.arrayOffset();
    msg.skipBytes(length);
  } else {
    data = new byte[length];
    msg.readBytes(data);
    offset = 0;
  }

  out.add(Unpooled.wrappedBuffer(backend.unwrap(data, offset, length)));
}
 
Example 6
Project: sctalk   File: PduAttachData.java   Source Code and License Vote up 6 votes
public PduAttachData(ByteString bytes) {
    
    buffer.writeBytes(bytes.toByteArray());
    
    this.type = buffer.readInt();
    this.handle = buffer.readLong();
    this.serviceType = buffer.readInt();
    this.pduLength = buffer.readInt();
    ByteBuf buf = buffer.readBytes(this.pduLength);
    
    if (buf.hasArray()) {
        this.pdu = ByteString.copyFrom(buf.array());
    } else {
        byte[] content = new byte[buf.capacity()];
        buf.readBytes(content);
        this.pdu = ByteString.copyFrom(content);
    }
}
 
Example 7
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 8
Project: wecard-server   File: ProtobufDecoder.java   Source Code and License Vote up 5 votes
public Object decode(ByteBuf msg) 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;
    }

    return prototype.getParserForType().parseFrom(array, offset, length);
}
 
Example 9
Project: incubator-servicecomb-java-chassis   File: VertxUtils.java   Source Code and License Vote up 5 votes
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 10
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 11
Project: AgentX   File: Udp2TcpHandler.java   Source Code and License Vote up 5 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    DatagramPacket datagram = (DatagramPacket) msg;
    InetSocketAddress sender = datagram.sender();
    Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
    if (tcpChannel == null) {
        // udpSource not registered, actively discard this packet
        // without register, an udp channel cannot relate to any tcp channel, so remove the map
        XChannelMapper.removeUdpMapping(sender);
        log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
    } else if (tcpChannel.isActive()) {
        ByteBuf byteBuf = datagram.content();
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                log.info("\t          Proxy << Target \tFrom   {}:{}", sender.getHostString(), sender.getPort());

                // write udp payload via tcp channel
                tcpChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(requestResolver.wrap(XRequest.Channel.UDP, bytes))));
                log.info("\tClient << Proxy           \tGet [{} bytes]", bytes.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 12
Project: NSS   File: SocksServerConnectHandler.java   Source Code and License Vote up 5 votes
/**
 * localserver和remoteserver进行connect发送的数据
 * 
 * @param request
 * @param outboundChannel
 */
private void sendConnectRemoteMessage(SocksCmdRequest request,
		Channel outboundChannel) {
	ByteBuf buff = Unpooled.buffer();
	request.encodeAsByteBuf(buff);
	if (buff.hasArray()) {
		int len = buff.readableBytes();
		byte[] arr = new byte[len];
		buff.getBytes(0, arr);
		byte[] data = remoteByte(arr);
		sendRemote(data, data.length, outboundChannel);
	}
}
 
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: NettyStudy   File: ByteBufExamples.java   Source Code and License Vote up 5 votes
/**
 * Listing 5.1
 */
public static void heapBuffer(ByteBuf heapBuf) {
    if (heapBuf.hasArray()) {
    	System.out.println("has array");
        byte[] array = heapBuf.array();
        int offset = heapBuf.arrayOffset() + heapBuf.readerIndex();
        int length = heapBuf.readableBytes();
        System.out.println(offset+" " + length);
        handleArray(array, offset, length);
    }
}
 
Example 15
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 16
Project: sctalk   File: PacketDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {

    try {

        logger.debug("Protobuf decode started.");
        in.markReaderIndex();
        if (in.readableBytes() < 4) {
            logger.info("Readable Bytes length less than 4 bytes, ignored");
            in.resetReaderIndex();
            return;
        }

        DataBuffer dataBuf = new DataBuffer(in);

        IMHeader header = new IMHeader();
        header.decode(dataBuf);

        if (header.getLength() < 0) {
            ctx.close();
            logger.error("message length less than 0, channel closed");
            return;
        }

        ByteBuf byteBuf = ctx.alloc().buffer(header.getLength() - SysConstant.PROTOCOL_HEADER_LENGTH);

        in.readBytes(byteBuf);
        byte[] body;
        if (byteBuf.hasArray()) {
            body = byteBuf.array();
        } else {
            body = new byte[byteBuf.capacity()];
            byteBuf.readBytes(body);
        }

        MessageLite msg = ProtobufParseMap.getMessage(header.getServiceId(), header.getCommandId(), body);

        IMProtoMessage<MessageLite> protoMessage = new IMProtoMessage<>(header, msg);
        out.add(protoMessage);
        
        logger.debug("Received protobuf : length={}, commandId={}", header.getLength(), header.getCommandId());
    } catch (Exception e) {
        logger.error(ctx.channel().remoteAddress() + ",decode failed.", e);
    } finally {
        logger.debug("Protobuf decode finished.");
    }
}