Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

In this page you can find the example usage for java.nio ByteBuffer get.

Prototype

public abstract byte get();

Source Link

Document

Returns the byte at the current position and increases the position by 1.

Usage

From source file:jenkins.plugins.publish_over_cifs.CifsHostConfiguration.java

@SuppressWarnings("PMD.EmptyCatchBlock")
private static String encode(final String raw) {
    if (raw == null)
        return null;
    final StringBuilder encoded = new StringBuilder(raw.length() * ESCAPED_BUILDER_SIZE_MULTIPLIER);
    final CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    final CharBuffer buffer = CharBuffer.allocate(1);
    for (final char c : raw.toCharArray()) {
        if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            encoded.append(c);//  ww  w .  j a v  a2s .co  m
        } else {
            buffer.put(0, c);
            buffer.rewind();
            try {
                final ByteBuffer bytes = encoder.encode(buffer);
                while (bytes.hasRemaining()) {
                    final byte oneByte = bytes.get();
                    encoded.append('%');
                    encoded.append(toDigit((oneByte >> HI_TO_LOW_NIBBLE_BIT_SHIFT) & LOW_NIBBLE_BIT_MASK));
                    encoded.append(toDigit(oneByte & LOW_NIBBLE_BIT_MASK));
                }
            } catch (final CharacterCodingException cce) {
                throw new BapPublisherException(Messages.exception_encode_cce(cce.getLocalizedMessage()), cce);
            }
        }
    }
    return encoded.toString();
}

From source file:net.pms.util.AudioUtils.java

private static void parseRealAudioMetaData(ByteBuffer buffer, DLNAMediaAudio audio, short version) {
    buffer.position(buffer.position() + (version == 4 ? 3 : 4)); // skip unknown
    byte b = buffer.get();
    if (b != 0) {
        byte[] title = new byte[Math.min(b & 0xFF, buffer.remaining())];
        buffer.get(title);//from   ww w .  j  av a 2 s . com
        String titleString = new String(title, StandardCharsets.US_ASCII);
        audio.setSongname(titleString);
        audio.setAudioTrackTitleFromMetadata(titleString);
    }
    if (buffer.hasRemaining()) {
        b = buffer.get();
        if (b != 0) {
            byte[] artist = new byte[Math.min(b & 0xFF, buffer.remaining())];
            buffer.get(artist);
            audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
        }
    }
}

From source file:edu.umass.cs.gigapaxos.paxosutil.PaxosPacketDemultiplexerFast.java

/**
 * @param bytes//from   ww w.j  a  v a2 s  .  c  o  m
 * @param header
 * @return A static utility method to convert bytes to RequestPacket with
 *         header processing.
 */
public static final Object processHeaderUtil(byte[] bytes, NIOHeader header) {
    if (isByteable(bytes)) {
        long t = System.nanoTime();
        if (PaxosPacket.getType(bytes) == PaxosPacketType.REQUEST) {
            // affix header info only for request packets
            byte[] caddress = header.sndr.getAddress().getAddress();
            short cport = (short) header.sndr.getPort();
            byte[] laddress = header.rcvr.getAddress().getAddress();
            short lport = (short) header.rcvr.getPort();
            ByteBuffer bbuf = ByteBuffer.wrap(bytes, 0, 16);
            for (int i = 0; i < 3; i++)
                bbuf.getInt();
            int paxosIDLength = bbuf.get();

            int offset = 13 + paxosIDLength + 8 + 1;
            int expectedPos = offset + 4 + 2 + 4 + 2;
            assert (bytes.length > offset + 12) : bytes.length + " <= " + expectedPos;
            bbuf = ByteBuffer.wrap(bytes, offset, 12);
            boolean noCA = bytes[offset + 4] == 0 && bytes[offset + 5] == 0;
            boolean noLA = bytes[offset + 6 + 4] == 0 && bytes[offset + 6 + 5] == 0;
            try {
                if (noCA)
                    bbuf.put(caddress).putShort(cport);
                if (noLA)
                    bbuf.put(laddress).putShort(lport);

            } catch (Exception e) {
                assert (false) : bytes.length + " ? " + 16 + 4 + paxosIDLength + 8 + 1;
            }
        }
        try {
            PaxosPacket pp = toPaxosPacket(bytes);
            if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100)) {
                if (pp.getType() == PaxosPacketType.REQUEST)
                    DelayProfiler.updateDelayNano("<-request", t);
                else if (pp.getType() == PaxosPacketType.BATCHED_ACCEPT_REPLY)
                    DelayProfiler.updateDelayNano("<-acceptreply", t);
            }
            return pp;
        } catch (UnsupportedEncodingException | UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    if (!JSONPacket.couldBeJSON(bytes))
        return bytes;

    String message;
    long t = System.nanoTime();
    try {
        message = MessageExtractor.decode(bytes);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
    net.minidev.json.JSONObject json = MessageExtractor.parseJSONSmart(message);
    assert (json != null) : message;
    net.minidev.json.JSONObject retval = MessageExtractor.stampAddressIntoJSONObject(header.sndr, header.rcvr,
            insertStringifiedSelf(json, message));
    assert (retval != null) : message + " " + header;
    try {
        if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100))
            if (PaxosPacket.getPaxosPacketType(retval) == PaxosPacket.PaxosPacketType.REQUEST)
                DelayProfiler.updateDelayNano("requestJSONification", t);
            else if (PaxosPacket.getPaxosPacketType(retval) == PaxosPacket.PaxosPacketType.BATCHED_ACCEPT_REPLY)
                DelayProfiler.updateDelayNano("batchedAcceptReplyJSONification", t);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return retval;
}

From source file:net.darkmist.alib.io.BufferUtil.java

public static boolean isAll(ByteBuffer buf, byte b) {
    buf = buf.duplicate();// w ww  . j  a v a 2s . co m

    while (buf.hasRemaining())
        if (buf.get() != b)
            return false;
    return true;
}

From source file:com.box.restclientv2.httpclientsupport.HttpClientURLEncodedUtils.java

/**
 * Emcode/escape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 * // ww w . java 2  s .c  om
 * @param content
 *            the portion to decode
 * @param charset
 *            the charset to use
 * @param blankAsPlus
 *            if {@code true}, then convert space to '+' (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return
 */
private static String urlencode(final String content, final Charset charset, final BitSet safechars,
        final boolean blankAsPlus) {
    if (content == null) {
        return null;
    }
    StringBuilder buf = new StringBuilder();
    ByteBuffer bb = charset.encode(content);
    while (bb.hasRemaining()) {
        int b = bb.get() & 0xff;
        if (safechars.get(b)) {
            buf.append((char) b);
        } else if (blankAsPlus && b == ' ') {
            buf.append('+');
        } else {
            buf.append("%");
            char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
            char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
            buf.append(hex1);
            buf.append(hex2);
        }
    }
    return buf.toString();
}

From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java

/**
 * Emcode/escape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 * //from  www  .  ja  v a2  s.c o m
 * @param content the portion to decode
 * @param charset the charset to use
 * @param blankAsPlus if {@code true}, then convert space to '+' (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return
 */
private static String urlencode(final String content, final Charset charset, final BitSet safechars,
        final boolean blankAsPlus) {
    if (content == null)
        return null;
    StringBuilder buf = new StringBuilder();
    ByteBuffer bb = charset.encode(content);
    while (bb.hasRemaining()) {
        int b = bb.get() & 0xff;
        if (safechars.get(b))
            buf.append((char) b);
        else if (blankAsPlus && b == ' ')
            buf.append('+');
        else {
            buf.append("%");
            char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
            char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
            buf.append(hex1);
            buf.append(hex2);
        }
    }
    return buf.toString();
}

From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java

public static RpcCommand decode(final ByteBuffer byteBuffer) {
    ///*w w w .  j  a v a  2s .com*/
    int length = byteBuffer.limit();
    //?? 1byte
    byte protocolType = byteBuffer.get();
    //Header 4type
    int headerLength = byteBuffer.getInt();
    //Header
    byte[] headerData = new byte[headerLength];
    byteBuffer.get(headerData);

    RpcCommand cmd = headerDecode(headerData, getProtocolType(protocolType));
    //body
    int bodyLength = length - 5 - headerLength;
    byte[] bodyData = null;
    if (bodyLength > 0) {
        bodyData = new byte[bodyLength];
        byteBuffer.get(bodyData);
    }
    cmd.body = bodyData;

    return cmd;
}

From source file:io.mycat.util.ByteBufferUtil.java

public static InputStream inputStream(ByteBuffer bytes) {
    final ByteBuffer copy = bytes.duplicate();

    return new InputStream() {
        public int read() {
            if (!copy.hasRemaining()) {
                return -1;
            }//from ww w  . ja  v a2  s  .  c  o m

            return copy.get() & 0xFF;
        }

        @Override
        public int read(byte[] bytes, int off, int len) {
            if (!copy.hasRemaining()) {
                return -1;
            }

            len = Math.min(len, copy.remaining());
            copy.get(bytes, off, len);
            return len;
        }

        @Override
        public int available() {
            return copy.remaining();
        }
    };
}

From source file:io.Text.java

/**
 * Returns the next code point at the current position in
 * the buffer. The buffer's position will be incremented.
 * Any mark set on this buffer will be changed by this method!
 *///w  w  w .j a  v a 2  s .com
public static int bytesToCodePoint(ByteBuffer bytes) {
    bytes.mark();
    byte b = bytes.get();
    bytes.reset();
    int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
    if (extraBytesToRead < 0)
        return -1; // trailing byte!
    int ch = 0;

    switch (extraBytesToRead) {
    case 5:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 4:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 3:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 2:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 1:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 0:
        ch += (bytes.get() & 0xFF);
    }
    ch -= offsetsFromUTF8[extraBytesToRead];

    return ch;
}

From source file:org.apache.arrow.vector.util.Text.java

/**
 * Returns the next code point at the current position in the buffer. The buffer's position will be incremented. Any
 * mark set on this buffer will be changed by this method!
 *//*from   w w  w  . j ava 2 s. c  o  m*/
public static int bytesToCodePoint(ByteBuffer bytes) {
    bytes.mark();
    byte b = bytes.get();
    bytes.reset();
    int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
    if (extraBytesToRead < 0) {
        return -1; // trailing byte!
    }
    int ch = 0;

    switch (extraBytesToRead) {
    case 5:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 4:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 3:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 2:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 1:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 0:
        ch += (bytes.get() & 0xFF);
    }
    ch -= offsetsFromUTF8[extraBytesToRead];

    return ch;
}