Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

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

Prototype

public abstract byte get(int index);

Source Link

Document

Returns the byte at the specified index and does not change the position.

Usage

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);
    saveJpeg(file, bytes);/*from ww  w .j av a2 s . c  o  m*/
    image.close();
    buffer.clear();
    image = null;

}

From source file:org.commonjava.indy.httprox.handler.ProxyRequestReader.java

private int doRead(final ConduitStreamSourceChannel channel) throws IOException {
    bReq = new ByteArrayOutputStream();
    pReq = new PrintStream(bReq);

    logger.debug("Starting read: {}", channel);

    int total = 0;
    while (true) {
        ByteBuffer buf = ByteBuffer.allocate(1024);
        channel.awaitReadable(AWAIT_READABLE_IN_MILLISECONDS, TimeUnit.MILLISECONDS);

        int read = channel.read(buf); // return the number of bytes read, possibly zero, or -1

        logger.debug("Read {} bytes", read);

        if (read == -1) // return -1 if the channel has reached end-of-stream
        {/*  w ww  . j a  v  a2 s .c  om*/
            if (total == 0) // nothing read, return -1 to indicate the EOF
            {
                return -1;
            } else {
                return total;
            }
        }

        if (read == 0) // no new bytes this time
        {
            return total;
        }

        total += read;

        buf.flip();
        byte[] bbuf = new byte[buf.limit()];
        buf.get(bbuf);

        if (!headDone) {
            // allows us to stop after header read...
            final String part = new String(bbuf);
            for (final char c : part.toCharArray()) {
                switch (c) {
                case '\n': {
                    while (lastFour.size() > 3) {
                        lastFour.remove(0);
                    }

                    lastFour.add(c);
                    try {
                        if (bReq.size() > 0 && HEAD_END.equals(lastFour)) {
                            logger.debug("Detected end of request headers.");
                            headDone = true;

                            logger.trace("Proxy request header:\n{}\n", new String(bReq.toByteArray()));
                        }
                    } finally {
                        lastFour.remove(lastFour.size() - 1);
                    }
                }
                default: {
                    pReq.print(c);
                    lastFour.add(c);
                }
                }
            }
        } else {
            bReq.write(bbuf);
        }
    }
}

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);

    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();//ww  w  .  j a va2s .  c  o m
    bytes = null;
    buffer = null;
    image = null;
}

From source file:au.org.ala.delta.intkey.model.IntkeyDatasetFileReader.java

/**
 * Read information about the fonts to use when generating text labels on
 * image overlays/*w w  w .ja v a 2 s  .  c  o  m*/
 * 
 * @param charFileHeader
 *            Characters file header data
 * @param charBinFile
 *            Characters file
 * @param ds
 *            Object representation of intkey dataset. This object will be
 *            updated with the read image information
 */
private static void readOverlayFonts(CharactersFileHeader charFileHeader, BinFile charBinFile,
        IntkeyDataset ds) {
    int recordNo = charFileHeader.getRpFont();
    if (recordNo != 0) {
        seekToRecord(charBinFile, recordNo);

        // single integer showing the number of fonts
        int numFonts = charBinFile.readInt();

        seekToRecord(charBinFile, recordNo + 1);
        List<Integer> fontTextLengths = readIntegerList(charBinFile, numFonts);

        int totalFontsLength = 0;
        for (int fontLength : fontTextLengths) {
            totalFontsLength += fontLength;
        }

        int recordsSpannedByFontTextLengths = recordsSpannedByBytes(numFonts * Constants.SIZE_INT_IN_BYTES);
        seekToRecord(charBinFile, recordNo + 1 + recordsSpannedByFontTextLengths);

        List<FontInfo> fonts = new ArrayList<FontInfo>();
        ByteBuffer fontTextData = charBinFile.readByteBuffer(totalFontsLength);
        for (int fontLength : fontTextLengths) {
            byte[] fontTextBytes = new byte[fontLength];
            fontTextData.get(fontTextBytes);
            String fontText = BinFileEncoding.decode(fontTextBytes);
            FontInfo fontInfo = null;
            try {
                fontInfo = parseOverlayFontString(fontText);
            } catch (Exception e) {
                // A workaround for corrupt font info in some of the crustacea.net keys.
                System.err.println("Error parsing font info: " + fontText);
                fontInfo = new ImageSettings().getDefaultFontInfo();
            }
            fonts.add(fontInfo);
        }

        ds.setOverlayFonts(fonts);
    }
}

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

@Override
public int remove(final K key, final V value) {
    final int offset = offsetOfKey(key);
    if (offset == NOT_FOUND)
        return 0;

    final int numberOfValues = get(key).size();

    final ByteBuffer buffer = rawPage().bufferForWriting(offset);
    final byte[] buf1 = new byte[keySerializer.getSerializedLength()];
    final byte[] buf2 = new byte[valueSerializer.getSerializedLength()];
    int removed = 0;

    for (int i = 0; i < numberOfValues; i++) {
        buffer.get(buf1);
        buffer.get(buf2); // load only the value
        final V val = valueSerializer.deserialize(buf2);

        if (val == null)
            throw new IllegalStateException("value retrieved from a value page should not be null");

        // we cant use a comparator here since we have none for values (its the only case we need it)
        if (val.equals(value)) {
            // also free key page
            // move pointers forward and reset buffer
            final int startingPos = buffer.position() - buf1.length - buf2.length;
            System.arraycopy(buffer.array(), buffer.position(), buffer.array(), startingPos,
                    buffer.capacity() - buffer.position());

            buffer.position(startingPos);

            removed++;/*from  ww w .  j  av a  2  s.  c  o  m*/
        }
    }

    setNumberOfEntries(getNumberOfEntries() - removed);
    return removed;
}

From source file:com.linkedin.pinot.core.indexsegment.utils.MmapMemoryManagerTest.java

@Test
public void testCornerConditions() throws Exception {
    final String segmentName = "someSegment";
    PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
    final long s1 = MmapMemoryManager.getDefaultFileLength() - 1;
    final long s2 = 1;
    final long s3 = 100 * 1024 * 1024;
    final String colName = "col";
    final byte v1 = 56;
    final byte v2 = 11;
    final byte v3 = 32;

    // Allocate a buffer 1 less than the default file length, and write the last byte of the buffer.
    PinotDataBuffer b1 = memoryManager.allocate(s1, colName);
    ByteBuffer bb1 = b1.toDirectByteBuffer(0, (int) s1);
    bb1.put((int) s1 - 1, v1);

    // Allocate another buffer that is 1 byte in size, should be in the same file.
    // Write a value in the byte.
    PinotDataBuffer b2 = memoryManager.allocate(s2, colName);
    ByteBuffer bb2 = b2.toDirectByteBuffer(0, (int) s2);
    bb2.put((int) s2 - 1, v2);

    // Verify that there is only one file.
    File dir = new File(_tmpDir);
    Assert.assertEquals(dir.listFiles().length, 1);

    // Now allocate another buffer that will open a second file, write a value in the first byte of the buffer.
    PinotDataBuffer b3 = memoryManager.allocate(s3, colName);
    ByteBuffer bb3 = b3.toDirectByteBuffer(0, (int) s3);
    bb3.put(0, v3);/*from w  w  w .  jav  a2s. c om*/

    // Ensure that there are 2 files.
    Assert.assertEquals(dir.listFiles().length, 2);

    // Make sure that the values written are preserved.
    Assert.assertEquals(bb1.get((int) s1 - 1), v1);
    Assert.assertEquals(bb2.get((int) s2 - 1), v2);
    Assert.assertEquals(bb3.get(0), v3);

    memoryManager.close();
    List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
    Assert.assertEquals(allocationContexts.size(), 0);
}

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

protected void updateMap(int absolutePageNumber, int bufferRelativePageNumber, ByteBuffer buffer, boolean add,
        boolean force) throws IOException {
    //Find the byte to which to apply the bitmask and create the bitmask
    int offset = bufferRelativePageNumber / 8;
    int bitmask = 1 << (bufferRelativePageNumber % 8);
    byte b = buffer.get(_startOffset + offset);

    // check current value for this page number
    int pageNumberOffset = pageNumberToBitIndex(absolutePageNumber);
    boolean isOn = _pageNumbers.get(pageNumberOffset);
    if ((isOn == add) && !force) {
        throw new IOException(
                "Page number " + absolutePageNumber + " already " + ((add) ? "added to" : "removed from")
                        + " usage map, expected range " + _startPage + " to " + _endPage);
    }//  ww w.  ja v  a 2s  . c o  m

    //Apply the bitmask
    if (add) {
        b |= bitmask;
        _pageNumbers.set(pageNumberOffset);
    } else {
        b &= ~bitmask;
        _pageNumbers.clear(pageNumberOffset);
    }
    buffer.put(_startOffset + offset, b);
}

From source file:com.vest.album.fragment.CameraBasicFragment.java

private void sureSave() {
    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    FileOutputStream output = null;
    try {//  w  ww. j a  v a  2 s.  co m
        output = new FileOutputStream(mFilePath);
        output.write(bytes);
        callback.onPhotoSuccess(mFilePath);
    } catch (IOException e) {
        e.printStackTrace();
        callback.onPhotoError("??");
    } finally {
        image.close();
        if (null != output) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:au.org.ala.delta.intkey.model.IntkeyDatasetFileReader.java

/**
 * Read character descriptions and states
 * //from  ww w  .  j  a v a  2  s. c  o  m
 * @param charFileHeader
 *            Characters file header data
 * @param charBinFile
 *            Characters file
 * @param characters
 *            List of object representations of dataset characters, ordered
 *            by character number. These objects will be updated with the
 *            read information.
 * @param numCharacterStates
 *            Number of characters for each dataset character, ordered by
 *            character number.
 */
private static void readCharacterDescriptionsAndStates(CharactersFileHeader charFileHeader, BinFile charBinFile,
        List<Character> characters, List<Integer> numCharacterStates) {
    int numChars = charFileHeader.getNC();

    // READ CHARACTER DESCRIPTIONS
    seekToRecord(charBinFile, charFileHeader.getRpCdes());

    List<Integer> charDescriptionRecordIndicies = readIntegerList(charBinFile, numChars);

    for (int i = 0; i < numChars; i++) {
        au.org.ala.delta.model.Character ch = characters.get(i);

        int descRecordIndex = charDescriptionRecordIndicies.get(i);
        seekToRecord(charBinFile, descRecordIndex);

        int numStatesForChar = numCharacterStates.get(i);
        List<Integer> charDescriptionsLengths = readIntegerList(charBinFile, numStatesForChar + 1);
        int lengthTotal = 0;

        for (int charDescriptionLength : charDescriptionsLengths) {
            lengthTotal += charDescriptionLength;
        }

        int recordsSpannedByDescLengths = recordsSpannedByBytes(
                (numStatesForChar + 1) * Constants.SIZE_INT_IN_BYTES);

        List<String> charStateDescriptions = new ArrayList<String>();

        seekToRecord(charBinFile, descRecordIndex + recordsSpannedByDescLengths);
        ByteBuffer descBuffer = charBinFile.readByteBuffer(lengthTotal);

        for (int k = 0; k < charDescriptionsLengths.size(); k++) {
            int len = charDescriptionsLengths.get(k);
            byte[] descArray = new byte[len];
            descBuffer.get(descArray);

            String descriptionText = BinFileEncoding.decode(descArray);

            if (k == 0) {
                // First description listed is the character description
                ch.setDescription(descriptionText);
            } else {
                charStateDescriptions.add(descriptionText);
            }
        }

        if (ch instanceof IntegerCharacter) {
            if (charStateDescriptions.size() == 1) {
                ((IntegerCharacter) ch).setUnits(charStateDescriptions.get(0));
            } else if (charStateDescriptions.size() > 1) {
                throw new RuntimeException(
                        "Integer characters should only have one state listed which represents the units description.");
            }
        } else if (ch instanceof RealCharacter) {
            if (charStateDescriptions.size() == 1) {
                ((RealCharacter) ch).setUnits(charStateDescriptions.get(0));
            } else if (charStateDescriptions.size() > 1) {
                throw new RuntimeException(
                        "Real numeric characters should only have one state listed which represents the units description.");
            }
        } else if (ch instanceof MultiStateCharacter) {
            MultiStateCharacter multiStateChar = (MultiStateCharacter) ch;

            multiStateChar.setNumberOfStates(charStateDescriptions.size());

            for (int l = 0; l < charStateDescriptions.size(); l++) {
                multiStateChar.setState(l + 1, charStateDescriptions.get(l));
            }
        } else {
            if (charStateDescriptions.size() > 0) {
                throw new RuntimeException("Text characters should not have a state specified");
            }
        }
    }
}

From source file:com.koda.integ.hbase.blockcache.OffHeapBlockCacheOld.java

/**
 * Read external.//from ww  w  .  j av  a  2s. c  o m
 *
 * @param blockName the block name
 * @return the cacheable
 * @throws IOException Signals that an I/O exception has occurred.
 */
@SuppressWarnings("unused")
private Cacheable readExternal(String blockName) throws IOException {
    if (overflowExtEnabled == false)
        return null;
    // Check if we have  already this block in external storage cache
    try {
        StorageHandle handle = (StorageHandle) extStorageCache.get(blockName);
        if (handle == null)
            return null;
        ByteBuffer buffer = extStorageCache.getLocalBufferWithAddress().getBuffer();

        buffer.clear();

        StorageHandle newHandle = storage.getData(handle, buffer);
        int size = buffer.getInt(0);
        if (size == 0)
            return null;
        boolean inMemory = buffer.get(4) == (byte) 1;
        buffer.position(5);
        buffer.limit(size + 4);
        if (deserializer.get() == null)
            return null;
        CacheableDeserializer<Cacheable> deserializer = this.deserializer.get();
        Cacheable obj = deserializer.deserialize(buffer);
        if (inMemory) {
            permGenCache.put(blockName, obj);
        } else {
            tenGenCache.put(blockName, obj);
        }

        if (newHandle.equals(handle) == false) {
            extStorageCache.put(blockName, newHandle);
        }

        return obj;

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

}