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:com.sm.connector.server.ServerStore.java

protected Pair<byte[], byte[]> next(int current, ByteBuffer buf) throws IOException {
    buf.clear();/*from  w  w w . j  a v a2  s  .  co  m*/
    long pos = OFFSET + (long) current * RECORD_SIZE;
    indexChannel.read(buf, pos);
    buf.rewind();
    byte status = buf.get();
    if (isDeleted(status)) {
        return null;
    } else {
        long keyLen = buf.getLong();
        byte[] keys = readChannel(keyLen, keyChannel);
        long data = buf.getLong();
        long block2version = buf.getLong();
        CacheBlock block = new CacheBlock(current, data, block2version, status);
        if (block.getDataOffset() <= 0 || block.getDataLen() <= 0
                || block.getBlockSize() < block.getDataLen()) {
            throw new StoreException("data reading error");
        } else {
            //Key key = toKey(keys);
            byte[] datas = readChannel(block.getDataOffset2Len(), dataChannel);
            return new Pair(keys, datas);
        }
    }
}

From source file:com.meidusa.venus.benchmark.FileLineRandomData.java

private final String readLine(ByteBuffer buffer) {
    if (closed)//from  ww  w . ja  v a  2 s.  c o m
        throw new IllegalStateException("file closed..");
    ByteBuffer tempbuffer = localTempBuffer.get();
    tempbuffer.position(0);
    tempbuffer.limit(tempbuffer.capacity());
    byte c = -1;
    boolean eol = false;
    while (!eol) {
        switch (c = buffer.get()) {
        case -1:
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            int cur = buffer.position();
            if ((buffer.get()) != '\n') {
                buffer.position(cur);
            }
            break;
        default:
            tempbuffer.put(c);
            break;
        }
    }

    if ((c == -1) && (tempbuffer.position() == 0)) {
        return null;
    }
    tempbuffer.flip();

    try {
        return new String(tempbuffer.array(), encoding);
    } catch (UnsupportedEncodingException e) {
        return new String(tempbuffer.array());
    }

}

From source file:org.openhab.binding.insteonplm.internal.driver.hub.HubIOStream.java

/**
 * Sends Insteon message (byte array) as a readable ascii string to the Hub
 * /*w  w w. j  a v a2  s  . c  om*/
 * @param msg byte array representing the Insteon message
 * @throws IOException in case of I/O error
 */
public synchronized void write(ByteBuffer msg) throws IOException {
    poll(); // fetch the status buffer before we send out commands
    clearBuffer(); // clear the status buffer explicitly.

    StringBuilder b = new StringBuilder();
    while (msg.remaining() > 0) {
        b.append(String.format("%02x", msg.get()));
    }
    String hexMSG = b.toString();
    getURL("/3?" + hexMSG + "=I=3");
}

From source file:edu.hawaii.soest.hioos.storx.StorXParser.java

/**
 * Parses the binary STOR-X timestamp. The timestamp format is
 * YYYYDDD from the first 3 bytes, and HHMMSS.SSS from the last four:
 * Example:/*w w  w .j  av a2s .  co  m*/
 * 1E AC CC = 2010316 (year 2010, julian day 316)
 * 09 9D 3E 20 = 16:13:00.000 (4:13 pm)
 * @param timestamp - the timestamp to parse as a byte array
 * @return date - the timestamp as a Date object
 */
public Date parseTimestamp(byte[] timestamp) {

    Date convertedDate = new Date(0L); // initialize to the epoch

    try {
        ByteBuffer timestampBuffer = ByteBuffer.wrap(timestamp);

        // convert the year and day bytes
        int yearAndJulianDay = ((timestampBuffer.get() & 0xFF) << 16) | ((timestampBuffer.get() & 0xFF) << 8)
                | ((timestampBuffer.get() & 0xFF));

        String yearAndJulianDayString = new Integer(yearAndJulianDay).toString();

        // convert the hour, minute, second, millis bytes
        int hourMinuteSecondMillis = timestampBuffer.getInt();
        String hourMinuteSecondMillisString = String.format("%09d", hourMinuteSecondMillis);

        // concatenate the strings to get the timestamp
        String timestampString = yearAndJulianDayString + hourMinuteSecondMillisString;

        // convert to a Date object
        FRAME_DATE_FORMAT.setTimeZone(TZ);
        convertedDate = FRAME_DATE_FORMAT.parse(timestampString, new ParsePosition(0));

    } catch (BufferUnderflowException bue) {

        logger.debug(
                "There was a problem reading the timestamp. " + "The error message was: " + bue.getMessage());

    } catch (NullPointerException npe) {

        logger.debug("There was a problem converting the timestamp. " + "The error message was: "
                + npe.getMessage());

    } finally {

        return convertedDate;

    }

}

From source file:io.Text.java

/**
 * Finds any occurence of <code>what</code> in the backing
 * buffer, starting as position <code>start</code>. The starting
 * position is measured in bytes and the return value is in
 * terms of byte position in the buffer. The backing buffer is
 * not converted to a string for this operation.
 * @return byte position of the first occurence of the search
 *         string in the UTF-8 buffer or -1 if not found
 *//*from  w ww. j  a  v  a  2  s . c  o  m*/
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found)
                    return pos;
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

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

/**
 * Finds any occurence of <code>what</code> in the backing buffer, starting as position <code>start</code>. The
 * starting position is measured in bytes and the return value is in terms of byte position in the buffer. The backing
 * buffer is not converted to a string for this operation.
 *
 * @return byte position of the first occurence of the search string in the UTF-8 buffer or -1 if not found
 *//*from   www  .j  a  va  2s  .c o  m*/
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found) {
                    return pos;
                }
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptReplyPacket.java

/**
 * @param bbuf/* w w  w  . j a v  a  2 s  .  c o  m*/
 * @throws UnsupportedEncodingException
 * @throws UnknownHostException
 */
public AcceptReplyPacket(ByteBuffer bbuf) throws UnsupportedEncodingException, UnknownHostException {
    super(bbuf);
    int paxosIDLength = this.getPaxosID().getBytes(CHARSET).length;
    assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + paxosIDLength);
    this.acceptor = bbuf.getInt();
    this.ballot = new Ballot(bbuf.getInt(), bbuf.getInt());
    this.slotNumber = bbuf.getInt();
    this.maxCheckpointedSlot = bbuf.getInt();
    this.requestID = bbuf.getLong();
    if (bbuf.get() == (byte) 1)
        this.setDigestRequest();
    assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + paxosIDLength + SIZEOF_ACCEPTREPLY) : bbuf.position()
            + " != [" + SIZEOF_PAXOSPACKET_FIXED + " + " + paxosIDLength + " + " + SIZEOF_ACCEPTREPLY + "]";
}

From source file:edu.tsinghua.lumaqq.qq.Util.java

/**
 * buf???buf/*ww w .j  av a  2s . co  m*/
 * <p>
 * ?buf??buf????
 * ?buf???buf??
 * </p>
 * <p>
 * QQ???GBK?
 * </p>
 * 
 * @param buf
 *          ByteBuffer          
 * @return 
 */
public static String getString(ByteBuffer buf) {
    baos.reset();
    while (buf.hasRemaining()) {
        baos.write(buf.get());
    }
    return getString(baos.toByteArray());
}

From source file:edu.tsinghua.lumaqq.qq.Util.java

/**
 * buf???buf/*w ww. j a  v  a  2 s .c  o  m*/
 * <p>
 * ?buf??buf????
 * ?buf????
 * </p>
 * <p>
 * QQ???GBK?
 * </p>
 * 
 * @param buf
 *          ByteBuffer          
 * @param delimit
 *          
 * @return 
 */
public static String getString(ByteBuffer buf, byte delimit) {
    baos.reset();
    while (buf.hasRemaining()) {
        byte b = buf.get();
        if (b == delimit)
            return getString(baos.toByteArray());
        else
            baos.write(b);
    }
    return getString(baos.toByteArray());
}