Example usage for java.nio ByteBuffer remaining

List of usage examples for java.nio ByteBuffer remaining

Introduction

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

Prototype

public final int remaining() 

Source Link

Document

Returns the number of remaining elements in this buffer, that is limit - position .

Usage

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterInbound.java

private void parseUsingStream(ByteBuffer bb) {
    try {//from w w  w  .j a  v a2s . co m
        int remaining = bb.remaining();
        System.out.println("buf-copy remaining: " + bb.remaining());
        if (remaining <= 0)
            return;
        byte[] bytes = new byte[remaining];
        bb.get(bytes);

        saxParser.parse(new ByteArrayInputStream(bytes), messageParser);
        bytes = null;
    } catch (SAXException e) {
        log.error(e);
        log.error(e.getStackTrace());
    } catch (IOException e) {
        log.error(e);
        log.error(e.getStackTrace());
    }
}

From source file:com.github.hrpc.rpc.Server.java

/**
 * Helper for {@link #channelRead(ReadableByteChannel, ByteBuffer)}
 * and {@link #channelWrite(WritableByteChannel, ByteBuffer)}. Only
 * one of readCh or writeCh should be non-null.
 *
 * @see #channelRead(ReadableByteChannel, ByteBuffer)
 * @see #channelWrite(WritableByteChannel, ByteBuffer)
 *///from   www .  jav a2 s .co  m
private static int channelIO(ReadableByteChannel readCh, WritableByteChannel writeCh, ByteBuffer buf)
        throws IOException {

    int originalLimit = buf.limit();
    int initialRemaining = buf.remaining();
    int ret = 0;

    while (buf.remaining() > 0) {
        try {
            int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT);
            buf.limit(buf.position() + ioSize);

            ret = (readCh == null) ? writeCh.write(buf) : readCh.read(buf);

            if (ret < ioSize) {
                break;
            }

        } finally {
            buf.limit(originalLimit);
        }
    }

    int nBytes = initialRemaining - buf.remaining();
    return (nBytes > 0) ? nBytes : ret;
}

From source file:freed.cam.apis.camera2.modules.PictureModuleApi2.java

@NonNull
private void process_jpeg(Image image, File file) {

    Log.d(TAG, "Create JPEG");
    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);// w w w. java  2 s.co  m
    saveJpeg(file, bytes);
    image.close();
    buffer.clear();
    image = null;

}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterInbound.java

@Override
public void receive(ByteBuffer buf, String channelId) {
    try {//from   w ww . j a va  2 s .c  o  m
        buf.mark();
        int size = buf.remaining();
        if (size < 1)
            return;

        parseUsingStream(buf);
    } catch (Exception e) {
        log.error(e);
        log.error(e.getStackTrace());
    }
}

From source file:de.rwhq.btree.LeafNode.java

/**
 * Initializes the Leaf with data//from ww w . ja  va2  s .co m
 *
 * @param kvs
 *       data to insert as KeyValueObj Array
 * @param from
 *       from where in the array to start inserting
 *    @param maxTo
 *        usually lvs.length - 1
 * @return number of keys inserted
 */
public int bulkInitialize(final SimpleEntry<K, ?>[] kvs, final int from, final int maxTo) {
    initialize();

    final int remainingToInsert = maxTo - from + 1;
    if (remainingToInsert <= 0)
        return 0;

    final ByteBuffer buf = rawPage().bufferForWriting(Header.size());

    final int entrySize = keySerializer.getSerializedLength() + valueSerializer.getSerializedLength();
    final int entriesThatFit = buf.remaining() / entrySize;
    final int entriesToInsert = entriesThatFit > remainingToInsert ? remainingToInsert : entriesThatFit;

    // determine value type
    boolean isSerialized = (kvs[from].getValue() instanceof byte[]);

    if (!isSerialized) {
        for (int i = 0; i < entriesToInsert; i++) {
            buf.put(keySerializer.serialize(kvs[from + i].getKey()));
            buf.put(valueSerializer.serialize((V) kvs[from + i].getValue()));
        }
    } else {
        for (int i = 0; i < entriesToInsert; i++) {
            buf.put(keySerializer.serialize(kvs[from + i].getKey()));
            buf.put((byte[]) kvs[from + i].getValue());
        }
    }

    setNumberOfEntries(entriesToInsert);

    rawPage.sync();
    return entriesToInsert;
}

From source file:com.github.ambry.utils.UtilsTest.java

@Test
public void testSerializeNullableString() {
    String randomString = getRandomString(10);
    ByteBuffer outputBuffer = ByteBuffer.allocate(4 + randomString.getBytes().length);
    Utils.serializeNullableString(outputBuffer, randomString);
    outputBuffer.flip();//from   ww  w. j  a v  a 2  s . c  om
    int length = outputBuffer.getInt();
    assertEquals("Input and output string lengths don't match ", randomString.getBytes().length, length);
    byte[] output = new byte[length];
    outputBuffer.get(output);
    assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes",
            outputBuffer.hasRemaining());
    String outputString = new String(output);
    assertEquals("Input and output strings don't match", randomString, outputString);

    randomString = null;
    outputBuffer = ByteBuffer.allocate(4);
    Utils.serializeNullableString(outputBuffer, randomString);
    outputBuffer.flip();
    length = outputBuffer.getInt();
    assertEquals("Input and output string lengths don't match", 0, length);
    output = new byte[length];
    outputBuffer.get(output);
    assertFalse("Output buffer shouldn't have any remaining, but has " + outputBuffer.remaining() + " bytes",
            outputBuffer.hasRemaining());
    outputString = new String(output);
    assertEquals("Output string \"" + outputString + "\" expected to be empty", outputString, "");
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

/**
 * Return an encoder with all data from the last value retrieved (post call to next())
 * onwards/*from  w  ww  . ja va 2s .  c om*/
 * 
 * @param safeMetadata Is it safe to reuse the Metadata?
 */
public GTSEncoder getEncoder(boolean safeMetadata) throws IOException {

    if (!nextCalled) {
        throw new IOException(
                "Can only get an encoder for a decoder on which 'next' was called at least once.");
    }

    //
    // Copy the remaining data into a new ByteBuffer
    //

    ByteBuffer bb = this.buffer.duplicate();
    bb.position(this.position);

    int offset = 0;
    int len = bb.remaining();
    byte[] bytes = null;

    if (bb.hasArray()) {
        bytes = bb.array();
        offset = bb.arrayOffset() + bb.position();
    } else {
        bytes = new byte[bb.remaining()];
        bb.get(bytes);
    }

    //
    // Create an encoder with the same base timestamp and wrapping key, providing a sizing hint
    //

    GTSEncoder encoder = new GTSEncoder(this.baseTimestamp, this.wrappingKey, bb.remaining());

    if (safeMetadata) {
        encoder.safeSetMetadata(this.getMetadata());
    } else {
        encoder.setMetadata(this.getMetadata());
    }

    //
    // Set initial values
    //

    encoder.initialize(this.previousLastTimestamp, this.previousLastGeoXPPoint, this.previousLastElevation,
            this.previousLastLongValue, this.previousLastDoubleValue, this.previousLastBDValue,
            this.previousLastStringValue);

    //
    // Copy the encoded data
    //

    encoder.stream.write(bytes, offset, len);

    //
    // Put the encoder into 'safe delta' mode, because we don't know what the last
    // value/ts/elevation/location were, we can't use delta encoding for now
    //

    encoder.safeDelta();

    encoder.setCount(this.count);

    return encoder;
}

From source file:freed.cam.apis.camera2.modules.PictureModuleApi2.java

@NonNull
private void process_rawWithDngConverter(ImageHolder image, int rawFormat, File file) {
    Log.d(TAG, "Create DNG VIA RAw2DNG");
    ByteBuffer buffer = image.getImage().getPlanes()[0].getBuffer();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);/*w w  w.  j  a v  a  2s  . c o  m*/

    float fnum, focal = 0;
    fnum = image.getCaptureResult().get(CaptureResult.LENS_APERTURE);
    focal = image.getCaptureResult().get(CaptureResult.LENS_FOCAL_LENGTH);
    Log.d("Freedcam RawCM2", String.valueOf(bytes.length));

    int mISO = image.getCaptureResult().get(CaptureResult.SENSOR_SENSITIVITY).intValue();
    double mExposuretime = image.getCaptureResult().get(CaptureResult.SENSOR_EXPOSURE_TIME).doubleValue();
    //        int mFlash = image.getCaptureResult().get(CaptureResult.FLASH_STATE).intValue();
    //        double exposurecompensation= image.getCaptureResult().get(CaptureResult.CONTROL_AE_EXPOSURE_COMPENSATION).doubleValue();
    final DngProfile prof = getDngProfile(rawFormat, image);
    saveRawToDng(file, bytes, fnum, focal, (float) mExposuretime, mISO,
            image.captureResult.get(CaptureResult.JPEG_ORIENTATION), null, prof);
    image.getImage().close();
    bytes = null;
    buffer = null;
    image = null;
}

From source file:org.apache.hadoop.hbase.util.Bytes.java

/**
 * Add the whole content of the ByteBuffer to the bytes arrays. The ByteBuffer is modified.
 * @param bytes the byte array//w w  w.j  a  v a2s  .c  om
 * @param offset position in the array
 * @param buf ByteBuffer to write out
 * @return incremented offset
 */
public static int putByteBuffer(byte[] bytes, int offset, ByteBuffer buf) {
    int len = buf.remaining();
    buf.get(bytes, offset, len);
    return offset + len;
}

From source file:io.druid.query.aggregation.atomcube.AtomCubeAggregatorFactory.java

@Override
public RoaringBitmap deserialize(Object object) {
    final ByteBuffer byteBuffer;
    if (object == null) {
        throw new IAE("Cannot deserialize null object");
    } else if (object instanceof byte[]) {
        byteBuffer = ByteBuffer.wrap((byte[]) object);
    } else if (object instanceof String) {
        String value = (String) object;
        if (value.isEmpty()) {
            return new RoaringBitmap();
        }/*  w  w w.  j a  v  a 2 s  . com*/
        byteBuffer = ByteBuffer.wrap(Base64.decodeBase64(value));
    } else if (object instanceof ByteBuffer) {
        byteBuffer = (ByteBuffer) object;
    } else {
        throw new IAE("Cannot deserialize class[%s]", object.getClass().getName());
    }
    ImmutableBitmap immutableBitmap = BITMAP_SERDE_FACTORY.getObjectStrategy().fromByteBuffer(byteBuffer,
            byteBuffer.remaining());
    if (immutableBitmap instanceof WrappedImmutableRoaringBitmap) {
        RoaringBitmap bitmap = ((WrappedImmutableRoaringBitmap) immutableBitmap).getBitmap().toRoaringBitmap();
        return bitmap;
    }
    throw new IAE("Cannot deserialize this type of immutableBitmap object");
}