Example usage for java.nio ByteBuffer position

List of usage examples for java.nio ByteBuffer position

Introduction

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

Prototype

public final Buffer position(int newPosition) 

Source Link

Document

Sets the position of this buffer.

Usage

From source file:eu.stratosphere.pact.common.io.TextInputFormat.java

public boolean readRecord(PactRecord target, byte[] bytes, int offset, int numBytes) {
    PactString str = this.theString;

    if (this.ascii) {
        str.setValueAscii(bytes, offset, numBytes);
    } else {//from  w  ww  .j  a va 2 s  . c om
        ByteBuffer byteWrapper = this.byteWrapper;
        if (bytes != byteWrapper.array()) {
            byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
            this.byteWrapper = byteWrapper;
        }
        byteWrapper.position(offset);
        byteWrapper.limit(offset + numBytes);

        try {
            CharBuffer result = this.decoder.decode(byteWrapper);
            str.setValue(result);
        } catch (CharacterCodingException e) {
            byte[] copy = new byte[numBytes];
            System.arraycopy(bytes, offset, copy, 0, numBytes);
            LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
            return false;
        }
    }

    target.clear();
    target.setField(this.pos, str);
    return true;
}

From source file:com.spectralogic.ds3client.helpers.channels.WindowedSeekableByteChannel_Test.java

@Test(timeout = 1000)
public void writeDoesNotExceedWindow() throws IOException {
    try (final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel()) {
        final Object lock = new Object();
        try (final WindowedSeekableByteChannel window = new WindowedSeekableByteChannel(channel, lock, 2L,
                7L)) {/* ww  w .  ja v a  2 s.c  o  m*/
            final ByteBuffer buffer = Charset.forName("UTF-8").encode("0123456789");
            buffer.position(1);
            assertThat(window.write(buffer), is(7));
            assertThat(window.position(), is(7L));
            assertThat(buffer.position(), is(8));
            assertThat(buffer.limit(), is(10));

            assertThat(window.write(buffer), is(-1));
            assertThat(window.position(), is(7L));

            assertThat(channel.size(), is(9L));
            channel.position(0);

            assertThat(channel.toString(), is("\0\0" + "1234567"));
        }
    }
}

From source file:net.fenyo.mail4hotspot.dns.Msg.java

public String debugContent() {
    String retval = "";

    if (input_buffer.length == 0)
        return "invalid null size";

    if (input_buffer[0] == 0) {
        // UTF-8 message type
        retval += "type=text;";

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        retval += "query=" + query + ";";

    } else {/*from   ww w .  j a va2s  . c o  m*/
        // binary message type
        retval += "type=binary;";

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]);
        bb.put(input_buffer, 1, input_buffer[0]);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        retval += "query=" + query + ";";
    }

    return retval;
}

From source file:eu.stratosphere.arraymodel.io.StringInputFormat.java

public boolean readRecord(Value[] target, byte[] bytes, int offset, int numBytes) {
    StringValue str = this.theString;

    if (this.ascii) {
        str.setValueAscii(bytes, offset, numBytes);
    } else {//w  w w.  j a va  2 s .c om
        ByteBuffer byteWrapper = this.byteWrapper;
        if (bytes != byteWrapper.array()) {
            byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
            this.byteWrapper = byteWrapper;
        }
        byteWrapper.clear();
        byteWrapper.position(offset);
        byteWrapper.limit(offset + numBytes);

        try {
            CharBuffer result = this.decoder.decode(byteWrapper);
            str.setValue(result);
        } catch (CharacterCodingException e) {
            byte[] copy = new byte[numBytes];
            System.arraycopy(bytes, offset, copy, 0, numBytes);
            LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
            return false;
        }
    }

    target[0] = str;
    return true;
}

From source file:com.serenegiant.media.TLMediaEncoder.java

/**
 * write raw bit stream into specific intermediate file
 * @param out//from w w w.j av  a2s.c om
 * @param sequence
 * @param frame_number
 * @param info
 * @param buffer
 * @param writeBuffer
 * @throws IOException
 */
private static final void writeStream(final DataOutputStream out, final int sequence, final int frame_number,
        final MediaCodec.BufferInfo info, final ByteBuffer buffer, byte[] writeBuffer) throws IOException {

    if (writeBuffer.length < info.size) {
        writeBuffer = new byte[info.size];
    }
    buffer.position(info.offset);
    buffer.get(writeBuffer, 0, info.size);
    try {
        writeHeader(out, sequence, frame_number, info.presentationTimeUs, info.size, info.flags);
        out.write(writeBuffer, 0, info.size);
    } catch (IOException e) {
        if (DEBUG)
            Log.e(TAG_STATIC, "writeStream:", e);
        throw e;
    }
}

From source file:io.druid.segment.data.CompressedObjectStrategy.java

@Override
public ResourceHolder<T> fromByteBuffer(ByteBuffer buffer, int numBytes) {
    final ResourceHolder<ByteBuffer> bufHolder = CompressedPools.getByteBuf(order);
    final ByteBuffer buf = bufHolder.get();
    buf.position(0);
    buf.limit(buf.capacity());/* www. j  a v  a 2  s .  c o  m*/

    decompress(buffer, numBytes, buf);
    return new ResourceHolder<T>() {
        @Override
        public T get() {
            return converter.convert(buf);
        }

        @Override
        public void close() {
            bufHolder.close();
        }
    };
}

From source file:eu.stratosphere.pact.array.io.StringInputFormat.java

public boolean readRecord(Value[] target, byte[] bytes, int offset, int numBytes) {
    PactString str = this.theString;

    if (this.ascii) {
        str.setValueAscii(bytes, offset, numBytes);
    } else {//from  w  ww.  ja  va  2  s. c  om
        ByteBuffer byteWrapper = this.byteWrapper;
        if (bytes != byteWrapper.array()) {
            byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
            this.byteWrapper = byteWrapper;
        }
        byteWrapper.clear();
        byteWrapper.position(offset);
        byteWrapper.limit(offset + numBytes);

        try {
            CharBuffer result = this.decoder.decode(byteWrapper);
            str.setValue(result);
        } catch (CharacterCodingException e) {
            byte[] copy = new byte[numBytes];
            System.arraycopy(bytes, offset, copy, 0, numBytes);
            LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
            return false;
        }
    }

    target[0] = str;
    return true;
}

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

/**
 * creates the appropriate ContentImpl for the given blob.
 *//*from www .j a va  2  s .c  o  m*/
private static ContentImpl parseContent(OleBlobImpl blob) throws IOException {
    ByteBuffer bb = PageChannel.wrap(blob.getBytes());

    if ((bb.remaining() < 2) || (bb.getShort() != PACKAGE_SIGNATURE)) {
        return new UnknownContentImpl(blob);
    }

    // read outer package header
    int headerSize = bb.getShort();
    int objType = bb.getInt();
    int prettyNameLen = bb.getShort();
    int classNameLen = bb.getShort();
    int prettyNameOff = bb.getShort();
    int classNameOff = bb.getShort();
    int objSize = bb.getInt();
    String prettyName = readStr(bb, prettyNameOff, prettyNameLen);
    String className = readStr(bb, classNameOff, classNameLen);
    bb.position(headerSize);

    // read ole header
    int oleVer = bb.getInt();
    int format = bb.getInt();

    if (oleVer != OLE_VERSION) {
        return new UnknownContentImpl(blob);
    }

    int typeNameLen = bb.getInt();
    String typeName = readStr(bb, bb.position(), typeNameLen);
    bb.getLong(); // unused
    int dataBlockLen = bb.getInt();
    int dataBlockPos = bb.position();

    if (SIMPLE_PACKAGE_TYPE.equalsIgnoreCase(typeName)) {
        return createSimplePackageContent(blob, prettyName, className, typeName, bb, dataBlockLen);
    }

    // if COMPOUND_FACTORY is null, the poi library isn't available, so just
    // load compound data as "other"
    if ((COMPOUND_FACTORY != null) && (bb.remaining() >= COMPOUND_STORAGE_SIGNATURE.length)
            && ByteUtil.matchesRange(bb, bb.position(), COMPOUND_STORAGE_SIGNATURE)) {
        return COMPOUND_FACTORY.createCompoundPackageContent(blob, prettyName, className, typeName, bb,
                dataBlockLen);
    }

    // this is either some other "special" (as yet unhandled) format, or it is
    // simply an embedded file (or it is compound data and poi isn't available)
    return new OtherContentImpl(blob, prettyName, className, typeName, dataBlockPos, dataBlockLen);
}

From source file:net.fenyo.mail4hotspot.dns.Msg.java

private byte[] process(final AdvancedServices advancedServices, final Inet4Address address)
        throws GeneralException {
    // log.debug("processing message of type " + input_buffer[0]);
    // for (byte b : input_buffer) log.debug("received byte: [" + b + "]");

    if (input_buffer.length == 0)
        throw new GeneralException("invalid size");
    if (input_buffer[0] == 0) {
        // UTF-8 message type

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        // log.debug("RECEIVED query: [" + query + "]");

        final String reply = advancedServices.processQueryFromClient(query, address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill output_buffer
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply);
        ob.get(output_buffer = new byte[ob.limit()]);

        output_size = output_buffer.length;

    } else {/*  www . j  av  a2  s  .c o  m*/
        // binary message type
        // log.debug("processing binary message");

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]);
        bb.put(input_buffer, 1, input_buffer[0]);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        //      log.debug("RECEIVED query: [" + query + "]");

        final BinaryMessageReply reply = advancedServices.processBinaryQueryFromClient(query,
                Arrays.copyOfRange(input_buffer, input_buffer[0] + 1, input_buffer.length), address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill string_part
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply.reply_string);
        final byte[] string_part = new byte[ob.limit()];
        ob.get(string_part);

        if (string_part.length > 255)
            throw new GeneralException("string_part too long");
        output_buffer = new byte[string_part.length + reply.reply_data.length + 1];
        output_buffer[0] = (byte) string_part.length;
        for (int i = 0; i < string_part.length; i++)
            output_buffer[i + 1] = string_part[i];
        for (int i = 0; i < reply.reply_data.length; i++)
            output_buffer[string_part.length + i + 1] = reply.reply_data[i];
        output_size = output_buffer.length;
    }

    synchronized (compressed) {
        // http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#deflate(byte[])
        // log.debug("processing binary message: length before compressing: " + output_buffer.length);
        final Deflater compresser = new Deflater();
        compresser.setInput(output_buffer);
        compresser.finish();
        final int nbytes = compresser.deflate(compressed);
        //         log.debug("RET: " + nbytes);
        //         log.debug("COMPRESSED: " + compressed.length);
        // log.debug("processing binary message: length after compressing: " + nbytes);
        if (compressed.length == nbytes) {
            log.error("compressed buffer too small...");
            throw new GeneralException("compressed buffer too small...");
        }
        output_buffer = Arrays.copyOf(compressed, nbytes);
        output_size = output_buffer.length;
    }

    synchronized (is_processed) {
        is_processed = true;
    }

    return new byte[] { 'E', 0 }; // 'E'rror 0 == OK
}

From source file:eu.stratosphere.api.java.record.io.TextInputFormat.java

public Record readRecord(Record reuse, byte[] bytes, int offset, int numBytes) {
    StringValue str = this.theString;

    //Check if \n is used as delimiter and the end of this line is a \r, then remove \r from the line
    if (this.getDelimiter() != null && this.getDelimiter().length == 1 && this.getDelimiter()[0] == NEW_LINE
            && offset + numBytes >= 1 && bytes[offset + numBytes - 1] == CARRIAGE_RETURN) {
        numBytes -= 1;/*from w w  w .  jav a2  s  .c  o m*/
    }

    if (this.ascii) {
        str.setValueAscii(bytes, offset, numBytes);
    } else {
        ByteBuffer byteWrapper = this.byteWrapper;
        if (bytes != byteWrapper.array()) {
            byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
            this.byteWrapper = byteWrapper;
        }
        byteWrapper.limit(offset + numBytes);
        byteWrapper.position(offset);

        try {
            CharBuffer result = this.decoder.decode(byteWrapper);
            str.setValue(result);
        } catch (CharacterCodingException e) {
            byte[] copy = new byte[numBytes];
            System.arraycopy(bytes, offset, copy, 0, numBytes);
            LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
            return null;
        }
    }

    reuse.clear();
    reuse.setField(this.pos, str);
    return reuse;
}