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:de.rwhq.btree.InnerNode.java

private Integer getPageIdForKey(final K key) {
    final ByteBuffer buf = rawPage.bufferForReading(getOffsetOfPageIdForKey(key));
    return buf.getInt();
}

From source file:de.rwhq.btree.LeafNode.java

/** @return id of the next leaf or null */
public Integer getNextLeafId() {
    final ByteBuffer buffer = rawPage().bufferForReading(Header.NEXT_LEAF_ID.getOffset());
    final Integer result = buffer.getInt();
    return result == 0 ? null : result;
}

From source file:com.linkedin.pinot.common.utils.DataTable.java

private void deserializeDataTable(ByteBuffer input) {
    numRows = input.getInt();
    numCols = input.getInt();//from   w ww .ja  v  a2s. c o m
    // READ dictionary
    final int dictionaryStart = input.getInt();
    final int dictionaryLength = input.getInt();
    final int metadataStart = input.getInt();
    final int metadataLength = input.getInt();
    final int schemaStart = input.getInt();
    final int schemaLength = input.getInt();
    final int fixedDataStart = input.getInt();
    final int fixedDataLength = input.getInt();
    final int variableDataStart = input.getInt();
    final int variableDataLength = input.getInt();

    // READ DICTIONARY

    byte[] dictionaryBytes = null;
    if (dictionaryLength != 0) {
        dictionaryBytes = new byte[dictionaryLength];
        input.position(dictionaryStart);
        input.get(dictionaryBytes);
        dictionary = (Map<String, Map<Integer, String>>) deserializeDictionary(dictionaryBytes);
    } else {
        dictionary = new HashMap<String, Map<Integer, String>>(1);
    }

    // READ METADATA
    byte[] metadataBytes;
    if (metadataLength != 0) {
        metadataBytes = new byte[metadataLength];
        input.position(metadataStart);
        input.get(metadataBytes);
        metadata = (Map<String, String>) deserializeMetadata(metadataBytes);
    } else {
        metadata = new HashMap<String, String>();
    }

    // READ SCHEMA
    byte[] schemaBytes;

    if (schemaLength != 0) {
        schemaBytes = new byte[schemaLength];
        input.position(schemaStart);
        input.get(schemaBytes);
        schema = DataSchema.fromBytes(schemaBytes);
        columnOffsets = computeColumnOffsets(schema);
    }

    // READ FIXED SIZE DATA BYTES
    if (fixedDataLength != 0) {
        fixedSizeDataBytes = new byte[fixedDataLength];
        input.position(fixedDataStart);
        input.get(fixedSizeDataBytes);
        fixedSizeData = ByteBuffer.wrap(fixedSizeDataBytes);
    }

    // READ VARIABLE SIZE DATA BYTES
    if (variableDataLength != 0) {
        variableSizeDataBytes = new byte[variableDataLength];
        input.position(variableDataStart);
        input.get(variableSizeDataBytes);
        variableSizeData = ByteBuffer.wrap(variableSizeDataBytes);
    }
}

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

private byte[] handleResponseExceptions(byte[] resp, int errMax)
        throws ExchangeException, MessageNotFoundException {

    int firstInt = 0;
    ByteBuffer result = ByteBuffer.wrap(resp);
    if (mCancelable)
        throw new ExchangeException(mCtx.getString(R.string.error_WebCancelledByUser));
    else if (resp == null)
        throw new ExchangeException(mCtx.getString(R.string.error_ServerNotResponding));
    else if (resp.length < 4)
        throw new ExchangeException(mCtx.getString(R.string.error_ServerNotResponding));
    else {//from w  w w . jav a2 s.c o m
        firstInt = result.getInt();
        byte[] bytes = new byte[result.remaining()];
        result.get(bytes);
        if (firstInt <= errMax) { // error int
            MyLog.e(TAG, "server error code: " + firstInt);

            // first, look for expected error string codes from 3rd-party
            handleMessagingErrorCodes(resp);

            // second, use message directly from server
            throw new ExchangeException(
                    String.format(mCtx.getString(R.string.error_ServerAppMessage), new String(bytes).trim()));
        }
        // else strip off server version
        mLatestServerVersion = firstInt;
        return bytes;
    }
}

From source file:de.rwhq.btree.InnerNode.java

@Override
public K getFirstLeafKey() {
    final ByteBuffer buf = rawPage().bufferForReading(getOffsetForLeftPageIdOfKey(0));
    return getPageForPageId(buf.getInt()).getFirstLeafKey();
}

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:/*from   w  w w . ja  v a 2  s . 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:org.carbondata.query.aggregator.impl.CustomAggregatorHelper.java

/**
 * Below method will be used to read the level files
 *
 * @param memberFile//from   w  w w  .j  a  v a 2 s . c o  m
 * @param fileName
 * @throws IOException
 */
private void readLevelFileAndUpdateCache(File memberFile, String fileName) throws IOException {
    FileInputStream fos = null;
    FileChannel fileChannel = null;
    try {
        // create an object of FileOutputStream
        fos = new FileInputStream(memberFile);

        fileChannel = fos.getChannel();
        Map<Integer, String> memberMap = surrogateKeyMap.get(fileName);

        if (null == memberMap) {
            memberMap = new HashMap<Integer, String>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
            surrogateKeyMap.put(fileName, memberMap);
        }

        long size = fileChannel.size();
        int maxKey = 0;
        ByteBuffer rowlengthToRead = null;
        int len = 0;
        ByteBuffer row = null;
        int toread = 0;
        byte[] bb = null;
        String value = null;
        int surrogateValue = 0;

        boolean enableEncoding = Boolean.valueOf(
                CarbonProperties.getInstance().getProperty(CarbonCommonConstants.ENABLE_BASE64_ENCODING,
                        CarbonCommonConstants.ENABLE_BASE64_ENCODING_DEFAULT));

        while (fileChannel.position() < size) {
            rowlengthToRead = ByteBuffer.allocate(4);
            fileChannel.read(rowlengthToRead);
            rowlengthToRead.rewind();
            len = rowlengthToRead.getInt();
            if (len == 0) {
                continue;
            }

            row = ByteBuffer.allocate(len);
            fileChannel.read(row);
            row.rewind();
            toread = row.getInt();
            bb = new byte[toread];
            row.get(bb);

            if (enableEncoding) {
                value = new String(Base64.decodeBase64(bb), Charset.defaultCharset());
            } else {
                value = new String(bb, Charset.defaultCharset());
            }

            surrogateValue = row.getInt();
            memberMap.put(surrogateValue, value);

            // check if max key is less than Surrogate key then update the max key
            if (maxKey < surrogateValue) {
                maxKey = surrogateValue;
            }
        }

    } finally {
        CarbonUtil.closeStreams(fileChannel, fos);
    }
}

From source file:com.offbynull.portmapper.natpmp.NatPmpResponse.java

/**
 * Constructs a {@link NatPmpResponse} object by parsing a buffer.
 * @param buffer buffer containing NAT-PMP response data
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 * @throws IllegalArgumentException if the version doesn't match the expected version (must always be {@code 0}), or if the op is
 * {@code < 128}, or if there's an unsuccessful/unrecognized result code
 *///from   www.j  a  v  a 2s.  com
NatPmpResponse(ByteBuffer buffer) {
    Validate.notNull(buffer);

    if (buffer.remaining() < 2) {
        throw new IllegalArgumentException("Bad packet size: " + buffer.remaining());
    }

    int version = buffer.get() & 0xFF;
    Validate.isTrue(version == 0, "Unknown version: %d", version);

    op = buffer.get() & 0xFF;
    Validate.isTrue(op >= 128, "Op must be >= 128: %d", op);

    int resultCodeNum = buffer.getShort() & 0xFFFF;
    NatPmpResultCode[] resultCodes = NatPmpResultCode.values();

    Validate.isTrue(resultCodeNum < resultCodes.length, "Unknown result code encountered: %d", resultCodeNum);
    Validate.isTrue(resultCodeNum == NatPmpResultCode.SUCCESS.ordinal(), "Unsuccessful result code: %s [%s]",
            resultCodes[resultCodeNum].toString(), resultCodes[resultCodeNum].getMessage());

    secondsSinceStartOfEpoch = buffer.getInt() & 0xFFFFFFFFL;
}

From source file:tor.TorCircuit.java

public boolean handleCell(Cell c) throws IOException {
    boolean handled = false;

    if (receiveWindow < 900) {
        //System.out.println("sent SENDME (CIRCUIT): " + receiveWindow);
        send(null, RELAY_SENDME, false, (short) 0);
        receiveWindow += 100;/*from ww  w . j  av  a2s  . c  o  m*/
    }

    if (state == STATES.DESTROYED) {
        log.error("Trying to use destroyed circuit");
        throw new RuntimeException("Trying to use destroyed circuit");
    }

    if (c.cmdId == Cell.CREATED) // create
    {
        handleCreated(c.payload);

        if (!circuitToBuild.isEmpty()) {// more?
            boolean block = blocking;
            setBlocking(false);
            extend(circuitToBuild.removeFirst());
            setBlocking(block);
        }

        handled = true;
    } else if (c.cmdId == Cell.RELAY_EARLY || c.cmdId == Cell.PADDING || c.cmdId == Cell.VPADDING) { // these are used in deanon attacks
        log.error("WARNING**** cell CMD " + c.cmdId + " received in - Possible DEANON attack!!: Route: "
                + hops.toArray());
    } else if (c.cmdId == Cell.RELAY) // relay cell
    {
        // cell decrypt logic - decrypt from each hop in turn checking recognised and digest until success
        // remember, we can receive cells from intermediate hops, so it's an iterative decrypt and check if successful
        // for each hop.
        int cellFromHop = -1;
        for (int di = 0; di < hops.size(); di++) { // loop through circuit hops
            TorHop hop = hops.get(di);
            c.payload = hop.decrypt(c.payload); // decrypt for this hop

            if (c.payload[1] == 0 && c.payload[2] == 0) { // are recognised bytes set to zero?
                byte nodgrl[] = relayCellRemoveDigest(c.payload); // remove digest from cell
                byte hash[] = Arrays.copyOfRange(c.payload, 5, 9); // put digest from cell into hash
                byte[] digest;

                try { // calculate the digest that we thing it should be
                      // must clone here to stop clobbering original
                    digest = ((MessageDigest) hop.db_md.clone()).digest(nodgrl);
                } catch (CloneNotSupportedException e) {
                    throw new RuntimeException(e);
                }

                // compare our calculations with digest in cell - if right, we've decrypted correctly
                if (Arrays.equals(hash, Arrays.copyOfRange(digest, 0, 4))) {
                    hop.db_md.update(nodgrl); // update digest for hop for future cells
                    cellFromHop = di; // hop number this cell is from
                    break;
                }
            }
        }

        if (cellFromHop == -1) {
            log.warn("unrecognised cell - didn't decrypt");
            return false;
        }
        // successfully decrypted - now let's proceed

        // decode relay header
        ByteBuffer buf = ByteBuffer.wrap(c.payload);
        int cmd = buf.get();
        if (buf.getShort() != 0) {
            log.warn("invalid relay cell");
            return false;
        }
        int streamid = buf.getShort();

        int digest = buf.getInt();
        int length = buf.getShort();
        byte data[] = Arrays.copyOfRange(c.payload, 1 + 2 + 2 + 4 + 2, 1 + 2 + 2 + 4 + 2 + length);

        // now pass cell off to handler function below
        handled = handleRelayCell(cmd, streamid, cellFromHop, data);

    } else if (c.cmdId == Cell.DESTROY) {
        log.info("Circuit destroyed " + circId);
        log.info("Reason: " + DESTROY_ERRORS[c.payload[0]]);
        for (TorStream s : streams.values()) {
            s.notifyDisconnect();
        }
        setState(STATES.DESTROYED);
        handled = true;
    }

    return handled;
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void event_handler() {
    DataInputStream din = new DataInputStream(eventSocketIn);
    while (true) {
        try {/*  w w w  .j av  a  2s .  c o m*/
            // receive STX (1 byte) + eventcode (2) + length (4)
            byte[] start = new byte[7];
            try {
                //noinspection ResultOfMethodCallIgnored
                din.read(start);
            } catch (IOException e) {
                if (!disconnecting) {
                    signal("broken", "Server connection broken.");
                    _close();
                }
                return;
            }
            if (start[0] != daemon.STX) {
                // Every event starts with STX. Else, something's wrong.
                if (!disconnecting) {
                    signal("broken", "Server connection broken.");
                    _close();
                }
                return;
            }
            byte[] slice = Arrays.copyOfRange(start, 3, 7);
            ByteBuffer bb = ByteBuffer.wrap(slice);
            bb.order(ByteOrder.BIG_ENDIAN);

            // Get length, allocate byte buffer.
            int length = bb.getInt();
            byte[] buf = new byte[length];

            // Read length bytes and store them in buf.
            din.readFully(buf, 0, length);

            boolean should_signal = true;
            String event = null;
            Object data = null;
            try {
                // Stackoverflow magic to convert 2 bytes to int which can be compared in
                // daemon.command2event().
                int eventcode = ((start[1] & 0xff) << 8) | (start[2] & 0x00ff);
                event = daemon.command2event(eventcode);
                // serialized or raw data?
                if (daemon.eventNeedsUnserialize(event)) {
                    Unpickler unpickler = new Unpickler();
                    data = unpickler.loads(buf);
                } else {
                    data = buf;
                }
            } catch (Exception e) {
                // Garbled event
                should_signal = false;
            }
            if (should_signal) {
                signal(event, data);
            }
        } catch (Exception e) {
            if (!disconnecting) {
                signal("broken", "Server connection broken.");
                _close();
            }
            return;
        }
    }
}