Example usage for java.nio ByteBuffer putInt

List of usage examples for java.nio ByteBuffer putInt

Introduction

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

Prototype

public abstract ByteBuffer putInt(int value);

Source Link

Document

Writes the given int to the current position and increases the position by 4.

Usage

From source file:com.healthmarketscience.jackcess.impl.TableImpl.java

/**
 * Create the usage map definition page buffer.  The "used pages" map is in
 * row 0, the "pages with free space" map is in row 1.  Index usage maps are
 * in subsequent rows./*  ww w  . ja v  a  2  s .c o m*/
 */
private static void createUsageMapDefinitionBuffer(TableCreator creator) throws IOException {
    List<ColumnBuilder> lvalCols = creator.getLongValueColumns();

    // 2 table usage maps plus 1 for each index and 2 for each lval col
    int indexUmapEnd = 2 + creator.getIndexCount();
    int umapNum = indexUmapEnd + (lvalCols.size() * 2);

    JetFormat format = creator.getFormat();
    int umapRowLength = format.OFFSET_USAGE_MAP_START + format.USAGE_MAP_TABLE_BYTE_LENGTH;
    int umapSpaceUsage = getRowSpaceUsage(umapRowLength, format);
    PageChannel pageChannel = creator.getPageChannel();
    int umapPageNumber = PageChannel.INVALID_PAGE_NUMBER;
    ByteBuffer umapBuf = null;
    int freeSpace = 0;
    int rowStart = 0;
    int umapRowNum = 0;

    for (int i = 0; i < umapNum; ++i) {

        if (umapBuf == null) {

            // need new page for usage maps
            if (umapPageNumber == PageChannel.INVALID_PAGE_NUMBER) {
                // first umap page has already been reserved
                umapPageNumber = creator.getUmapPageNumber();
            } else {
                // need another umap page
                umapPageNumber = creator.reservePageNumber();
            }

            freeSpace = format.DATA_PAGE_INITIAL_FREE_SPACE;

            umapBuf = pageChannel.createPageBuffer();
            umapBuf.put(PageTypes.DATA);
            umapBuf.put((byte) 0x1); //Unknown
            umapBuf.putShort((short) freeSpace); //Free space in page
            umapBuf.putInt(0); //Table definition
            umapBuf.putInt(0); //Unknown
            umapBuf.putShort((short) 0); //Number of records on this page

            rowStart = findRowEnd(umapBuf, 0, format) - umapRowLength;
            umapRowNum = 0;
        }

        umapBuf.putShort(getRowStartOffset(umapRowNum, format), (short) rowStart);

        if (i == 0) {

            // table "owned pages" map definition
            umapBuf.put(rowStart, UsageMap.MAP_TYPE_REFERENCE);

        } else if (i == 1) {

            // table "free space pages" map definition
            umapBuf.put(rowStart, UsageMap.MAP_TYPE_INLINE);

        } else if (i < indexUmapEnd) {

            // index umap
            int indexIdx = i - 2;
            IndexBuilder idx = creator.getIndexes().get(indexIdx);

            // allocate root page for the index
            int rootPageNumber = pageChannel.allocateNewPage();

            // stash info for later use
            TableCreator.IndexState idxState = creator.getIndexState(idx);
            idxState.setRootPageNumber(rootPageNumber);
            idxState.setUmapRowNumber((byte) umapRowNum);
            idxState.setUmapPageNumber(umapPageNumber);

            // index map definition, including initial root page
            umapBuf.put(rowStart, UsageMap.MAP_TYPE_INLINE);
            umapBuf.putInt(rowStart + 1, rootPageNumber);
            umapBuf.put(rowStart + 5, (byte) 1);

        } else {

            // long value column umaps
            int lvalColIdx = i - indexUmapEnd;
            int umapType = lvalColIdx % 2;
            lvalColIdx /= 2;

            ColumnBuilder lvalCol = lvalCols.get(lvalColIdx);
            TableCreator.ColumnState colState = creator.getColumnState(lvalCol);

            umapBuf.put(rowStart, UsageMap.MAP_TYPE_INLINE);

            if ((umapType == 1) && (umapPageNumber != colState.getUmapPageNumber())) {
                // we want to force both usage maps for a column to be on the same
                // data page, so just discard the previous one we wrote
                --i;
                umapType = 0;
            }

            if (umapType == 0) {
                // lval column "owned pages" usage map
                colState.setUmapOwnedRowNumber((byte) umapRowNum);
                colState.setUmapPageNumber(umapPageNumber);
            } else {
                // lval column "free space pages" usage map (always on same page)
                colState.setUmapFreeRowNumber((byte) umapRowNum);
            }
        }

        rowStart -= umapRowLength;
        freeSpace -= umapSpaceUsage;
        ++umapRowNum;

        if ((freeSpace <= umapSpaceUsage) || (i == (umapNum - 1))) {
            // finish current page
            umapBuf.putShort(format.OFFSET_FREE_SPACE, (short) freeSpace);
            umapBuf.putShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE, (short) umapRowNum);
            pageChannel.writePage(umapBuf, umapPageNumber);
            umapBuf = null;
        }
    }
}

From source file:com.healthmarketscience.jackcess.Table.java

/**
 * Create a new data page/*from   w  w w. ja  v  a  2  s . c o m*/
 * @return Page number of the new page
 */
private ByteBuffer newDataPage() throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating new data page");
    }
    ByteBuffer dataPage = _addRowBufferH.setNewPage(getPageChannel());
    dataPage.put(PageTypes.DATA); //Page type
    dataPage.put((byte) 1); //Unknown
    dataPage.putShort((short) getFormat().DATA_PAGE_INITIAL_FREE_SPACE); //Free space in this page
    dataPage.putInt(_tableDefPageNumber); //Page pointer to table definition
    dataPage.putInt(0); //Unknown
    dataPage.putShort((short) 0); //Number of rows on this page
    int pageNumber = _addRowBufferH.getPageNumber();
    getPageChannel().writePage(dataPage, pageNumber);
    _ownedPages.addPageNumber(pageNumber);
    _freeSpacePages.addPageNumber(pageNumber);
    return dataPage;
}

From source file:hivemall.GeneralLearnerBaseUDTF.java

protected void recordTrainSampleToTempFile(@Nonnull final FeatureValue[] featureVector, final float target)
        throws HiveException {
    if (iterations == 1) {
        return;/*from  w w w  .  ja  v  a  2s  . c om*/
    }

    ByteBuffer buf = inputBuf;
    NioStatefulSegment dst = fileIO;

    if (buf == null) {
        final File file;
        try {
            file = File.createTempFile("hivemall_general_learner", ".sgmt");
            file.deleteOnExit();
            if (!file.canWrite()) {
                throw new UDFArgumentException("Cannot write a temporary file: " + file.getAbsolutePath());
            }
            logger.info("Record training samples to a file: " + file.getAbsolutePath());
        } catch (IOException ioe) {
            throw new UDFArgumentException(ioe);
        } catch (Throwable e) {
            throw new UDFArgumentException(e);
        }
        this.inputBuf = buf = ByteBuffer.allocateDirect(1024 * 1024); // 1 MB
        this.fileIO = dst = new NioStatefulSegment(file, false);
    }

    int featureVectorBytes = 0;
    for (FeatureValue f : featureVector) {
        if (f == null) {
            continue;
        }
        int featureLength = f.getFeatureAsString().length();

        // feature as String (even if it is Text or Integer)
        featureVectorBytes += SizeOf.CHAR * featureLength;

        // NIOUtils.putString() first puts the length of string before string itself
        featureVectorBytes += SizeOf.INT;

        // value
        featureVectorBytes += SizeOf.DOUBLE;
    }

    // feature length, feature 1, feature 2, ..., feature n, target
    int recordBytes = SizeOf.INT + featureVectorBytes + SizeOf.FLOAT;
    int requiredBytes = SizeOf.INT + recordBytes; // need to allocate space for "recordBytes" itself

    int remain = buf.remaining();
    if (remain < requiredBytes) {
        writeBuffer(buf, dst);
    }

    buf.putInt(recordBytes);
    buf.putInt(featureVector.length);
    for (FeatureValue f : featureVector) {
        writeFeatureValue(buf, f);
    }
    buf.putFloat(target);
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Writes the header info for a long value page.
 *///from ww w .j av a2  s.c o m
private void writeLongValueHeader(ByteBuffer lvalPage) {
    lvalPage.put(PageTypes.DATA); //Page type
    lvalPage.put((byte) 1); //Unknown
    lvalPage.putShort((short) getFormat().DATA_PAGE_INITIAL_FREE_SPACE); //Free space
    lvalPage.put((byte) 'L');
    lvalPage.put((byte) 'V');
    lvalPage.put((byte) 'A');
    lvalPage.put((byte) 'L');
    lvalPage.putInt(0); //unknown
    lvalPage.putShort((short) 0); // num rows in page
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

@Override
public byte[] encodeSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {

    if (cannedMessagesSpec.cannedMessages == null || cannedMessagesSpec.cannedMessages.length == 0) {
        return null;
    }/*  w w w.ja  v a 2  s  .c  o  m*/

    String blobDBKey;
    switch (cannedMessagesSpec.type) {
    case CannedMessagesSpec.TYPE_MISSEDCALLS:
        blobDBKey = "com.pebble.android.phone";
        break;
    case CannedMessagesSpec.TYPE_NEWSMS:
        blobDBKey = "com.pebble.sendText";
        break;
    default:
        return null;
    }

    int replies_length = -1;

    for (String reply : cannedMessagesSpec.cannedMessages) {
        replies_length += reply.getBytes().length + 1;
    }

    ByteBuffer buf = ByteBuffer.allocate(12 + replies_length);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    buf.putInt(0x00000000); // unknown
    buf.put((byte) 0x00); // attributes count?
    buf.put((byte) 0x01); // actions count?

    // action
    buf.put((byte) 0x00); // action id
    buf.put((byte) 0x03); // action type = reply
    buf.put((byte) 0x01); // attributes count
    buf.put((byte) 0x08); // canned messages
    buf.putShort((short) replies_length);
    for (int i = 0; i < cannedMessagesSpec.cannedMessages.length - 1; i++) {
        buf.put(cannedMessagesSpec.cannedMessages[i].getBytes());
        buf.put((byte) 0x00);
    }
    // last one must not be zero terminated, else we get an additional empty reply
    buf.put(cannedMessagesSpec.cannedMessages[cannedMessagesSpec.cannedMessages.length - 1].getBytes());

    return encodeBlobdb(blobDBKey, BLOBDB_INSERT, BLOBDB_CANNED_MESSAGES, buf.array());
}

From source file:com.healthmarketscience.jackcess.impl.TableImpl.java

/**
 * Create a new data page// www.  ja  v a 2  s .c o  m
 * @return Page number of the new page
 */
private ByteBuffer newDataPage() throws IOException {
    ByteBuffer dataPage = _addRowBufferH.setNewPage(getPageChannel());
    dataPage.put(PageTypes.DATA); //Page type
    dataPage.put((byte) 1); //Unknown
    dataPage.putShort((short) getFormat().DATA_PAGE_INITIAL_FREE_SPACE); //Free space in this page
    dataPage.putInt(_tableDefPageNumber); //Page pointer to table definition
    dataPage.putInt(0); //Unknown
    dataPage.putShort((short) 0); //Number of rows on this page
    int pageNumber = _addRowBufferH.getPageNumber();
    getPageChannel().writePage(dataPage, pageNumber);
    _ownedPages.addPageNumber(pageNumber);
    _freeSpacePages.addPageNumber(pageNumber);
    return dataPage;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private byte[] encodePing(byte command, int cookie) {
    final short LENGTH_PING = 5;
    ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_PING);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort(LENGTH_PING);/*w w  w .  ja va2 s  . c o  m*/
    buf.putShort(ENDPOINT_PING);
    buf.put(command);
    buf.putInt(cookie);

    return buf.array();
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Serialize an Object into a raw byte value for this column
 * @param obj Object to serialize/* w  w  w  .  j  av a2  s .c o  m*/
 * @param order Order in which to serialize
 * @return A buffer containing the bytes
 * @usage _advanced_method_
 */
public ByteBuffer writeFixedLengthField(Object obj, ByteOrder order) throws IOException {
    int size = getType().getFixedSize(_columnLength);

    // create buffer for data
    ByteBuffer buffer = getPageChannel().createBuffer(size, order);

    // since booleans are not written by this method, it's safe to convert any
    // incoming boolean into an integer.
    obj = booleanToInteger(obj);

    switch (getType()) {
    case BOOLEAN:
        //Do nothing
        break;
    case BYTE:
        buffer.put(toNumber(obj).byteValue());
        break;
    case INT:
        buffer.putShort(toNumber(obj).shortValue());
        break;
    case LONG:
        buffer.putInt(toNumber(obj).intValue());
        break;
    case MONEY:
        writeCurrencyValue(buffer, obj);
        break;
    case FLOAT:
        buffer.putFloat(toNumber(obj).floatValue());
        break;
    case DOUBLE:
        buffer.putDouble(toNumber(obj).doubleValue());
        break;
    case SHORT_DATE_TIME:
        writeDateValue(buffer, obj);
        break;
    case TEXT:
        // apparently text numeric values are also occasionally written as fixed
        // length...
        int numChars = getLengthInUnits();
        // force uncompressed encoding for fixed length text
        buffer.put(encodeTextValue(obj, numChars, numChars, true));
        break;
    case GUID:
        writeGUIDValue(buffer, obj, order);
        break;
    case NUMERIC:
        // yes, that's right, occasionally numeric values are written as fixed
        // length...
        writeNumericValue(buffer, obj);
        break;
    case BINARY:
    case UNKNOWN_0D:
    case UNKNOWN_11:
    case COMPLEX_TYPE:
        buffer.putInt(toNumber(obj).intValue());
        break;
    case UNSUPPORTED_FIXEDLEN:
        byte[] bytes = toByteArray(obj);
        if (bytes.length != getLength()) {
            throw new IOException(
                    "Invalid fixed size binary data, size " + getLength() + ", got " + bytes.length);
        }
        buffer.put(bytes);
        break;
    default:
        throw new IOException("Unsupported data type: " + getType());
    }
    buffer.flip();
    return buffer;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

byte[] encodeUploadStart(byte type, int app_id, int size, String filename) {
    short length;
    if (mFwMajor >= 3 && (type != PUTBYTES_TYPE_FILE)) {
        length = (short) 10;
        type |= 0b10000000;/*from   w w  w.  j  a va  2s .c o m*/
    } else {
        length = (short) 7;
    }

    if (type == PUTBYTES_TYPE_FILE && filename != null) {
        length += filename.getBytes().length + 1;
    }

    ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort(length);
    buf.putShort(ENDPOINT_PUTBYTES);
    buf.put(PUTBYTES_INIT);
    buf.putInt(size);
    buf.put(type);

    if (mFwMajor >= 3 && (type != PUTBYTES_TYPE_FILE)) {
        buf.putInt(app_id);
    } else {
        // slot
        buf.put((byte) app_id);
    }

    if (type == PUTBYTES_TYPE_FILE && filename != null) {
        buf.put(filename.getBytes());
        buf.put((byte) 0);
    }

    return buf.array();
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

byte[] encodeUploadCancel(int token) {
    final short LENGTH_UPLOADCANCEL = 5;
    ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_UPLOADCANCEL);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putShort(LENGTH_UPLOADCANCEL);/*  ww w  . j  a v  a2s  . co  m*/
    buf.putShort(ENDPOINT_PUTBYTES);
    buf.put(PUTBYTES_ABORT);
    buf.putInt(token);
    return buf.array();
}