Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

From source file:com.castis.sysComp.PoisConverterSysComp.java

private List<subDataDTO> writeNodeInfoOnFile(int byteSize, ByteBuffer byteBuffer,
        GatheringByteChannel outByteCh, InputDataDTO data, String isLeafNode) {

    StringBuffer strBuffer = new StringBuffer();
    strBuffer.append(data.getRegion());/*from  www.ja  v a2 s . com*/
    strBuffer.append("|");
    strBuffer.append(data.getCategory());
    strBuffer.append("|");
    strBuffer.append(data.getWeekday());
    strBuffer.append("|");
    strBuffer.append(data.getHour());
    strBuffer.append("|");
    strBuffer.append(data.getPlatform());
    strBuffer.append("|");
    strBuffer.append(data.getCount());
    List<subDataDTO> subDataList = getSubDataList(data);

    // leafNode or not(Y/N)
    strBuffer.append("|");
    strBuffer.append(isLeafNode);

    strBuffer.append("\r\n");

    byte[] outByte = null;
    try {
        outByte = strBuffer.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    byteBuffer.put(outByte);
    byteBuffer.flip();
    try {
        outByteCh.write(byteBuffer);
    } catch (IOException e) {
    }
    byteBuffer.clear();

    return subDataList;
}

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

/**
 * Create a new data page//  ww w .j  ava2  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: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.//from   w  ww .  j ava2 s  .  co  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.robonobo.eon.SEONConnection.java

/**
 * Blocks until there is data to read/*from ww  w.  java 2s. c  o  m*/
 * 
 * @return A byte buffer with the incoming data
 */
public void read(ByteBuffer buf) throws EONException {
    receiveLock.lock();
    try {
        while (true) {
            while (incomingDataBufs.size() == 0) {
                if (state == State.Closed)
                    return;
                try {
                    haveData.await();
                } catch (InterruptedException e) {
                    throw new EONException(e);
                }
            }
            ByteBuffer incoming = (ByteBuffer) incomingDataBufs.getFirst();
            if (buf.remaining() >= incoming.remaining())
                buf.put(incoming);
            else {
                int remain = buf.remaining();
                buf.put(incoming.array(), incoming.position(), remain);
                incoming.position(incoming.position() + remain);
            }
            if (incoming.remaining() == 0)
                incomingDataBufs.removeFirst();
            if (buf.remaining() == 0)
                return;
            if (incomingDataBufs.size() == 0)
                return;
        }
    } finally {
        receiveLock.unlock();
    }
}

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

/**
 * @param database database which owns this table
 * @param tableBuffer Buffer to read the table with
 * @param pageNumber Page number of the table definition
 * @param name Table name//from w  w w.  ja  v a2s .  c o m
 * @param useBigIndex whether or not "big index support" should be enabled
 *                    for the table
 */
protected Table(Database database, ByteBuffer tableBuffer, int pageNumber, String name, int flags,
        boolean useBigIndex) throws IOException {
    _database = database;
    _tableDefPageNumber = pageNumber;
    _name = name;
    _flags = flags;
    _useBigIndex = useBigIndex;
    int nextPage = tableBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE);
    ByteBuffer nextPageBuffer = null;
    while (nextPage != 0) {
        if (nextPageBuffer == null) {
            nextPageBuffer = getPageChannel().createPageBuffer();
        }
        getPageChannel().readPage(nextPageBuffer, nextPage);
        nextPage = nextPageBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE);
        ByteBuffer newBuffer = getPageChannel()
                .createBuffer(tableBuffer.capacity() + getFormat().PAGE_SIZE - 8);
        newBuffer.put(tableBuffer);
        newBuffer.put(nextPageBuffer.array(), 8, getFormat().PAGE_SIZE - 8);
        tableBuffer = newBuffer;
        tableBuffer.flip();
    }
    readTableDefinition(tableBuffer);
    tableBuffer = null;
}

From source file:com.aionemu.gameserver.services.LegionService.java

/**
 * @param player/*from  w w  w. ja  v a2s . c  o  m*/
 * @param legionEmblem
 * @param legionId
 * @param legionName
 */
public void sendEmblemData(Player player, LegionEmblem legionEmblem, int legionId, String legionName) {
    PacketSendUtility.sendPacket(player,
            new SM_LEGION_SEND_EMBLEM(legionId, legionEmblem.getEmblemId(), legionEmblem.getColor_r(),
                    legionEmblem.getColor_g(), legionEmblem.getColor_b(), legionName,
                    legionEmblem.getEmblemType(), legionEmblem.getCustomEmblemData().length));
    ByteBuffer buf = ByteBuffer.allocate(legionEmblem.getCustomEmblemData().length);
    buf.put(legionEmblem.getCustomEmblemData()).position(0);
    log.debug("legionEmblem size: " + buf.capacity() + " bytes");
    int maxSize = 7993;
    int currentSize;
    byte[] bytes;
    do {
        log.debug("legionEmblem data position: " + buf.position());
        currentSize = buf.capacity() - buf.position();
        log.debug("legionEmblem data remaining capacity: " + currentSize + " bytes");

        if (currentSize >= maxSize) {
            bytes = new byte[maxSize];
            for (int i = 0; i < maxSize; i++) {
                bytes[i] = buf.get();
            }
            log.debug("legionEmblem data send size: " + (bytes.length) + " bytes");
            PacketSendUtility.sendPacket(player, new SM_LEGION_SEND_EMBLEM_DATA(maxSize, bytes));
        } else {
            bytes = new byte[currentSize];
            for (int i = 0; i < currentSize; i++) {
                bytes[i] = buf.get();
            }
            log.debug("legionEmblem data send size: " + (bytes.length) + " bytes");
            PacketSendUtility.sendPacket(player, new SM_LEGION_SEND_EMBLEM_DATA(currentSize, bytes));
        }
    } while (buf.capacity() != buf.position());
}

From source file:edu.hawaii.soest.kilonalu.ctd.CTDSource.java

/**
 * A method that queries the instrument to obtain its ID 
 *
 * @return result - a boolean result, true if the command succeeds
 *///from   www. java2 s.  co m
public boolean queryInstrument(String command) {

    logger.debug("CTDSource.queryInstrument() called.");

    // the result of the query
    boolean result = false;

    // only send the command if the socket is connected
    if (this.channel.isOpen()) {
        ByteBuffer commandBuffer = ByteBuffer.allocate(command.length());

        // lock the byte buffer while writing to it to make it threadsafe
        synchronized (commandBuffer) {
            commandBuffer.put(command.getBytes());
            // don't flip the buffer
        }

        try {
            this.channel.write(commandBuffer);
            logger.debug("Wrote " + command + " to the instrument channel.");
            result = true;

        } catch (IOException ioe) {
            logger.info("There was a problem sending the command to the "
                    + "instrument. The error message was: " + ioe.getMessage());
            result = false;
        }
    }
    return result;
}

From source file:net.yacy.cora.document.id.MultiProtocolURL.java

/**
 * Decode UTF-8 percent-encoded characters eventually found in the given path.
 * <ul>/*from   w ww  .j a  va2  s .c  o  m*/
 * Differences with {@link URLDecoder#decode(String, String)} :
 * <li>the '+' character is not decoded to space character</li>
 * <li>no exception is thrown when invalid hexadecimal digits are found after a '%' character</li>
 * </ul>
 * 
 * @param path an URL path eventually escaped
 * @return return the unescaped path or null when path is null.
 */
public static final String unescapePath(final String escaped) {
    if (escaped == null) {
        return escaped;
    }
    boolean modified = false;
    final int len = escaped.length();
    final StringBuilder unescaped = new StringBuilder(len > 500 ? len / 2 : len);
    ByteBuffer utf8Bytes = null;
    int i = 0;
    while (i < len) {
        final char ch = escaped.charAt(i);
        if (ch == '%' && (i + 2) < len) {
            final char digit1 = escaped.charAt(i + 1);
            final char digit2 = escaped.charAt(i + 2);
            if (isHexDigit(digit1) && isHexDigit(digit2)) {
                if (utf8Bytes == null) {
                    utf8Bytes = ByteBuffer.allocate((len - i) / 3);
                }
                /* Percent-encoded character UTF-8 byte */
                int hexaValue = Integer.parseInt(escaped.substring(i + 1, i + 3), 16);
                utf8Bytes.put((byte) hexaValue);
                modified = true;
                i += 2;
            } else {
                /* Not a valid percent-encoded character : we append it as is */
                unescaped.append(ch);
            }
        } else {
            if (utf8Bytes != null && utf8Bytes.position() > 0) {
                unescaped
                        .append(new String(utf8Bytes.array(), 0, utf8Bytes.position(), StandardCharsets.UTF_8));
                utf8Bytes.position(0);
            }
            unescaped.append(ch);
        }
        i++;
    }
    if (utf8Bytes != null && utf8Bytes.position() > 0) {
        unescaped.append(new String(utf8Bytes.array(), 0, utf8Bytes.position(), StandardCharsets.UTF_8));
    }

    return modified ? unescaped.toString() : escaped;
}

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

/**
 * Writes a new table defined by the given TableCreator to the database.
 * @usage _advanced_method_/*  w w w .j  a va 2  s .  c o m*/
 */
protected static void writeTableDefinition(TableCreator creator) throws IOException {
    // first, create the usage map page
    createUsageMapDefinitionBuffer(creator);

    // next, determine how big the table def will be (in case it will be more
    // than one page)
    JetFormat format = creator.getFormat();
    int idxDataLen = (creator.getIndexCount() * (format.SIZE_INDEX_DEFINITION + format.SIZE_INDEX_COLUMN_BLOCK))
            + (creator.getLogicalIndexCount() * format.SIZE_INDEX_INFO_BLOCK);
    int colUmapLen = creator.getLongValueColumns().size() * 10;
    int totalTableDefSize = format.SIZE_TDEF_HEADER
            + (format.SIZE_COLUMN_DEF_BLOCK * creator.getColumns().size()) + idxDataLen + colUmapLen
            + format.SIZE_TDEF_TRAILER;

    // total up the amount of space used by the column and index names (2
    // bytes per char + 2 bytes for the length)
    for (ColumnBuilder col : creator.getColumns()) {
        int nameByteLen = (col.getName().length() * JetFormat.TEXT_FIELD_UNIT_SIZE);
        totalTableDefSize += nameByteLen + 2;
    }

    for (IndexBuilder idx : creator.getIndexes()) {
        int nameByteLen = (idx.getName().length() * JetFormat.TEXT_FIELD_UNIT_SIZE);
        totalTableDefSize += nameByteLen + 2;
    }

    // now, create the table definition
    PageChannel pageChannel = creator.getPageChannel();
    ByteBuffer buffer = PageChannel.createBuffer(Math.max(totalTableDefSize, format.PAGE_SIZE));
    writeTableDefinitionHeader(creator, buffer, totalTableDefSize);

    if (creator.hasIndexes()) {
        // index row counts
        IndexData.writeRowCountDefinitions(creator, buffer);
    }

    // column definitions
    ColumnImpl.writeDefinitions(creator, buffer);

    if (creator.hasIndexes()) {
        // index and index data definitions
        IndexData.writeDefinitions(creator, buffer);
        IndexImpl.writeDefinitions(creator, buffer);
    }

    // write long value column usage map references
    for (ColumnBuilder lvalCol : creator.getLongValueColumns()) {
        buffer.putShort(lvalCol.getColumnNumber());
        TableCreator.ColumnState colState = creator.getColumnState(lvalCol);

        // owned pages umap (both are on same page)
        buffer.put(colState.getUmapOwnedRowNumber());
        ByteUtil.put3ByteInt(buffer, colState.getUmapPageNumber());
        // free space pages umap
        buffer.put(colState.getUmapFreeRowNumber());
        ByteUtil.put3ByteInt(buffer, colState.getUmapPageNumber());
    }

    //End of tabledef
    buffer.put((byte) 0xff);
    buffer.put((byte) 0xff);

    // write table buffer to database
    if (totalTableDefSize <= format.PAGE_SIZE) {

        // easy case, fits on one page
        buffer.putShort(format.OFFSET_FREE_SPACE, (short) (buffer.remaining() - 8)); // overwrite page free space
        // Write the tdef page to disk.
        pageChannel.writePage(buffer, creator.getTdefPageNumber());

    } else {

        // need to split across multiple pages
        ByteBuffer partialTdef = pageChannel.createPageBuffer();
        buffer.rewind();
        int nextTdefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
        while (buffer.hasRemaining()) {

            // reset for next write
            partialTdef.clear();

            if (nextTdefPageNumber == PageChannel.INVALID_PAGE_NUMBER) {

                // this is the first page.  note, the first page already has the
                // page header, so no need to write it here
                nextTdefPageNumber = creator.getTdefPageNumber();

            } else {

                // write page header
                writeTablePageHeader(partialTdef);
            }

            // copy the next page of tdef bytes
            int curTdefPageNumber = nextTdefPageNumber;
            int writeLen = Math.min(partialTdef.remaining(), buffer.remaining());
            partialTdef.put(buffer.array(), buffer.position(), writeLen);
            ByteUtil.forward(buffer, writeLen);

            if (buffer.hasRemaining()) {
                // need a next page
                nextTdefPageNumber = pageChannel.allocateNewPage();
                partialTdef.putInt(format.OFFSET_NEXT_TABLE_DEF_PAGE, nextTdefPageNumber);
            }

            // update page free space
            partialTdef.putShort(format.OFFSET_FREE_SPACE, (short) (partialTdef.remaining() - 8)); // overwrite page free space

            // write partial page to disk
            pageChannel.writePage(partialTdef, curTdefPageNumber);
        }

    }
}

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

/**
 * Returns an entry buffer containing the relevant data for an entry given
 * the valuePrefix./*from   w  w  w. j  av a2s .c o  m*/
 */
private ByteBuffer getTempEntryBuffer(ByteBuffer indexPage, int entryLen, byte[] valuePrefix,
        TempBufferHolder tmpEntryBufferH) {
    ByteBuffer tmpEntryBuffer = tmpEntryBufferH.getBuffer(getPageChannel(), valuePrefix.length + entryLen);

    // combine valuePrefix and rest of entry from indexPage, then prep for
    // reading
    tmpEntryBuffer.put(valuePrefix);
    tmpEntryBuffer.put(indexPage.array(), indexPage.position(), entryLen);
    tmpEntryBuffer.flip();

    return tmpEntryBuffer;
}