Example usage for java.nio ByteBuffer rewind

List of usage examples for java.nio ByteBuffer rewind

Introduction

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

Prototype

public final Buffer rewind() 

Source Link

Document

Rewinds this buffer.

Usage

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

private static PaxosPacket toPaxosPacket(byte[] bytes)
        throws UnsupportedEncodingException, UnknownHostException {
    assert (bytes != null);
    ByteBuffer bbuf = ByteBuffer.wrap(bytes);

    PaxosPacket.PaxosPacketType type = bbuf.getInt() == PaxosPacketType.PAXOS_PACKET.getInt()
            ? PaxosPacketType.getPaxosPacketType(bbuf.getInt())
            : null;//from   www.  j av  a 2s  .c o  m

    if (type == null)
        fatal(bytes);

    // bbuf = ByteBuffer.wrap(bytes);
    bbuf.rewind();

    PaxosPacket paxosPacket = null;
    switch (type) {
    case REQUEST:
        // log.info("before new RequestPacket(ByteBuffer)");
        paxosPacket = new RequestPacket(bbuf);
        // log.info("after new RequestPacket(ByteBuffer)");
        break;
    case ACCEPT:
        paxosPacket = new AcceptPacket(bbuf);
        break;
    case BATCHED_COMMIT:
        paxosPacket = new BatchedCommit(bbuf);
        break;
    case BATCHED_ACCEPT_REPLY:
        paxosPacket = new BatchedAcceptReply(bbuf);
        break;

    default:
        assert (false);
    }
    return paxosPacket;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl.java

private static Credentials convertCredentialsFromByteBuffer(ByteBuffer appAttemptTokens) {
    DataInputByteBuffer dibb = new DataInputByteBuffer();
    try {/*from  www  . ja v  a  2  s .c  o  m*/
        Credentials credentials = null;
        if (appAttemptTokens != null) {
            credentials = new Credentials();
            appAttemptTokens.rewind();
            dibb.reset(appAttemptTokens);
            credentials.readTokenStorageStream(dibb);
        }
        return credentials;
    } catch (IOException e) {
        LOG.error("Failed to convert Credentials from ByteBuffer.");
        assert false;
        return null;
    } finally {
        IOUtils.closeStream(dibb);
    }
}

From source file:net.servicestack.client.Utils.java

public static byte[] toGuidBytes(UUID theUuid) {
    ByteBuffer first8 = ByteBuffer.allocate(8);
    first8.putLong(theUuid.getMostSignificantBits());
    first8.rewind();

    byte[] first4 = new byte[4];
    first8.get(first4);//from   ww w  . j  a  v a2 s. c o  m
    reverse(first4);

    byte[] second2 = new byte[2];
    first8.get(second2);
    reverse(second2);

    byte[] third2 = new byte[2];
    first8.get(third2);
    reverse(third2);

    ByteBuffer converted16 = ByteBuffer.allocate(16).put(first4).put(second2).put(third2);

    ByteBuffer last8 = ByteBuffer.allocate(8);
    last8.putLong(theUuid.getLeastSignificantBits());
    last8.rewind();

    converted16.put(last8);

    return converted16.array();
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

public static ByteBuffer bytebuffer(Long val) {
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(val);
    return (ByteBuffer) buf.rewind();
}

From source file:org.apache.myriad.state.utils.ByteBufferSupport.java

public static ByteBuffer toByteBuffer(NodeTask nt) {
    // Determine the size of ByteBuffer to allocate
    // The ServiceResourceProfile toString() returns Json, if this ever changes then this
    // will fail. Json is expected.
    byte[] profile = toBytes(nt.getProfile().toString());
    int size = profile.length + INT_SIZE;

    Constraint constraint = nt.getConstraint();
    Constraint.Type type = constraint == null ? Type.NULL : constraint.getType();
    size += INT_SIZE;/*from  w  ww .j  a v  a  2s .  c  om*/

    byte[] constraintBytes = ZERO_BYTES;
    if (constraint != null) {
        constraintBytes = toBytes(constraint.toString());
        size += constraintBytes.length + INT_SIZE;
    } else {
        size += INT_SIZE;
    }

    byte[] hostname = toBytes(nt.getHostname());
    size += hostname.length + INT_SIZE;

    if (nt.getSlaveId() != null) {
        size += nt.getSlaveId().getSerializedSize() + INT_SIZE;
    } else {
        size += INT_SIZE;
    }

    if (nt.getTaskStatus() != null) {
        size += nt.getTaskStatus().getSerializedSize() + INT_SIZE;
    } else {
        size += INT_SIZE;
    }

    if (nt.getExecutorInfo() != null) {
        size += nt.getExecutorInfo().getSerializedSize() + INT_SIZE;
    } else {
        size += INT_SIZE;
    }

    byte[] taskPrefixBytes = ZERO_BYTES;
    if (nt.getTaskPrefix() != null) {
        taskPrefixBytes = toBytes(nt.getTaskPrefix());
        size += taskPrefixBytes.length + INT_SIZE;
    }

    // Allocate and populate the buffer.
    ByteBuffer bb = createBuffer(size);
    putBytes(bb, profile);
    bb.putInt(type.ordinal());
    putBytes(bb, constraintBytes);
    putBytes(bb, hostname);
    putBytes(bb, getSlaveBytes(nt));
    putBytes(bb, getTaskBytes(nt));
    putBytes(bb, getExecutorInfoBytes(nt));
    putBytes(bb, taskPrefixBytes);
    // Make sure the buffer is at the beginning
    bb.rewind();
    return bb;
}

From source file:org.skife.muckery.mappy.ByteUtils.java

/**
 * If we have no more room in the current buffer, then double our capacity
 * and copy the current buffer to the new one.
 * <p/>/*w  w w. j av  a2s .com*/
 * Note: the new buffer is allocated using ByteBuffer.allocate.
 *
 * @param buffer The buffer from which to copy the contents
 * @param newCapacity The new capacity size
 */

public static ByteBuffer expand(ByteBuffer buffer, int newCapacity) {
    if (newCapacity < buffer.capacity())
        throw new IllegalArgumentException("newCapacity (" + newCapacity
                + ") must be larger than existing capacity (" + buffer.capacity() + ")");

    ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);
    int position = buffer.position();
    buffer.rewind();
    newBuffer.put(buffer);
    newBuffer.position(position);
    return newBuffer;
}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Generates the digest value for the SOAP secure header.
 * <p>/* w  w w .j a v a2 s  .c  om*/
 * This is a codified password, with the help of the date and nonce values.
 * Both of these values should be found on the SOAP secure header.
 *
 * @param password
 *            password to digest
 * @param date
 *            date used on the SOAP header
 * @param nonce
 *            nonce used on the SOAP header
 * @return the digested password
 * @throws UnsupportedEncodingException
 *             if the UTF-8 encoding is not supported
 */
private static final String generateDigest(final String password, final String date, final String nonce)
        throws UnsupportedEncodingException {
    final ByteBuffer buf; // Buffers storing the data to digest
    byte[] toHash; // Bytes to generate the hash

    // Fills buffer with data to digest
    buf = ByteBuffer.allocate(1000);
    buf.put(Base64.decodeBase64(nonce));
    buf.put(date.getBytes("UTF-8"));
    buf.put(password.getBytes("UTF-8"));

    // Initializes hash bytes to the correct size
    toHash = new byte[buf.position()];
    buf.rewind();

    // Copies bytes from the buffer to the hash bytes
    buf.get(toHash);

    return Base64.encodeBase64String(DigestUtils.sha1(toHash));
}

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

/**
 * Allocate a buffer and fill it from a channel. The returned
 * buffer will be rewound to the begining.
 * @return Buffer containing size bytes from the channel.
 * @throws IOException if the channel read does.
 * @throws EOFException if a end of stream is encountered
 *    before the full size is read./*from  ww w .j a  va 2 s.co  m*/
 */
public static ByteBuffer allocateAndReadAll(int size, ReadableByteChannel channel) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(size);
    int justRead;
    int totalRead = 0;

    // FIXME, this will be a tight loop if the channel is non-blocking...
    while (totalRead < size) {
        logger.debug("reading totalRead={}", totalRead);
        if ((justRead = channel.read(buf)) < 0)
            throw new EOFException("Unexpected end of stream after reading " + totalRead + " bytes");
        totalRead += justRead;
    }
    buf.rewind();
    return buf;
}

From source file:net.servicestack.client.Utils.java

public static UUID fromGuidBytes(byte[] guidBytes) {
    ByteBuffer buf = ByteBuffer.wrap(guidBytes);

    byte[] first4 = new byte[4];
    buf.get(first4);/*from  w w w  . j  a  v a  2  s .  com*/
    reverse(first4);

    byte[] second2 = new byte[2];
    buf.get(second2);
    reverse(second2);

    byte[] third2 = new byte[2];
    buf.get(third2);
    reverse(third2);

    long lsb = buf.getLong();

    buf = ByteBuffer.wrap(new byte[8]).put(first4).put(second2).put(third2);

    buf.rewind();
    long msb = buf.getLong();

    return new UUID(msb, lsb);
}

From source file:org.deeplearning4j.scaleout.api.ir.ParameterVectorUpdateable.java

@Override
public void fromBytes(ByteBuffer b) {
    b.rewind();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(b.array()));
    try {/*  ww  w  . j  a va 2  s .  c  om*/
        paramMessage = Nd4j.read(dis);
    } catch (IOException e) {
        e.printStackTrace();
    }

    IOUtils.closeQuietly(dis);

}