Example usage for java.nio ByteBuffer limit

List of usage examples for java.nio ByteBuffer limit

Introduction

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

Prototype

public final Buffer limit(int newLimit) 

Source Link

Document

Sets the limit of this buffer.

Usage

From source file:org.cloudata.core.commitlog.pipe.Message.java

public boolean write(SocketChannel channel) throws IOException {
    if (writingHeaderPhase) {
        ByteBuffer dupHeaderBuf = duplicate(headerBuf);
        dupHeaderBuf.position(writtenPosition);
        dupHeaderBuf.limit(headerBuf.capacity());
        channel.write(dupHeaderBuf);//w w w. j a v a  2 s. co  m

        if (dupHeaderBuf.hasRemaining()) {
            writtenPosition = dupHeaderBuf.position();
            return false;
        }
        dupHeaderBuf.clear();
        writtenPosition = 0;
        writingHeaderPhase = false;
    }

    ByteBuffer dupBuffer = duplicate(buffer);
    dupBuffer.position(writtenPosition);
    dupBuffer.limit(buffer.capacity());
    channel.write(dupBuffer);

    if (dupBuffer.hasRemaining()) {
        writtenPosition = dupBuffer.position();
        return false;
    }

    writtenPosition = 0;
    writingHeaderPhase = true;
    dupBuffer.clear();
    return true;
}

From source file:com.meidusa.venus.benchmark.FileLineRandomData.java

private final String readLine(ByteBuffer buffer) {
    if (closed)/*from   w  w  w.ja v  a  2s.c om*/
        throw new IllegalStateException("file closed..");
    ByteBuffer tempbuffer = localTempBuffer.get();
    tempbuffer.position(0);
    tempbuffer.limit(tempbuffer.capacity());
    byte c = -1;
    boolean eol = false;
    while (!eol) {
        switch (c = buffer.get()) {
        case -1:
        case '\n':
            eol = true;
            break;
        case '\r':
            eol = true;
            int cur = buffer.position();
            if ((buffer.get()) != '\n') {
                buffer.position(cur);
            }
            break;
        default:
            tempbuffer.put(c);
            break;
        }
    }

    if ((c == -1) && (tempbuffer.position() == 0)) {
        return null;
    }
    tempbuffer.flip();

    try {
        return new String(tempbuffer.array(), encoding);
    } catch (UnsupportedEncodingException e) {
        return new String(tempbuffer.array());
    }

}

From source file:Main.java

public final static int substringBetweenLast(final byte[] text, final int offset, final int limit,
        final byte[] start, final byte[] end, final boolean trim, ByteBuffer bb) {
    int nEnd = lastIndexOf(text, offset, limit, end);
    int nStart = -1;
    if (nEnd > start.length) {
        nStart = lastIndexOf(text, offset, nEnd - 1, start);
        if (nStart < nEnd && nStart != -1 && nEnd != -1) {
            nStart += start.length;//from   ww  w. j a v a 2  s . c o m
            if (trim) {
                byte c;
                int i;
                for (i = nStart; i < nEnd; i++) {
                    c = text[i];
                    if (c != ' ' && c != '\t' && c != '\r') {
                        break;
                    }
                }
                nStart = i;
                for (i = nEnd; i >= nStart; i--) {
                    c = text[i];
                    if (c != ' ' && c != '\t' && c != '\r') {
                        break;
                    }
                }
                nEnd = i;
            }
            if (nEnd > nStart) {
                int len = nEnd - nStart;
                System.arraycopy(text, nStart, bb.array(), 0, len);
                bb.limit(len);
            } else {
                bb.limit(0);
            }
        } else {
            bb.limit(0);
        }
    } else {
        bb.limit(0);
    }
    return bb.limit();
}

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

@Test(timeout = 1000)
public void readPositionTracking() throws IOException {
    try (final SeekableByteChannel channel = stringToChannel("aabbbcccc")) {
        final Object lock = new Object();
        try (final WindowedSeekableByteChannel window = new WindowedSeekableByteChannel(channel, lock, 2L,
                7L)) {/*w  w  w.j  a  va2s .co m*/
            final byte[] bytes = new byte[10];
            final ByteBuffer buffer = ByteBuffer.wrap(bytes);

            buffer.limit(3);
            assertThat(window.read(buffer), is(3));
            assertThat(window.position(), is(3L));
            assertThat(buffer.position(), is(3));
            assertThat(buffer.limit(), is(3));
            assertThat(new String(bytes, 0, 3, Charset.forName("UTF-8")), is("bbb"));

            buffer.limit(10);
            assertThat(window.read(buffer), is(4));
            assertThat(window.position(), is(7L));
            assertThat(buffer.position(), is(7));
            assertThat(buffer.limit(), is(10));
            assertThat(new String(bytes, 3, 4, Charset.forName("UTF-8")), is("cccc"));
        }
    }
}

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;/*  ww w. j a va  2 s  . co  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;
}

From source file:org.cloudata.core.commitlog.pipe.Bulk.java

public OperationResult write(SocketChannel ch) throws IOException {
    if (bufferList.size() == 0) {
        throw new IOException("Pipe is closed");
    }//from w w w. j  a v a  2s  .c om

    int numWritten = 0;

    while (true) {
        ByteBuffer readBuf = bufferList.get(currentWriteBufIndex);
        ByteBuffer writeBuffer = readBuf.duplicate();
        writeBuffer.position(writtenPos);
        writeBuffer.limit(readBuf.position());

        numWritten = ch.write(writeBuffer);

        writtenPos += numWritten;
        totalNumWritten += numWritten;

        if (writeBuffer.hasRemaining()) {
            return OperationResult.partially;
        }

        //LOG.info("totalNumWritten : " + totalNumWritten + ", totalNumRead : " + totalNumRead);
        if (totalNumWritten < totalNumRead) {
            if (currentWriteBufIndex < currentReadBufIndex) {
                currentWriteBufIndex++;
                writtenPos = 0;
            } else {
                return OperationResult.partially;
            }
        } else {
            return OperationResult.completed;
        }
    }
}

From source file:com.linkedin.databus.core.DbusEventPart.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder(64);
    sb.append("Length=").append(getDataLength()).append(";SchemaVersion=").append(getSchemaVersion())
            .append(";SchemaId=").append("0x").append(Hex.encodeHexString(getSchemaDigest()));

    ByteBuffer dataBB = getData();
    if (dataBB.remaining() > MAX_DATA_BYTES_PRINTED) {
        dataBB.limit(MAX_DATA_BYTES_PRINTED);
    }/*  www .  j a v  a 2s.c  om*/
    byte[] data = new byte[dataBB.remaining()];
    dataBB.get(data);
    sb.append(";Value=").append("0x").append(Hex.encodeHexString(data));
    return sb.toString();
}

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 v  a 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: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);//from www  .  j ava  2  s .  c o m
    buf.limit(buf.capacity());

    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:ome.services.RawFileBean.java

@RolesAllowed("user")
public void write(byte[] buf, long position, int length) {
    errorIfNotLoaded();// www.  j  av  a 2s.c  o m
    ByteBuffer nioBuffer = MappedByteBuffer.wrap(buf);
    nioBuffer.limit(length);

    if (diskSpaceChecking) {
        iRepositoryInfo.sanityCheckRepository();
    }

    try {
        buffer.write(nioBuffer, position);
        modified();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Buffer write did not occur.", e);
        }
        throw new ResourceError(e.getMessage());
    }
}