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.ebay.pulsar.analytics.metricstore.druid.query.model.GroupByQuery.java

@Override
public byte[] cacheKey() {
    BaseFilter filter = this.getFilter();
    byte[] filterBytes = filter == null ? new byte[] {} : filter.cacheKey();
    byte[] aggregatorBytes = QueryCacheHelper.computeAggregatorBytes(this.getAggregations());
    byte[] granularityBytes = null;
    if (this.getGranularity() instanceof BaseGranularity) {
        granularityBytes = ((BaseGranularity) this.getGranularity()).cacheKey();
    } else {/*from   w w  w .  ja va2  s .  c  o m*/
        granularityBytes = new byte[0];
    }
    byte[] intervalsBytes = QueryCacheHelper.computeIntervalsBytes(this.getIntervals());
    final byte[][] dimensionsBytes = new byte[this.getDimensions().size()][];
    int dimensionsBytesSize = 0;
    int index = 0;
    for (String dimension : this.getDimensions()) {
        dimensionsBytes[index] = dimension.getBytes();
        dimensionsBytesSize += dimensionsBytes[index].length;
        ++index;
    }
    final byte[] limitBytes = this.getLimitSpec().cacheKey();

    BaseHaving having = this.getHaving();
    byte[] havingBytes = having == null ? new byte[] {} : having.cacheKey();

    List<BasePostAggregator> postaggregators = this.getPostAggregations();
    byte[] postaggregatorBytes = postaggregators == null ? new byte[] {}
            : QueryCacheHelper.computePostAggregatorBytes(postaggregators);

    ByteBuffer buffer = ByteBuffer
            .allocate(1 + granularityBytes.length + filterBytes.length + aggregatorBytes.length
                    + dimensionsBytesSize + limitBytes.length + havingBytes.length + intervalsBytes.length
                    + postaggregatorBytes.length)
            .put(GROUPBY_QUERY).put(granularityBytes).put(filterBytes).put(aggregatorBytes)
            .put(postaggregatorBytes);

    for (byte[] dimensionsByte : dimensionsBytes) {
        buffer.put(dimensionsByte);
    }
    return buffer.put(limitBytes).put(havingBytes).put(intervalsBytes).array();
}

From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java

public ByteBuffer encode() throws RpcCommandException {
    /******* ? *******/
    // 1> protocol type size
    int length = Protocol.PROTOCOL_TYPE_SIZE;

    // 2> header length size
    length += Protocol.HEADER_LENGTH_SIZE;

    // 3> header data length
    byte[] headerData = this.headerEncode();
    length += headerData.length;//from w ww.j av a2s  .co  m

    // 4> body data length
    if (this.body != null) {
        length += body.length;
    }

    /******* ByteBuffer *******/
    //?
    ByteBuffer result = ByteBuffer.allocate(Protocol.TOTAL_LENGTH_SIZE + length);

    // 0?length
    result.putInt(length);

    // 1?protocol type
    result.put(markProtocolType(serializeType));

    // 2?header length
    result.putInt(headerData.length);

    // 3?header data
    result.put(headerData);

    // 4?body data;
    if (this.body != null) {
        result.put(this.body);
    }

    result.flip();

    return result;
}

From source file:net.cellcloud.talk.stuff.PrimitiveSerializer.java

/** ???
 *///from w  w  w . ja  v  a2  s . c o m
public static void read(Primitive primitive, InputStream stream) {
    /*
    ??
    [version]{sutff}...{stuff}[dialect@tracker]
    
    [01.00]{sub=cloud:string}{pre=add:string}[Action@Ambrose]
    */

    try {
        byte phase = PARSE_PHASE_UNKNOWN;
        int read = 0;

        ByteBuffer buf = ByteBuffer.allocate(BLOCK);
        byte[] type = new byte[3];
        byte[] value = null;
        byte[] literal = null;
        int length = 0;

        while ((read = stream.read()) >= 0) {

            // ?
            switch (phase) {

            case PARSE_PHASE_VALUE:
                // 
                if (read == '\\') {
                    // ?
                    int next = stream.read();
                    if (next == TOKEN_OPEN_BRACE || next == TOKEN_CLOSE_BRACE || next == TOKEN_OPERATE_ASSIGN
                            || next == TOKEN_OPERATE_DECLARE) {
                        buf.put((byte) next);
                        ++length;
                    } else {
                        buf.put((byte) read);
                        buf.put((byte) next);
                        length += 2;
                    }

                    // 
                    continue;
                }

                if (read == TOKEN_OPERATE_DECLARE) {
                    // ?
                    buf.flip();
                    value = new byte[length];
                    buf.get(value, 0, length);
                    buf.clear();

                    phase = PARSE_PHASE_LITERAL;
                    length = 0;
                    continue;
                }

                buf.put((byte) read);
                ++length;
                break;

            case PARSE_PHASE_TYPE:
                if (read == TOKEN_OPERATE_ASSIGN) {
                    // ?
                    buf.flip();
                    buf.get(type);
                    buf.clear();

                    phase = PARSE_PHASE_VALUE;
                    length = 0;
                    continue;
                }
                // 
                buf.put((byte) read);
                break;

            case PARSE_PHASE_LITERAL:
                if (read == TOKEN_CLOSE_BRACE) {
                    // ??
                    buf.flip();
                    literal = new byte[length];
                    buf.get(literal, 0, length);
                    buf.clear();

                    // 
                    injectStuff(primitive, type, value, literal);

                    phase = PARSE_PHASE_DIALECT;
                    length = 0;
                    continue;
                }
                buf.put((byte) read);
                ++length;
                break;

            case PARSE_PHASE_STUFF:
                if (read == TOKEN_OPEN_BRACE) {
                    // ?
                    phase = PARSE_PHASE_TYPE;
                    buf.clear();
                }
                break;

            case PARSE_PHASE_VERSION:
                if (read == TOKEN_CLOSE_BRACKET) {
                    // ??
                    phase = PARSE_PHASE_STUFF;
                    continue;
                }
                buf.put((byte) read);
                break;

            case PARSE_PHASE_DIALECT:
                if (read == TOKEN_OPEN_BRACE) {
                    phase = PARSE_PHASE_TYPE;
                    buf.clear();
                } else if (read == TOKEN_OPEN_BRACKET) {
                    // ?
                    buf.clear();
                } else if (read == TOKEN_CLOSE_BRACKET) {
                    // ??
                    deserializeDialect(primitive, new String(buf.array(), 0, length, Charset.forName("UTF-8")));
                } else {
                    // ?
                    buf.put((byte) read);
                    ++length;
                }
                break;

            default:
                if (read == TOKEN_OPEN_BRACE) {
                    phase = PARSE_PHASE_TYPE;
                    buf.clear();
                } else if (read == TOKEN_OPEN_BRACKET) {
                    phase = PARSE_PHASE_VERSION;
                    buf.clear();
                }
                break;
            }
        }

        buf.clear();

    } catch (IOException e) {
        Logger.log(PrimitiveSerializer.class, e, LogLevel.ERROR);
    }
}

From source file:com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider.java

private short convertTwoBytesToShort(byte[] input, int index) throws SQLServerException {

    short shortVal = -1;
    if (index + 1 >= input.length) {
        throw new SQLServerException(null, SQLServerException.getErrString("R_ByteToShortConversion"), null, 0,
                false);//from   w w  w. j  a  va2s .c  om
    }
    ByteBuffer byteBuffer = ByteBuffer.allocate(2);
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byteBuffer.put(input[index]);
    byteBuffer.put(input[index + 1]);
    shortVal = byteBuffer.getShort(0);
    return shortVal;

}

From source file:org.alfresco.contentstore.ContentStoreTest.java

private PatchDocument getPatch(Node node, String content) throws IOException {
    PatchDocument patchDocument = new PatchDocumentImpl();

    ByteBuffer data = ByteBuffer.allocate(1024 * 10);
    data.put(content.getBytes());
    data.flip();//from w  w w.  ja v  a  2s  .co m

    NodeChecksums checksums = checksumService.getChecksums(node.getNodeId(), node.getNodeVersion());
    patchService.updatePatchDocument(patchDocument, checksums, data);

    return patchDocument;
}

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

/**
 * Write a page (or part of a page) to disk
 * @param page Page to write//from ww  w  .  j av a  2s  . c o  m
 * @param pageNumber Page number to write the page to
 * @param pageOffset offset within the page at which to start writing the
 *                   page data
 */
public void writePage(ByteBuffer page, int pageNumber, int pageOffset) throws IOException {
    assertWriting();
    validatePageNumber(pageNumber);

    page.rewind().position(pageOffset);

    int writeLen = page.remaining();
    if ((writeLen + pageOffset) > getFormat().PAGE_SIZE) {
        throw new IllegalArgumentException("Page buffer is too large, size " + (writeLen + pageOffset));
    }

    ByteBuffer encodedPage = page;
    if (pageNumber == 0) {
        // re-mask header
        applyHeaderMask(page);
    } else {

        if (!_codecHandler.canEncodePartialPage()) {
            if ((pageOffset > 0) && (writeLen < getFormat().PAGE_SIZE)) {

                // current codec handler cannot encode part of a page, so need to
                // copy the modified part into the current page contents in a temp
                // buffer so that we can encode the entire page
                ByteBuffer fullPage = _fullPageEncodeBufferH.setPage(this, pageNumber);

                // copy the modified part to the full page
                fullPage.position(pageOffset);
                fullPage.put(page);
                fullPage.rewind();

                // reset so we can write the whole page
                page = fullPage;
                pageOffset = 0;
                writeLen = getFormat().PAGE_SIZE;

            } else {

                _fullPageEncodeBufferH.possiblyInvalidate(pageNumber, null);
            }
        }

        // re-encode page
        encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset);

        // reset position/limit in case they were affected by encoding
        encodedPage.position(pageOffset).limit(pageOffset + writeLen);
    }

    try {
        _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset));
    } finally {
        if (pageNumber == 0) {
            // de-mask header
            applyHeaderMask(page);
        }
    }
}

From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java

public ByteBuffer encodeHeader(final int bodyLength) throws RpcCommandException {
    /******* ? *******/
    // 1> protocol type size
    int length = Protocol.PROTOCOL_TYPE_SIZE;

    // 2> header length size
    length += Protocol.HEADER_LENGTH_SIZE;

    // 3> header data length
    byte[] headerData;
    headerData = this.headerEncode();
    length += headerData.length;/* ww w  .  j a v a 2  s.c  o  m*/

    // 4> body data length
    length += bodyLength;

    /******* ByteBuffer *******/
    //??body
    ByteBuffer result = ByteBuffer.allocate(Protocol.TOTAL_LENGTH_SIZE + length - bodyLength);

    // 0?length
    result.putInt(length);

    // 1?protocol type
    result.put(markProtocolType(serializeType));

    // 2?header length
    result.putInt(headerData.length);

    // 3?header data
    result.put(headerData);

    result.flip();

    return result;
}

From source file:ru.jts_dev.common.tcp.ProtocolByteArrayLengthHeaderSerializer.java

@Override
protected void writeHeader(OutputStream outputStream, int length) throws IOException {
    ByteBuffer lengthPart = ByteBuffer.allocate(this.headerSize).order(LITTLE_ENDIAN);
    length += headerSize; // Protocol thing, length represent header size + data size
    switch (this.headerSize) {
    case HEADER_SIZE_INT:
        lengthPart.putInt(length);/*www .j  av a 2  s .c  om*/
        break;
    case HEADER_SIZE_UNSIGNED_BYTE:
        if (length > 0xff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.put((byte) length);
        break;
    case HEADER_SIZE_UNSIGNED_SHORT:
        if (length > 0xffff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.putShort((short) length);
        break;
    default:
        throw new IllegalArgumentException("Bad header size:" + headerSize);
    }
    outputStream.write(lengthPart.array());
}

From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicParser.java

/**
 * replaces octal representations of bytes, written as \ddd to actual byte values.
 *
 * @param s a string with encoded octals
 *
 * @return string with all octals decoded
 *//*ww w.  jav a  2  s  .  c  om*/
private ByteBuffer convertOctals(String s) {
    int beg = 0;
    int end = 0;
    int c1;
    int c2;
    int c3;
    int chr;
    ByteArrayOutputStream buf = new ByteArrayOutputStream();

    while ((end = s.indexOf('\\', beg)) != -1) {
        if (s.charAt(end + 1) != '\\') {
            //log.debug("appending chunk '"+s.substring(beg, end)+"'");
            for (int z = beg; z < end; z++) {
                buf.write((int) s.charAt(z));
            }

            //log.debug("found \\ at position "+end);
            //log.debug("converting octal '"+s.substring(end, end+4)+"'");
            if ((end + 4) <= s.length()) {
                try {
                    chr = Integer.parseInt(s.substring(end + 1, end + 4), 8);

                    //log.debug("converted octal '"+s.substring(end+1,end+4)+"' to '"+chr);
                    //log.debug("converted octal back to '"+Integer.toOctalString(chr));

                    //log.debug("converted '"+s.substring(end+1,end+4)+"' to "+chr+"/"+((char)chr));
                    buf.write(chr);
                    beg = end + 4;
                    end = beg;
                } catch (NumberFormatException nfe) {
                    //log.debug("not an octal");
                    buf.write((int) '\\');
                    beg = end + 1;
                    end = beg;
                }
            } else {
                //log.debug("not an octal, not enough chars left in string");
                buf.write((int) '\\');
                beg = end + 1;
                end = beg;
            }
        } else {
            //log.debug("appending \\");
            buf.write((int) '\\');
            beg = end + 1;
            end = beg;
        }
    }

    if (end < s.length()) {
        for (int z = beg; z < s.length(); z++) {
            buf.write((int) s.charAt(z));
        }
    }

    try {
        log.debug("convertOctals(): returning buffer size '" + buf.size() + "'");

        ByteBuffer b = ByteBuffer.allocate(buf.size());

        return b.put(buf.toByteArray());
    } catch (Exception e) {
        log.error("convertOctals(): error parsing string: " + e);

        return ByteBuffer.allocate(0);
    }
}

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

/**
 * get a file, based on the retrieval id from the server
 * //ww w. ja  v  a  2 s.c  o  m
 * @throws MessageNotFoundException
 */
public byte[] getFile(byte[] msgHashBytes) throws ExchangeException, MessageNotFoundException {

    ByteBuffer msg = ByteBuffer.allocate(mVersionLen //
            + 4 + msgHashBytes.length //
    );
    msg.putInt(mVersion);
    msg.putInt(msgHashBytes.length);
    msg.put(msgHashBytes);

    byte[] resp = doPost(mUrlPrefix + mHost + "/getFile" + mUrlSuffix, msg.array());

    resp = handleResponseExceptions(resp, 0);

    return resp;
}