Example usage for java.nio ByteBuffer getInt

List of usage examples for java.nio ByteBuffer getInt

Introduction

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

Prototype

public abstract int getInt();

Source Link

Document

Returns the int at the current position and increases the position by 4.

Usage

From source file:com.ottogroup.bi.spqr.pipeline.statistics.MicroPipelineStatistics.java

/**
 * Converts the provided byte array into a {@link MicroPipelineStatistics} representation
 * @param statsContent/*from   w w w .j av  a  2 s.c o  m*/
 * @return
 */
public static MicroPipelineStatistics fromByteArray(final byte[] statsContent) {

    MicroPipelineStatistics stats = new MicroPipelineStatistics();
    ByteBuffer buf = ByteBuffer.wrap(statsContent);

    // ensure that the order is the same as when populating the array 
    stats.setNumOfMessages(buf.getInt());
    stats.setStartTime(buf.getLong());
    stats.setEndTime(buf.getLong());
    stats.setMinDuration(buf.getInt());
    stats.setMaxDuration(buf.getInt());
    stats.setAvgDuration(buf.getInt());
    stats.setMinSize(buf.getInt());
    stats.setMaxSize(buf.getInt());
    stats.setAvgSize(buf.getInt());
    stats.setErrors(buf.getInt());

    byte[] procNodeId = new byte[buf.getInt()];
    buf.get(procNodeId);

    byte[] pipelineId = new byte[buf.getInt()];
    buf.get(pipelineId);

    byte[] componentId = new byte[buf.getInt()];
    buf.get(componentId);

    stats.setProcessingNodeId(new String(procNodeId));
    stats.setPipelineId(new String(pipelineId));
    stats.setComponentId(new String(componentId));

    return stats;
}

From source file:org.opensha.commons.util.XMLUtils.java

public static int[] intArrayFromXML(Element intArrayEl) {
    byte[] data = byteArrayFromXML(intArrayEl);

    Preconditions.checkState(data.length % 4 == 0, "binary data not a multiple of 4 bits");
    int size = data.length / 4;

    ByteBuffer buf = ByteBuffer.wrap(data);
    int[] array = new int[size];
    for (int i = 0; i < size; i++)
        array[i] = buf.getInt();

    return array;
}

From source file:com.healthmarketscience.jackcess.impl.office.EncryptionHeader.java

public static EncryptionHeader read(ByteBuffer encProvBuf, Set<CryptoAlgorithm> validCryptoAlgos,
        Set<HashAlgorithm> validHashAlgos) {
    // read length of header
    int headerLen = encProvBuf.getInt();

    // read header (temporarily narrowing buf to header)
    int curLimit = encProvBuf.limit();
    int curPos = encProvBuf.position();
    encProvBuf.limit(curPos + headerLen);
    EncryptionHeader header = new EncryptionHeader(encProvBuf);

    // verify parameters
    if (!validCryptoAlgos.contains(header.getCryptoAlgorithm())) {
        throw new IllegalStateException(header + " crypto algorithm must be one of " + validCryptoAlgos);
    }//from ww w .  ja  v a  2s.  com

    if (!validHashAlgos.contains(header.getHashAlgorithm())) {
        throw new IllegalStateException(header + " hash algorithm must be one of " + validHashAlgos);
    }

    int keySize = header.getKeySize();
    if (!header.getCryptoAlgorithm().isValidKeySize(keySize)) {
        throw new IllegalStateException(header + " key size is outside allowable range");
    }
    if ((keySize % 8) != 0) {
        throw new IllegalStateException(header + " key size must be multiple of 8");
    }

    // move to after header
    encProvBuf.limit(curLimit);
    encProvBuf.position(curPos + headerLen);

    return header;
}

From source file:org.zuinnote.hadoop.bitcoin.format.BitcoinUtil.java

/**
* Converts a variable length integer (https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer) to long
*
* @param varInt byte array containing variable length integer
* 
* @return long corresponding to variable length integer
*
*//* w ww .  j a va  2s.  co  m*/

public static long getVarInt(byte[] varInt) {
    long result = 0;
    if (varInt.length == 0)
        return result;
    int unsignedByte = varInt[0] & 0xFF;
    if (unsignedByte < 0xFD)
        return unsignedByte;
    int intSize = 0;
    if (unsignedByte == 0xFD)
        intSize = 3;
    else if (unsignedByte == 0xFE)
        intSize = 5;
    else if (unsignedByte == 0XFF)
        intSize = 9;
    byte[] rawDataInt = reverseByteArray(Arrays.copyOfRange(varInt, 1, intSize));
    ByteBuffer byteBuffer = ByteBuffer.wrap(rawDataInt);
    if (intSize == 3)
        result = byteBuffer.getShort();
    else if (intSize == 5)
        result = byteBuffer.getInt();
    else if (intSize == 9)
        result = byteBuffer.getLong(); // Need to handle sign - available only in JDK8
    return result;
}

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

/**
 * @param bytes/*from   w  w  w.ja  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:edu.umass.cs.gigapaxos.paxosutil.PaxosPacketDemultiplexerFast.java

private static boolean isByteable(byte[] bytes) {
    ByteBuffer bbuf;
    int type = -1;
    if ((bbuf = ByteBuffer.wrap(bytes, 0, 8)).getInt() == PaxosPacket.PaxosPacketType.PAXOS_PACKET.getInt()
            && ((type = bbuf.getInt()) == PaxosPacket.PaxosPacketType.REQUEST.getInt()
                    || (type == PaxosPacket.PaxosPacketType.ACCEPT.getInt())
                    || type == PaxosPacketType.BATCHED_COMMIT.getInt()
                    || type == PaxosPacketType.BATCHED_ACCEPT_REPLY.getInt()))
        return true;
    assert (type != PaxosPacket.PaxosPacketType.PROPOSAL.getInt());
    return false;
}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.Utils.DataManipulation.java

/**
 * Creates an int starting from two given shorts. An int is composed of four
 * bytes. Numbering the four bytes from 1 (the most important) to 4 (the
 * least important), the converted int will be formed placing the two given
 * bytes in the two less important places of the created int.
 * <p>//w w w .  j  av a 2  s  .co m
 * More formally the low byte will be placed in position 4, the high byte
 * will be placed in position 3, while positions 1 and 2 will be set at
 * zero.
 * 
 * @param hb
 *            the high byte.
 * @param lb
 *            the low byte.
 * @return the result int.
 */
public static int toIntFromShort(byte hb, byte lb) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0x00, 0x00, hb, lb });
    return bb.getInt();
}

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

public static List<ByteBuffer> createBufferList(ByteBuffer bb, int size) {
    List<ByteBuffer> list = new ArrayList<ByteBuffer>(size);
    for (int i = 0; i < size; i++) {
        list.add(fillBuffer(getBytes(bb, bb.getInt())));
    }//  w  w w.j a v a2  s .  c om
    return list;
}

From source file:org.hobbit.core.rabbit.RabbitMQUtils.java

/**
 * Reads a byte array from the given buffer assuming that it is preceded by
 * an int value containing the length of the byte array.
 *
 * @param buffer//from  ww w. ja va  2 s .c  o m
 *            the buffer containing an int containing the length of the byte
 *            array followed by the byte array itself
 * @return the byte array or null if the given byte array is null
 */
public static byte[] readByteArray(ByteBuffer buffer) {
    if (buffer == null) {
        return null;
    } else {
        if (buffer.remaining() < Integer.BYTES) {
            return new byte[0];
        } else {
            int length = buffer.getInt();
            byte[] data = new byte[length];
            buffer.get(data, 0, data.length);
            return data;
        }
    }
}

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

public static byte[] parseMessageResponse(byte[] resp) throws BufferUnderflowException {
    ByteBuffer buffer = ByteBuffer.wrap(resp);
    byte[] encfile = null;

    int errCode = buffer.getInt();
    if (errCode != 1)
        return null;

    int fileLen = buffer.getInt();
    encfile = new byte[fileLen];
    try {//from  ww w. j a  va2s.  c  o  m
        buffer.get(encfile);
        return encfile;
    } catch (BufferUnderflowException e) {
        e.printStackTrace();
        return null;
    }
}