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:au.org.ala.delta.io.BinFile.java

public void writeByte(byte b) {
    try {/*from  w ww.j a va  2s .c o m*/
        // _file.write(b);
        ByteBuffer bb = ByteBuffer.allocate(1);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.put(b);
        bb.position(0);
        _channel.write(bb);
    } catch (IOException ioex) {
        throw new RuntimeException(ioex);
    }
}

From source file:it.crs4.seal.recab.RecabTableMapper.java

protected void processMapping(AbstractTaggedMapping currentMapping, IMRContext<Text, ObservationCount> context)
        throws IOException, InterruptedException {
    context.increment(ReadCounters.Processed, 1);
    context.increment(BaseCounters.All, currentMapping.getLength());

    if (readFailsFilters(currentMapping))
        return;//from   w ww.  j a  v  a2 s  .com

    final String contig = currentMapping.getContig();

    int left, right; // left and right "limits" within the current sequence
    if (currentMapping.isTemplateLengthAvailable()
            && currentMapping.getTemplateLength() < currentMapping.getLength()) {
        // Insert size is less than the read size, so we've sequenced part of the read adapter.
        // We need to trim it the last read_length - insert_size bases sequenced.
        if (currentMapping.isOnReverse()) {
            // trim from front
            left = currentMapping.getLength() - currentMapping.getTemplateLength();
            right = currentMapping.getLength();
        } else {
            // trim from the back
            left = 0;
            right = currentMapping.getTemplateLength();
        }

        context.increment(BaseCounters.AdaptorBasesTrimmed, currentMapping.getLength() - (right - left));
    } else {
        left = 0;
        right = currentMapping.getLength();
    }

    currentMapping.calculateReferenceCoordinates(referenceCoordinates);
    currentMapping.calculateReferenceMatches(referenceMatches);

    for (Covariate cov : covariateList)
        cov.applyToMapping(currentMapping);

    final ByteBuffer seq = currentMapping.getSequence();
    final ByteBuffer qual = currentMapping.getBaseQualities();

    if (left > 0) {
        // we're using a relative get() method in the loop below, so here we
        // advance the buffer position to our starting point.
        seq.position(seq.position() + left);
        qual.position(qual.position() + left);
    }

    for (int i = left; i < right; ++i) {
        byte base = seq.get();
        byte quality = qual.get();

        if (base == 'N' || quality <= SANGER_OFFSET)
            context.increment(BaseCounters.BadBases, 1);
        else {
            int pos = referenceCoordinates.get(i);
            if (pos > 0) // valid reference position
            {
                // is it a known variation site?
                if (skipKnownVariantPositions && snps.isVariantLocation(contig, pos)) {
                    context.increment(BaseCounters.VariantBases, 1);

                    if (!referenceMatches.get(i))
                        context.increment(BaseCounters.VariantMismatches, 1);
                } else {
                    // use this base
                    context.increment(BaseCounters.Used, 1);

                    key.clear();
                    for (Covariate cov : covariateList) {
                        String tmp = cov.getValue(i);
                        key.append(tmp.getBytes(RecabTable.ASCII), 0, tmp.length());
                        key.append(RecabTable.TableDelimBytes, 0, RecabTable.TableDelimBytes.length);
                    }

                    boolean match = referenceMatches.get(i);
                    if (match) {
                        value.set(1, 0); // (num observations, num mismatches)
                    } else { // mismatch
                        context.increment(BaseCounters.NonVariantMismatches, 1);
                        value.set(1, 1);
                    }

                    context.write(key, value);
                }
            }
        }
    }
}

From source file:au.org.ala.delta.io.BinFile.java

public int readBytes(byte[] buffer) {
    if (_buffer != null) {
        for (int i = 0; i < buffer.length; ++i) {
            buffer[i] = _buffer[_filePointer];
            _filePointer++;//from  w  ww. ja va2s. co m
        }
        return buffer.length;
    } else {
        try {
            ByteBuffer bb = ByteBuffer.allocate(buffer.length);
            int bytesRead = _channel.read(bb);
            bb.position(0);
            bb.get(buffer, 0, buffer.length);
            return bytesRead;
        } catch (IOException ioex) {
            throw new RuntimeException(ioex);
        }
    }
}

From source file:au.org.ala.delta.io.BinFile.java

public void writeBytes(byte[] buffer) {
    try {/* ww  w  . j  a v a2  s .  c  om*/
        ByteBuffer bb = ByteBuffer.allocate(buffer.length);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.put(buffer);
        bb.position(0);
        _channel.write(bb);
        // _file.write(buffer);
    } catch (IOException ioex) {
        throw new RuntimeException(ioex);
    }
}

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

/**
 * Write a page (or part of a page) to disk
 * @param page Page to write// w  w w .  j  a  v a  2 s.c  om
 * @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:au.org.ala.delta.io.BinFile.java

public ByteBuffer readByteBuffer(int size) {
    ByteBuffer bb = ByteBuffer.allocate(size);
    try {/*w  ww . j  a  v  a2s  . c o  m*/
        int bytesRead = _channel.read(bb);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.position(0);
        assert bytesRead == size;
    } catch (IOException ioex) {
        throw new RuntimeException(ioex);
    }
    return bb;
}

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

/**
 * Write a page (or part of a page) to disk
 * @param page Page to write//from   ww  w . ja v  a2  s.com
 * @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 {
    validatePageNumber(pageNumber);

    page.rewind();

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

    ByteBuffer encodedPage = page;
    if (pageNumber == 0) {
        // re-mask header
        applyHeaderMask(page);
    } else {
        // re-encode page
        encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset);
    }
    try {
        encodedPage.position(pageOffset);
        _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset));
        if (_autoSync) {
            flush();
        }
    } finally {
        if (pageNumber == 0) {
            // de-mask header
            applyHeaderMask(page);
        }
    }
}

From source file:com.slytechs.capture.file.editor.FileEditorImpl.java

/**
 * @param headerReader/*from  ww  w  . j a  v a  2 s .c om*/
 * @param l
 * @param length
 * @throws IOException
 */
private PartialBuffer fetchPartialBuffer(final HeaderReader lengthGetter, final long global,
        final int minLength) throws IOException {

    final RegionSegment<PartialLoader> segment = this.edits.getSegment(global);
    final PartialLoader loader = segment.getData();
    final long regional = segment.mapGlobalToRegional(global);

    final PartialBuffer blockBuffer = loader.fetchBlock(regional, minLength);

    final int p = (int) (regional - blockBuffer.getStartRegional());

    /*
     * Make sure the next record we want to fetch resides in the existing shared
     * buffer, otherwise we have to prefetch another buffer.
     */
    if ((p < 0) || (blockBuffer.checkBoundsRegional(regional, minLength) == false)) {

        throw new IllegalStateException("Unable to prefetch buffer [" + regional + "/" + minLength + "]");
    }

    final ByteBuffer buffer = blockBuffer.getByteBuffer();

    buffer.limit(p + lengthGetter.getMinLength());
    buffer.position(p);

    return blockBuffer;
}

From source file:com.inductiveautomation.xopc.drivers.modbus2.requests.WriteMultipleRegistersRequest.java

public WriteMultipleRegistersRequest(List<WriteItem> items, ChannelWriter channelWriter,
        ModbusTransport transport, boolean zeroBased, byte unitId, int timeout, Logger log, boolean swapWords,
        boolean rightJustifyStrings, boolean reverseStringByteOrder,
        CommunicationCallback communicationCallback) {
    super(items, channelWriter, transport, zeroBased, unitId, timeout, log, communicationCallback);

    this.swapWords = swapWords;
    this.rightJustifyStrings = rightJustifyStrings;
    this.reverseStringByteOrder = reverseStringByteOrder;

    RequestOffsets offsets = new RequestOffsets.Calculator(items).calculate();

    // Multiply by two since each unit of length is one 16-bit register.
    ByteBuffer buffer = ByteBuffer.allocate(offsets.getLength() * 2);

    Iterator<? extends WriteItem> iter = items.iterator();

    while (iter.hasNext()) {
        WriteItem item = iter.next();/*  www  . j  a v  a  2 s . c o  m*/
        ModbusAddress address = (ModbusAddress) item.getAddressObject();

        int offset = (address.getStartAddress() - offsets.getStartAddress()) * 2;
        buffer.position(offset);

        byte[] bs = getValue(item, address);
        buffer.put(bs);
    }

    short startAddress = (short) offsets.getStartAddress();
    short quantity = (short) offsets.getLength();
    byte byteCount = (byte) buffer.limit();
    byte[] values = buffer.array();

    if (zeroBased) {
        startAddress--;
    }

    request = new WriteMultipleRegisters.Request(startAddress, quantity, byteCount, values);
}

From source file:au.org.ala.delta.io.BinFile.java

public void setLength(int newLength) {

    try {//w w  w. ja  va  2 s.c  o m
        // _file.setLength(newLength);
        int currentPos = tell();
        _channel.position(_channel.size());
        long growSize = newLength - _channel.size();
        ByteBuffer dummyBuffer = ByteBuffer.allocate((int) growSize);
        for (int i = 0; i < growSize; i++) {
            dummyBuffer.put((byte) 0);
        }
        dummyBuffer.position(0);
        _channel.write(dummyBuffer);
        seek(currentPos);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}