Example usage for java.nio ByteBuffer reset

List of usage examples for java.nio ByteBuffer reset

Introduction

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

Prototype

public final Buffer reset() 

Source Link

Document

Resets the position of this buffer to the mark.

Usage

From source file:com.glaf.core.util.BinaryUtils.java

/**
 * Returns a copy of the bytes from the given <code>ByteBuffer</code>,
 * ranging from the the buffer's current position to the buffer's limit; or
 * null if the input is null.//  w w w.  j  ava 2  s .  c o m
 * <p>
 * The internal states of the given byte buffer will be restored when this
 * method completes execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to
 * call the {@link #copyBytesFrom(ByteBuffer)} instead of
 * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
 * of the input <code>ByteBuffer</code>. The opposite is typically true,
 * however, when handling <code>ByteBuffer</code> from withint the
 * unmarshallers of the low-level clients.
 */
public static byte[] copyBytesFrom(ByteBuffer bb) {
    if (bb == null)
        return null;
    if (bb.hasArray())
        return Arrays.copyOfRange(bb.array(), bb.position(), bb.limit());
    bb.mark();
    try {
        byte[] dst = new byte[bb.remaining()];
        bb.get(dst);
        return dst;
    } finally {
        bb.reset();
    }
}

From source file:com.nridge.core.base.std.BufUtl.java

/**
 * Retrieves the operation version code stored within the header of the
 * <code>ByteBuffer</code> object.
 *
 * @param aBuffer Packet byte buffer object.
 * @return Application specific operation code version value.
 *//* ww w . jav a  2  s  .  com*/
@SuppressWarnings({ "UnusedAssignment" })
public static int getVersion(ByteBuffer aBuffer) {
    int opCode, versionId;

    if (aBuffer == null)
        return -1;
    else {
        aBuffer.mark();
        aBuffer.position(0);
        opCode = aBuffer.getInt();
        versionId = aBuffer.getInt();
        aBuffer.reset();

        return versionId;
    }
}

From source file:io.Text.java

/**
 * Returns the next code point at the current position in
 * the buffer. The buffer's position will be incremented.
 * Any mark set on this buffer will be changed by this method!
 *//*  w  ww  .  ja  va2s.  c o  m*/
public static int bytesToCodePoint(ByteBuffer bytes) {
    bytes.mark();
    byte b = bytes.get();
    bytes.reset();
    int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
    if (extraBytesToRead < 0)
        return -1; // trailing byte!
    int ch = 0;

    switch (extraBytesToRead) {
    case 5:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 4:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 3:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 2:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 1:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 0:
        ch += (bytes.get() & 0xFF);
    }
    ch -= offsetsFromUTF8[extraBytesToRead];

    return ch;
}

From source file:org.apache.arrow.vector.util.Text.java

/**
 * Returns the next code point at the current position in the buffer. The buffer's position will be incremented. Any
 * mark set on this buffer will be changed by this method!
 *//*from   w ww  .j av  a2s  .  c  om*/
public static int bytesToCodePoint(ByteBuffer bytes) {
    bytes.mark();
    byte b = bytes.get();
    bytes.reset();
    int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
    if (extraBytesToRead < 0) {
        return -1; // trailing byte!
    }
    int ch = 0;

    switch (extraBytesToRead) {
    case 5:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 4:
        ch += (bytes.get() & 0xFF);
        ch <<= 6; /* remember, illegal UTF-8 */
    case 3:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 2:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 1:
        ch += (bytes.get() & 0xFF);
        ch <<= 6;
    case 0:
        ch += (bytes.get() & 0xFF);
    }
    ch -= offsetsFromUTF8[extraBytesToRead];

    return ch;
}

From source file:org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils.java

public static int findText(Text text, Text subtext, int start) {
    if (start < 0)
        return -1;

    ByteBuffer src = ByteBuffer.wrap(text.getBytes(), 0, text.getLength());
    ByteBuffer tgt = ByteBuffer.wrap(subtext.getBytes(), 0, subtext.getLength());
    byte b = tgt.get();
    src.position(start);//  www .  j a  va 2s  .c  om

    while (src.hasRemaining()) {
        if (b == src.get()) {
            src.mark();
            tgt.mark();
            boolean found = true;
            int pos = src.position() - 1;
            while (tgt.hasRemaining()) {
                if (!src.hasRemaining()) {
                    tgt.reset();
                    src.reset();
                    found = false;
                    break;
                }
                if (!(tgt.get() == src.get())) {
                    tgt.reset();
                    src.reset();
                    found = false;
                    break;
                }
            }
            if (found)
                return pos;
        }
    }
    return -1;
}

From source file:org.apache.hadoop.hive.ql.io.orc.OrcSplit.java

@Override
public void write(DataOutput out) throws IOException {
    //serialize path, offset, length using FileSplit
    super.write(out);

    int flags = (hasBase ? BASE_FLAG : 0) | (isOriginal ? ORIGINAL_FLAG : 0) | (hasFooter ? FOOTER_FLAG : 0)
            | (fileId != null ? HAS_FILEID_FLAG : 0);
    out.writeByte(flags);//from w  w  w  .j ava2 s  .co  m
    out.writeInt(deltas.size());
    for (AcidInputFormat.DeltaMetaData delta : deltas) {
        delta.write(out);
    }
    if (hasFooter) {
        // serialize FileMetaInfo fields
        Text.writeString(out, fileMetaInfo.compressionType);
        WritableUtils.writeVInt(out, fileMetaInfo.bufferSize);
        WritableUtils.writeVInt(out, fileMetaInfo.metadataSize);

        // serialize FileMetaInfo field footer
        ByteBuffer footerBuff = fileMetaInfo.footerBuffer;
        footerBuff.reset();

        // write length of buffer
        WritableUtils.writeVInt(out, footerBuff.limit() - footerBuff.position());
        out.write(footerBuff.array(), footerBuff.position(), footerBuff.limit() - footerBuff.position());
        WritableUtils.writeVInt(out, fileMetaInfo.writerVersion.getId());
    }
    if (fileId != null) {
        out.writeLong(fileId.longValue());
    }
}

From source file:Main.java

public static List<ByteBuffer> mergeAdjacentBuffers(List<ByteBuffer> samples) {
    ArrayList<ByteBuffer> nuSamples = new ArrayList<ByteBuffer>(samples.size());
    for (ByteBuffer buffer : samples) {
        int lastIndex = nuSamples.size() - 1;
        if (lastIndex >= 0 && buffer.hasArray() && nuSamples.get(lastIndex).hasArray()
                && buffer.array() == nuSamples.get(lastIndex).array() && nuSamples.get(lastIndex).arrayOffset()
                        + nuSamples.get(lastIndex).limit() == buffer.arrayOffset()) {
            ByteBuffer oldBuffer = nuSamples.remove(lastIndex);
            ByteBuffer nu = ByteBuffer
                    .wrap(buffer.array(), oldBuffer.arrayOffset(), oldBuffer.limit() + buffer.limit()).slice();
            // We need to slice here since wrap([], offset, length) just sets position and not the arrayOffset.
            nuSamples.add(nu);/*from   w w  w  . ja  va 2s . c  o  m*/
        } else if (lastIndex >= 0 && buffer instanceof MappedByteBuffer
                && nuSamples.get(lastIndex) instanceof MappedByteBuffer && nuSamples.get(lastIndex)
                        .limit() == nuSamples.get(lastIndex).capacity() - buffer.capacity()) {
            // This can go wrong - but will it?
            ByteBuffer oldBuffer = nuSamples.get(lastIndex);
            oldBuffer.limit(buffer.limit() + oldBuffer.limit());
        } else {
            buffer.reset();
            nuSamples.add(buffer);
        }
    }
    return nuSamples;
}

From source file:org.commoncrawl.service.queryserver.master.S3Helper.java

static int scanForGZIPHeader(ByteBuffer byteBuffer) throws IOException {

    LOG.info("*** SCANNING FOR GZIP MAGIC Bytes:" + Byte.toString((byte) StreamingArcFileReader.GZIP_MAGIC)
            + " " + Byte.toString((byte) (StreamingArcFileReader.GZIP_MAGIC >> 8)) + " BufferSize is:"
            + byteBuffer.limit() + " Remaining:" + byteBuffer.remaining());
    int limit = byteBuffer.limit();

    while (byteBuffer.position() + 2 < limit) {
        //LOG.info("Reading Byte At:"+ byteBuffer.position());
        int b = byteBuffer.get();
        //LOG.info("First Byte is:"+ b);
        if (b == (byte) (StreamingArcFileReader.GZIP_MAGIC)) {

            byteBuffer.mark();/*from  ww  w .ja  v  a 2  s  .  c  o  m*/

            byte b2 = byteBuffer.get();
            //LOG.info("Second Byte is:"+ b2);
            if (b2 == (byte) (StreamingArcFileReader.GZIP_MAGIC >> 8)) {

                byte b3 = byteBuffer.get();
                if (b3 == Deflater.DEFLATED) {
                    LOG.info("Found GZip Magic at:" + (byteBuffer.position() - 3));
                    return byteBuffer.position() - 3;
                }
            }
            byteBuffer.reset();
        }
    }
    LOG.error("Failed to Find GZIP Magic!!");
    //LOG.error(Arrays.toString(byteBuffer.array()));
    return -1;
}

From source file:org.apache.hadoop.util.Crc32PerformanceTest.java

private ByteBuffer newData() {
    final byte[] bytes = new byte[dataLengthMB << 20];
    new Random().nextBytes(bytes);
    final ByteBuffer dataBufs = allocateByteBuffer(bytes.length);
    dataBufs.mark();/*from w  ww . j a v a  2 s . co m*/
    dataBufs.put(bytes);
    dataBufs.reset();
    return dataBufs;
}

From source file:com.homeadvisor.kafdrop.service.MessageInspector.java

private byte[] readBytes(ByteBuffer buffer, int offset, int size) {
    byte[] dest = new byte[size];
    if (buffer.hasArray()) {
        System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, size);
    } else {//from   w w w.  ja v a2  s  .c o m
        buffer.mark();
        buffer.get(dest);
        buffer.reset();
    }
    return dest;
}