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

The following examples show how to use io.netty.buffer.ByteBuf#hasArray() . 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: ChunkedReadWriteHandler.java    From reef with Apache License 2.0 6 votes vote down vote up
/**
 * Thread-safe since there is no shared instance state.
 * Just prepend size to the message and stream it through
 * a chunked stream and let the base method handle the actual
 * chunking.
 * <p>
 * We do not need to tag the writes since the base class ChunkedWriteHandler
 * serializes access to the channel and first write will complete before
 * the second begins.
 */
@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {

  if (msg instanceof ByteBuf) {

    final ByteBuf bf = (ByteBuf) msg;

    if (bf.hasArray()) {
      final byte[] data = bf.array();
      final byte[] size = sizeAsByteArr(data.length);
      final ByteBuf writeBuffer = Unpooled.wrappedBuffer(size, data);
      final ByteBufCloseableStream stream = new ByteBufCloseableStream(writeBuffer);
      final ChunkedStream chunkedStream = new ChunkedStream(
          stream, NettyChannelInitializer.MAXFRAMELENGTH - 1024);
      super.write(ctx, chunkedStream, promise);
    } else {
      super.write(ctx, msg, promise);
    }

  } else {
    super.write(ctx, msg, promise);
  }
}
 
Example 2
Source File: TCPClientHandler.java    From panama with MIT License 6 votes vote down vote up
protected byte[] read(ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;

    try {
        if (!byteBuf.hasArray()) {
            byte []dataSequence = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(dataSequence);

            return dataSequence;
        }

        return null;
    } finally {
        ReferenceCountUtil.release(byteBuf);
    }
}
 
Example 3
Source File: ServletNettyChannelHandler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
void copyHttpBodyData(FullHttpRequest fullHttpReq, MockHttpServletRequest servletRequest){
	ByteBuf bbContent = fullHttpReq.content();	
	
	if(bbContent.hasArray()) {				
		servletRequest.setContent(bbContent.array());
	} else {			
		if(fullHttpReq.getMethod().equals(HttpMethod.POST)){
			HttpPostRequestDecoder decoderPostData  = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpReq);
			String bbContentStr = bbContent.toString(Charset.forName(UTF_8));
			servletRequest.setContent(bbContentStr.getBytes());
			if( ! decoderPostData.isMultipart() ){
				List<InterfaceHttpData> postDatas = decoderPostData.getBodyHttpDatas();
				for (InterfaceHttpData postData : postDatas) {
					if (postData.getHttpDataType() == HttpDataType.Attribute) {
						Attribute attribute = (Attribute) postData;
						try {											
							servletRequest.addParameter(attribute.getName(),attribute.getValue());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}	
			}
		}			
	}	
}
 
Example 4
Source File: CustomLogger.java    From tutorials with MIT License 6 votes vote down vote up
private String decode(ByteBuf src, int readerIndex, int len, Charset charset) {
    if (len != 0) {
        byte[] array;
        int offset;
        if (src.hasArray()) {
            array = src.array();
            offset = src.arrayOffset() + readerIndex;
        } else {
            array = allocateUninitializedArray(max(len, 1024));
            offset = 0;
            src.getBytes(readerIndex, array, 0, len);
        }
        return new String(array, offset, len, charset);
    }
    return "";
}
 
Example 5
Source File: BasicSSLSessionInfo.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private static byte[] base64Decode(String sessionId) {
    try {
        ByteBuf sessionIdBuffer = FlexBase64.decode(sessionId);
        byte[] sessionIdData;
        if (sessionIdBuffer.hasArray()) {
            sessionIdData = sessionIdBuffer.array();
        } else {
            sessionIdData = new byte[sessionIdBuffer.readableBytes()];
            sessionIdBuffer.readBytes(sessionIdData);
        }
        return sessionIdData;
    } catch (IOException e) {
        //can happen if the session id is invalid
        return null;
    }
}
 
Example 6
Source File: Gzipper.java    From zuul with Apache License 2.0 5 votes vote down vote up
private void write(ByteBuf bb) throws IOException {
    byte[] bytes;
    int offset;
    final int length = bb.readableBytes();
    if (bb.hasArray()) {
        /* avoid memory copy if possible */
        bytes = bb.array();
        offset = bb.arrayOffset();
    } else {
        bytes = new byte[length];
        bb.getBytes(bb.readerIndex(), bytes);
        offset = 0;
    }
    gzos.write(bytes, offset, length);
}
 
Example 7
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 8
Source File: ReusableWriteHeapBuffer.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
public void writeTo(ByteBuf to, int maxWriteLength, BufferOperation operation) throws Exception {
	if (to.hasArray()) {
		to.ensureWritable(maxWriteLength);
		int widx = to.writerIndex();
		to.writerIndex(widx + operation.write(to.array(), to.arrayOffset() + widx, maxWriteLength));
	} else {
		byte[] buffer = getBuffer(maxWriteLength);
		to.writeBytes(buffer, 0, operation.write(buffer, 0, maxWriteLength));
	}
}
 
Example 9
Source File: ByteBufChecksum.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * @see #update(byte[], int, int)
 */
public void update(ByteBuf b, int off, int len) {
    if (b.hasArray()) {
        update(b.array(), b.arrayOffset() + off, len);
    } else {
        b.forEachByte(off, len, updateProcessor);
    }
}
 
Example 10
Source File: Udp2TcpHandler.java    From AgentX with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: SpdyHeaderBlockZlibDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private int setInput(ByteBuf compressed) {
    int len = compressed.readableBytes();

    if (compressed.hasArray()) {
        decompressor.setInput(compressed.array(), compressed.arrayOffset() + compressed.readerIndex(), len);
    } else {
        byte[] in = new byte[len];
        compressed.getBytes(compressed.readerIndex(), in);
        decompressor.setInput(in, 0, in.length);
    }

    return len;
}
 
Example 12
Source File: ProtobufDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: JavaVelocityCipher.java    From Velocity with MIT License 5 votes vote down vote up
private static ByteBuf asHeapBuf(ByteBuf source) {
  if (source.hasArray()) {
    // If this byte buffer is backed by an array, we can just use this buffer directly.
    return source;
  }

  int inBytes = source.readableBytes();
  byte[] inBuf = inBufLocal.get();
  if (inBuf.length <= inBytes) {
    inBuf = new byte[inBytes];
    inBufLocal.set(inBuf);
  }
  source.readBytes(inBuf, 0, inBytes);
  return Unpooled.wrappedBuffer(inBuf, 0, inBytes);
}
 
Example 14
Source File: ByteBufUtils.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public static byte[] getArray(ByteBuf buffer) {
    if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.writableBytes() == 0) {
        return buffer.array();
    }
    byte[] data = new byte[buffer.readableBytes()];
    buffer.getBytes(buffer.readerIndex(), data);
    return data;
}
 
Example 15
Source File: CompressionCodecZLib.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf encode(ByteBuf source) {
    byte[] array;
    int length = source.readableBytes();

    int sizeEstimate = (int) Math.ceil(source.readableBytes() * 1.001) + 14;
    ByteBuf compressed = PulsarByteBufAllocator.DEFAULT.heapBuffer(sizeEstimate);

    int offset = 0;
    if (source.hasArray()) {
        array = source.array();
        offset = source.arrayOffset() + source.readerIndex();
    } else {
        // If it's a direct buffer, we need to copy it
        array = new byte[length];
        source.getBytes(source.readerIndex(), array);
    }

    Deflater deflater = this.deflater.get();
    deflater.reset();
    deflater.setInput(array, offset, length);
    while (!deflater.needsInput()) {
        deflate(deflater, compressed);
    }

    return compressed;
}
 
Example 16
Source File: AppendEncodeDecodeTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
private int getAllocatedSize(ByteBuf buf) {
    if (buf.hasArray()) {
        // Array-backed buffer. The length of the array is the allocated size.
        return buf.array().length;
    } else if (buf instanceof CompositeByteBuf) {
        // Composite ByteBuf. Sum up component allocated data.
        AtomicInteger allocated = new AtomicInteger();
        ((CompositeByteBuf) buf).iterator().forEachRemaining(b -> allocated.addAndGet(getAllocatedSize(b)));
        return allocated.get();
    } else {
        // Other type of buffer (direct?). Our best guess is invoking capacity() which should return the right value.
        return buf.capacity();
    }
}
 
Example 17
Source File: HttpPostBodyUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * @param buffer buffer with a backing byte array
 */
SeekAheadOptimize(ByteBuf buffer) {
    if (!buffer.hasArray()) {
        throw new IllegalArgumentException("buffer hasn't backing byte array");
    }
    this.buffer = buffer;
    bytes = buffer.array();
    readerIndex = buffer.readerIndex();
    origPos = pos = buffer.arrayOffset() + readerIndex;
    limit = buffer.arrayOffset() + buffer.writerIndex();
}
 
Example 18
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 19
Source File: JdkZlibEncoder.java    From netty4.0.27Learn 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: UdpDecoder.java    From timely with Apache License 2.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    ByteBuf buf = in.readBytes(in.readableBytes());
    try {
        if (buf == Unpooled.EMPTY_BUFFER) {
            return;
        }
        final String input;
        if (buf.hasArray()) {
            input = new String(buf.array(), UTF_8);
        } else {
            input = buf.toString(UTF_8);
        }
        if (StringUtils.isEmpty(input)) {
            LOG.warn("Received no input");
            return;
        }
        LOG.trace("Received input {}", input);

        String[] parts = input.split(" ");
        String operation = null;
        if (parts.length == 0 && !StringUtils.isEmpty(input)) {
            operation = input;
        } else {
            operation = parts[0];
        }
        UdpRequest tcp = null;
        try {
            tcp = (UdpRequest) AnnotationResolver.getClassForUdpOperation(operation);
        } catch (Exception e) {
            LOG.error("Error getting class for operation: " + operation, e);
        }
        if (null == tcp) {
            LOG.error("Unknown udp operation: " + parts[0]);
            return;
        }
        tcp.parse(input);
        out.add(tcp);
        LOG.trace("Converted {} to {}", input, tcp);
    } finally {
        buf.release();
    }
}