Example usage for io.netty.buffer ByteBuf getBytes

List of usage examples for io.netty.buffer ByteBuf getBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf getBytes.

Prototype

public abstract ByteBuf getBytes(int index, ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the specified absolute index until the destination's position reaches its limit.

Usage

From source file:com.dianping.cat.message.CodecHandler.java

License:Open Source License

public static MessageTree decode(ByteBuf buf) {
    byte[] data = new byte[3];
    MessageTree tree;//from   w ww.j ava2s. co  m

    buf.getBytes(4, data);
    String hint = new String(data);

    buf.resetReaderIndex();

    if ("PT1".equals(hint)) {
        tree = m_plainTextCodec.decode(buf);
    } else if ("NT1".equals(hint)) {
        tree = m_nativeCodec.decode(buf);
    } else {
        throw new RuntimeException("Error message type : " + hint);
    }

    MessageTreeFormat.format(tree);
    return tree;
}

From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponse.java

License:Apache License

@Override
public byte[] getContent() {
    ByteBuf buf = response.content();
    byte[] bytes;
    int length = buf.readableBytes();

    if (buf.hasArray()) {
        bytes = buf.array();//from  w  w w.  jav  a 2 s. com
    } else {
        bytes = new byte[length];
        buf.getBytes(buf.readerIndex(), bytes);
    }
    buf.release();
    return bytes;
}

From source file:com.eightkdata.mongowp.bson.netty.NettyBsonString.java

License:Open Source License

private String getString(@Tight ByteBuf byteBuf) {
    int lenght = getStringLenght(byteBuf);
    byte[] bytes = new byte[lenght];
    byteBuf.getBytes(0, bytes);
    return new String(bytes, Charsets.UTF_8);
}

From source file:com.kael.surf.net.codec.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   in              the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created./*from  w  w  w  .  j  ava  2 s . c  o  m*/
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    Integer packetNum = ctx.attr(countKey).get();
    if (packetNum == null || packetNum <= 100) {
        ctx.attr(countKey).set(packetNum == null ? 1 : packetNum + 1);

        int readableBytes = in.readableBytes();
        if (skipPolicy && readableBytes >= lengthFieldEndOffset) {
            if (readableBytes >= POLICY_STR_BYTES.length) {
                byte[] dst = new byte[POLICY_STR_BYTES.length];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, POLICY_STR_BYTES)) {
                    in.skipBytes(POLICY_STR_BYTES.length);
                    return new String(dst);
                }
            } else {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, POLICY_STR_BYTES)) {
                    return null;
                }
            }
        }

        if (skipTencentGTWHead && readableBytes >= lengthFieldEndOffset) {
            if (readableBytes >= GET_BYTES.length) {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isBeginWith(dst, GET_BYTES)) {
                    int endIndex = findEndIndex(dst, CRLF_BYTES);
                    if (endIndex == -1) {
                        return null;
                    }
                    in.skipBytes(endIndex);
                }
            } else {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, GET_BYTES)) {
                    return null;
                }
            }
        }
    }

    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;

        failIfNecessary(false);
    }

    if (in.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        long discard = frameLength - in.readableBytes();
        tooLongFrameLength = frameLength;

        if (discard < 0) {
            // buffer contains more bytes then the frameLength so we can discard all now
            in.skipBytes((int) frameLength);
        } else {
            // Enter the discard mode and discard everything received so far.
            discardingTooLongFrame = true;
            bytesToDiscard = discard;
            in.skipBytes(in.readableBytes());
        }
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

private void onPacketSent(ByteBuf buf) {
    final byte[] data = new byte[buf.writerIndex()];
    buf.getBytes(0, data);
    EventDispatcher.getInstance().notifyEvent(new OnPacketSent(_client, data));
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

private void onPacketReceive(ByteBuf buf) {
    final byte[] data = new byte[buf.writerIndex()];
    buf.getBytes(0, data);
    EventDispatcher.getInstance().notifyEvent(new OnPacketReceived(_client, data));
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroup.java

License:Apache License

@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    final boolean hasLoopbackARecords = records.stream().filter(r -> r instanceof DnsRawRecord)
            .map(DnsRawRecord.class::cast).anyMatch(
                    r -> r.type() == DnsRecordType.A && r.content().getByte(r.content().readerIndex()) == 127);

    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord)) {
            continue;
        }//  w w w  .jav a2s.  c  o  m

        final DnsRecordType type = r.type();
        final ByteBuf content = ((ByteBufHolder) r).content();
        final int contentLen = content.readableBytes();

        // Skip invalid records.
        if (type == DnsRecordType.A) {
            if (contentLen != 4) {
                warnInvalidRecord(DnsRecordType.A, content);
                continue;
            }
        } else if (type == DnsRecordType.AAAA) {
            if (contentLen != 16) {
                warnInvalidRecord(DnsRecordType.AAAA, content);
                continue;
            }
        } else {
            continue;
        }

        // Convert the content into an IP address and then into an endpoint.
        final String ipAddr;
        final byte[] addrBytes = new byte[contentLen];
        content.getBytes(content.readerIndex(), addrBytes);

        if (contentLen == 16) {
            // Convert some IPv6 addresses into IPv4 addresses to remove duplicate endpoints.
            if (addrBytes[0] == 0x00 && addrBytes[1] == 0x00 && addrBytes[2] == 0x00 && addrBytes[3] == 0x00
                    && addrBytes[4] == 0x00 && addrBytes[5] == 0x00 && addrBytes[6] == 0x00
                    && addrBytes[7] == 0x00 && addrBytes[8] == 0x00 && addrBytes[9] == 0x00) {

                if (addrBytes[10] == 0x00 && addrBytes[11] == 0x00) {
                    if (addrBytes[12] == 0x00 && addrBytes[13] == 0x00 && addrBytes[14] == 0x00
                            && addrBytes[15] == 0x01) {
                        // Loopback address (::1)
                        if (hasLoopbackARecords) {
                            // Contains an IPv4 loopback address already; skip.
                            continue;
                        } else {
                            ipAddr = "::1";
                        }
                    } else {
                        // IPv4-compatible address.
                        ipAddr = NetUtil.bytesToIpAddress(addrBytes, 12, 4);
                    }
                } else if (addrBytes[10] == -1 && addrBytes[11] == -1) {
                    // IPv4-mapped address.
                    ipAddr = NetUtil.bytesToIpAddress(addrBytes, 12, 4);
                } else {
                    ipAddr = NetUtil.bytesToIpAddress(addrBytes);
                }
            } else {
                ipAddr = NetUtil.bytesToIpAddress(addrBytes);
            }
        } else {
            ipAddr = NetUtil.bytesToIpAddress(addrBytes);
        }

        final Endpoint endpoint = port != 0 ? Endpoint.of(hostname, port) : Endpoint.of(hostname);
        builder.add(endpoint.withIpAddr(ipAddr));
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})", logPrefix(),
                endpoints.stream().map(Endpoint::ipAddr).collect(Collectors.joining(", ")), ttl);
    }

    return endpoints;
}

From source file:com.microsoft.Malmo.MissionHandlers.RewardForItemBase.java

License:Open Source License

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);
}

From source file:com.moshi.receptionist.remoting.netty.NettyDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    try {/*from www .ja  va2  s .  c o m*/
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) {
            return null;
        }

        byte[] tmpBuf = new byte[frame.capacity()];
        frame.getBytes(0, tmpBuf);
        frame.release();

        return RemotingCommand.decode(tmpBuf);
    } catch (Exception e) {
        log.error("decode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        // ? pipelineclose???
        RemotingUtil.closeChannel(ctx.channel());
    }

    return null;
}

From source file:com.necla.simba.server.gateway.server.frontend.FrontendFrameDecoder.java

License:Apache License

private ByteBuf decompress(ChannelHandlerContext ctx, ByteBuf frame) throws Exception {
    int readableBytes = frame.readableBytes();
    if (frame.hasArray()) {
        inflater.setInput(frame.array(), 0, readableBytes);
    } else {/*w  ww . java2  s .c o  m*/
        byte[] array = new byte[frame.readableBytes()];
        frame.getBytes(0, array);
        inflater.setInput(array);
    }
    int totalLength = 0;
    List<ByteBuf> all = new LinkedList<ByteBuf>();
    int multiplier = 2;
    alldone: while (true) {

        int maxOutputLength = inflater.getRemaining() * multiplier;
        // multiplier keeps increasing, so we will keep picking
        // larger and larger buffers the more times we have to loop
        // around, i.e., the more we realize that the data was very
        // heavily compressed, the larger our buffers are going to be.
        multiplier += 1;
        ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength);
        while (!inflater.needsInput()) {
            byte[] outArray = decompressed.array();
            int outIndex = decompressed.arrayOffset() + decompressed.writerIndex();
            int length = outArray.length - outIndex;
            if (length == 0)
                break;
            try {
                //LOG.debug("here1");
                int outputLength = inflater.inflate(outArray, outIndex, length);
                totalLength += outputLength;
                //LOG.debug("here2");

                if (outputLength > 0)
                    decompressed.writerIndex(decompressed.writerIndex() + outputLength);
            } catch (DataFormatException e) {
                throw new Exception("Could not inflate" + e.getMessage());
            }
            if (inflater.finished()) {
                all.add(decompressed);
                break alldone;
            }

        }
        all.add(decompressed);
    }
    inflater.reset();
    if (all.size() == 1)
        return all.get(0);
    else {
        ByteBuf allData = ctx.alloc().heapBuffer(totalLength);
        for (ByteBuf b : all) {
            //LOG.debug("capacity=" + allData.capacity());
            allData.writeBytes(b);
            b.release();
        }
        return allData;
    }

}