Example usage for io.netty.buffer ByteBuf toString

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

Introduction

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

Prototype

public abstract String toString(int index, int length, Charset charset);

Source Link

Document

Decodes this buffer's sub-region into a string with the specified character set.

Usage

From source file:io.nodyn.buffer.Buffer.java

License:Apache License

public static String binarySlice(JSObject object, int start, int end) {
    ByteBuf b = extract(object);
    return b.toString(start, (end - start), BINARY);
}

From source file:io.reactiverse.pgclient.impl.codec.DataTypeCodec.java

License:Apache License

private static <T> T textDecodeArrayElement(DataType type, int index, int len, ByteBuf buff) {
    if (len == 4 && Character.toUpperCase(buff.getByte(index)) == 'N'
            && Character.toUpperCase(buff.getByte(index + 1)) == 'U'
            && Character.toUpperCase(buff.getByte(index + 2)) == 'L'
            && Character.toUpperCase(buff.getByte(index + 3)) == 'L') {
        return null;
    } else {/*  www  .j av  a2s.  c o  m*/
        boolean escaped = buff.getByte(index) == '"';
        if (escaped) {
            // Some escaping - improve that later...
            String s = buff.toString(index + 1, len - 2, StandardCharsets.UTF_8);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '\\') {
                    c = s.charAt(++i);
                }
                sb.append(c);
            }
            buff = Unpooled.copiedBuffer(sb, StandardCharsets.UTF_8);
            index = 0;
            len = buff.readableBytes();
        }
        return (T) decodeText(type, index, len, buff);
    }
}

From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java

License:Open Source License

static Function<DnsRecord, String> address(int octets) {
    return record -> {
        ByteBuf data = ((DnsRawRecord) record).content();
        int size = data.writerIndex() - data.readerIndex();
        if (size != octets) {
            throw new DecoderException("Invalid content length, or reader index when decoding address [index: "
                    + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "].");
        }/*from   w  w w .  ja  v  a 2s  .co  m*/
        byte[] address = new byte[octets];
        data.getBytes(data.readerIndex(), address);
        try {
            return InetAddress.getByAddress(address).getHostAddress();
        } catch (UnknownHostException e) {
            throw new DecoderException("Could not convert address "
                    + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress.");
        }
    };
}

From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java

License:Open Source License

/**
 * Retrieves a domain name given a buffer containing a DNS packet. If the
 * name contains a pointer, the position of the buffer will be set to
 * directly after the pointer's index after the name has been read.
 *
 * @param buf the byte buffer containing the DNS packet
 * @return the domain name for an entry/*  w  w w.j ava  2s.c o m*/
 */
static String readName(ByteBuf buf) {
    int position = -1;
    StringBuilder name = new StringBuilder();
    for (int len = buf.readUnsignedByte(); buf.isReadable() && len != 0; len = buf.readUnsignedByte()) {
        boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            if (position == -1) {
                position = buf.readerIndex() + 1;
            }
            buf.readerIndex((len & 0x3f) << 8 | buf.readUnsignedByte());
        } else {
            name.append(buf.toString(buf.readerIndex(), len, CharsetUtil.UTF_8)).append(".");
            buf.skipBytes(len);
        }
    }
    if (position != -1) {
        buf.readerIndex(position);
    }
    if (name.length() == 0) {
        return null;
    }
    return name.substring(0, name.length() - 1);
}

From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.java

License:Open Source License

/**
 * Retrieves a domain name given a buffer containing a DNS packet without
 * advancing the readerIndex for the buffer.
 *
 * @param buf    the byte buffer containing the DNS packet
 * @param offset the position at which the name begins
 * @return the domain name for an entry//ww  w.j  a va 2 s.  co  m
 */
static String getName(ByteBuf buf, int offset) {
    StringBuilder name = new StringBuilder();
    for (int len = buf.getUnsignedByte(offset++); buf.writerIndex() > offset
            && len != 0; len = buf.getUnsignedByte(offset++)) {
        boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            offset = (len & 0x3f) << 8 | buf.getUnsignedByte(offset++);
        } else {
            name.append(buf.toString(offset, len, CharsetUtil.UTF_8)).append(".");
            offset += len;
        }
    }
    if (name.length() == 0) {
        return null;
    }
    return name.substring(0, name.length() - 1);
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

/**
 * Retrieves a domain name given a buffer containing a DNS packet. If the
 * name contains a pointer, the position of the buffer will be set to
 * directly after the pointer's index after the name has been read.
 *
 * @param in the byte buffer containing the DNS packet
 * @return the domain name for an entry//from   w  w  w.j a va  2  s.com
 */
public static String decodeName(ByteBuf in) {
    int position = -1;
    int checked = 0;
    final int end = in.writerIndex();
    final int readable = in.readableBytes();

    // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
    // some servers do not respect this for empty names. So just workaround this and return an empty name in this
    // case.
    //
    // See:
    // - https://github.com/netty/netty/issues/5014
    // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
    if (readable == 0) {
        return ".";
    }

    final StringBuilder name = new StringBuilder(readable << 1);
    while (in.isReadable()) {
        final int len = in.readUnsignedByte();
        final boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            if (position == -1) {
                position = in.readerIndex() + 1;
            }

            if (!in.isReadable()) {
                throw new CorruptedFrameException("truncated pointer in a name");
            }

            final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
            if (next >= end) {
                throw new CorruptedFrameException("name has an out-of-range pointer");
            }
            in.readerIndex(next);

            // check for loops
            checked += 2;
            if (checked >= end) {
                throw new CorruptedFrameException("name contains a loop.");
            }
        } else if (len != 0) {
            if (!in.isReadable(len)) {
                throw new CorruptedFrameException("truncated label in a name");
            }
            name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
            in.skipBytes(len);
        } else { // len == 0
            break;
        }
    }

    if (position != -1) {
        in.readerIndex(position);
    }

    if (name.length() == 0) {
        return ".";
    }

    if (name.charAt(name.length() - 1) != '.') {
        name.append('.');
    }

    return name.toString();
}

From source file:netty.syslog.DecoderUtil.java

License:Open Source License

static String readStringToSpace(ByteBuf buffer, boolean checkNull) {
    if (checkNull && peek(buffer) == '-') {
        buffer.readByte();//from   w w  w . j a  v  a2  s  .  com
        return null;
    }
    int length = -1;
    for (int i = buffer.readerIndex(); i < buffer.capacity(); i++) {
        if (buffer.getByte(i) == ' ') {
            length = i - buffer.readerIndex();
            break;
        }
    }
    if (length < 0) {
        length = buffer.readableBytes();
    }
    final String s = buffer.toString(buffer.readerIndex(), length, CharsetUtil.UTF_8);
    buffer.skipBytes(length);
    return s;
}

From source file:org.apache.hadoop.hbase.security.SaslChallengeDecoder.java

License:Apache License

private void tryDecodeError(ByteBuf in, int offset, int readableBytes) throws IOException {
    if (readableBytes < 4) {
        return;/* w ww  .j a  v a 2s . c  o m*/
    }
    int classLen = in.getInt(offset);
    if (classLen <= 0) {
        throw new IOException("Invalid exception class name length " + classLen);
    }
    if (classLen > MAX_CHALLENGE_SIZE) {
        throw new IOException("Exception class name length too large(" + classLen + "), max allowed is "
                + MAX_CHALLENGE_SIZE);
    }
    if (readableBytes < 4 + classLen + 4) {
        return;
    }
    int msgLen = in.getInt(offset + 4 + classLen);
    if (msgLen <= 0) {
        throw new IOException("Invalid exception message length " + msgLen);
    }
    if (msgLen > MAX_CHALLENGE_SIZE) {
        throw new IOException(
                "Exception message length too large(" + msgLen + "), max allowed is " + MAX_CHALLENGE_SIZE);
    }
    int totalLen = classLen + msgLen + 8;
    if (readableBytes < totalLen) {
        return;
    }
    String className = in.toString(offset + 4, classLen, HConstants.UTF8_CHARSET);
    String msg = in.toString(offset + classLen + 8, msgLen, HConstants.UTF8_CHARSET);
    in.readerIndex(offset + totalLen);
    throw new RemoteException(className, msg);
}

From source file:org.apache.helix.ipc.netty.NettyHelixIPCUtils.java

License:Apache License

/** Given a byte buf w/ a certain reader index, encodes the next length bytes as a String */
public static String toNonEmptyString(int length, ByteBuf byteBuf) {
    if (byteBuf.readableBytes() >= length) {
        String string = byteBuf.toString(byteBuf.readerIndex(), length, Charset.defaultCharset());
        byteBuf.readerIndex(byteBuf.readerIndex() + length);
        return string;
    }//from ww w  .  jav  a2s .c o m
    return null;
}

From source file:org.apache.tajo.util.NumberUtil.java

License:Apache License

/**
 * Parses the byte array argument as if it was a double value and returns the
 * result. Throws NumberFormatException if the byte buffer does not represent a
 * double value.//from w w w.  j a va2s .c o m
 *
 * @return double, the value represented by the argument
 * @throws NumberFormatException if the argument could not be parsed as a double
 */
public static double parseDouble(ByteBuf bytes, int start, int length) {
    if (!PlatformDependent.hasUnsafe()) {
        return parseDouble(bytes.array(), start, length);
    }

    if (bytes == null) {
        throw new NumberFormatException("String is null");
    }

    if (length == 0 || bytes.writerIndex() < start + length) {
        throw new NumberFormatException("Empty string or Invalid buffer!");
    }

    long memoryAddress = bytes.memoryAddress();
    /*
     * Strip off leading blanks
     */
    int offset = start;
    int end = start + length;

    while (offset < end && PlatformDependent.getByte(memoryAddress + offset) == ' ') {
        offset++;
    }
    if (offset == end) {
        throw new NumberFormatException("blank byte array!");
    }

    /*
     * check for a sign.
     */
    boolean sign = false;
    if (PlatformDependent.getByte(memoryAddress + offset) == '-') {
        sign = true;
        offset++;
    } else if (PlatformDependent.getByte(memoryAddress + offset) == '+') {
        offset++;
    }
    if (offset == end) {
        throw new NumberFormatException("the byte array only has a sign!");
    }

    /*
     * Count the number of digits in the mantissa (including the decimal
     * point), and also locate the decimal point.
     */
    int mantSize = 0; /* Number of digits in mantissa. */
    int decicalOffset = -1; /* Number of mantissa digits BEFORE decimal point. */
    for (; offset < end; offset++) {
        if (!isDigit(PlatformDependent.getByte(memoryAddress + offset))) {
            if ((PlatformDependent.getByte(memoryAddress + offset) != '.') || (decicalOffset >= 0)) {
                break;
            }
            decicalOffset = mantSize;
        }
        mantSize++;
    }

    int exponentOffset = offset; /* Temporarily holds location of exponent in bytes. */

    /*
     * Now suck up the digits in the mantissa.  Use two integers to
     * collect 9 digits each (this is faster than using floating-point).
     * If the mantissa has more than 18 digits, ignore the extras, since
     * they can't affect the value anyway.
     */
    offset -= mantSize;
    if (decicalOffset < 0) {
        decicalOffset = mantSize;
    } else {
        mantSize -= 1; /* One of the digits was the decimal point. */
    }
    int fracExponent; /* Exponent that derives from the fractional
                       * part.  Under normal circumstatnces, it is
                           * the negative of the number of digits in F.
                           * However, if I is very long, the last digits
                           * of I get dropped (otherwise a long I with a
                           * large negative exponent could cause an
                           * unnecessary overflow on I alone).  In this
                           * case, fracExp is incremented one for each
                           * dropped digit. */
    if (mantSize > 18) {
        fracExponent = decicalOffset - 18;
        mantSize = 18;
    } else {
        fracExponent = decicalOffset - mantSize;
    }

    if (mantSize == 0) {
        return 0.0;
    }

    int frac1 = 0;
    for (; mantSize > 9; mantSize--) {
        int b = PlatformDependent.getByte(memoryAddress + offset);
        offset++;
        if (b == '.') {
            b = PlatformDependent.getByte(memoryAddress + offset);
            offset++;
        }
        frac1 = 10 * frac1 + (b - '0');
    }
    int frac2 = 0;
    for (; mantSize > 0; mantSize--) {
        int b = PlatformDependent.getByte(memoryAddress + offset);
        offset++;
        if (b == '.') {
            b = PlatformDependent.getByte(memoryAddress + offset);
            offset++;
        }
        frac2 = 10 * frac2 + (b - '0');
    }
    double fraction = (1.0e9 * frac1) + frac2;

    /*
     * Skim off the exponent.
     */
    int exponent = 0; /* Exponent read from "EX" field. */
    offset = exponentOffset;
    boolean expSign = false;

    if (offset < end) {
        if ((PlatformDependent.getByte(memoryAddress + offset) != 'E')
                && (PlatformDependent.getByte(memoryAddress + offset) != 'e')) {
            throw new NumberFormatException(bytes.toString(start, length, Charset.defaultCharset()));
        }

        // (bytes[offset] == 'E') || (bytes[offset] == 'e')
        offset++;

        if (PlatformDependent.getByte(memoryAddress + offset) == '-') {
            expSign = true;
            offset++;
        } else if (PlatformDependent.getByte(memoryAddress + offset) == '+') {
            offset++;
        }

        for (; offset < end; offset++) {
            if (isDigit(PlatformDependent.getByte(memoryAddress + offset))) {
                exponent = exponent * 10 + (PlatformDependent.getByte(memoryAddress + offset) - '0');
            } else {
                throw new NumberFormatException(bytes.toString(start, length, Charset.defaultCharset()));
            }
        }
    }

    exponent = expSign ? (fracExponent - exponent) : (fracExponent + exponent);

    /*
     * Generate a floating-point number that represents the exponent.
     * Do this by processing the exponent one bit at a time to combine
     * many powers of 2 of 10. Then combine the exponent with the
     * fraction.
     */
    if (exponent < 0) {
        expSign = true;
        exponent = -exponent;
    } else {
        expSign = false;
    }
    if (exponent > maxExponent) {
        throw new NumberFormatException(bytes.toString(start, length, Charset.defaultCharset()));
    }

    double dblExp = 1.0;
    for (int i = 0; exponent != 0; exponent >>= 1, i++) {
        if ((exponent & 01) == 01) {
            dblExp *= powersOf10[i];
        }
    }

    fraction = (expSign) ? (fraction / dblExp) : (fraction * dblExp);

    return sign ? (-fraction) : fraction;
}