Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public abstract ByteBuffer put(int index, byte b);

Source Link

Document

Write a byte to the specified index of this buffer without changing the position.

Usage

From source file:com.arpnetworking.tsdcore.sinks.KairosDbSink.java

private void addChunk(final ByteArrayOutputStream chunkStream, final ByteBuffer currentChunk,
        final Collection<byte[]> completedChunks) {
    final byte[] nextChunk = chunkStream.toByteArray();
    final int nextChunkSize = nextChunk.length;
    if (currentChunk.position() + nextChunkSize > _maxRequestSize) {
        if (currentChunk.position() > HEADER_BYTE_LENGTH) {
            // TODO(vkoskela): Add chunk size metric. [MAI-?]

            // Copy the relevant part of the buffer
            currentChunk.put(currentChunk.position() - 1, FOOTER);
            completedChunks.add(Arrays.copyOf(currentChunk.array(), currentChunk.position()));

            // Truncate all but the beginning '[' to prepare the next entries
            currentChunk.clear();/*from ww  w.j  a  v  a 2  s  . c om*/
            currentChunk.put(HEADER);
        } else {
            CHUNK_TOO_BIG_LOGGER.warn().setMessage("First chunk too big").addData("sink", getName())
                    .addData("bufferLength", currentChunk.position()).addData("nextChunkSize", nextChunkSize)
                    .addData("maxRequestSIze", _maxRequestSize).log();
        }
    }

    currentChunk.put(nextChunk);
    currentChunk.put(SEPARATOR);
    chunkStream.reset();
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFoldWithUpperNibbleTriggersOffsetChange() throws Exception {
    byte[] arr1 = new byte[HyperLogLogCollector.getLatestNumBytesForDenseStorage()];
    Arrays.fill(arr1, (byte) 0x11);
    ByteBuffer buffer1 = ByteBuffer.wrap(arr1);
    buffer1.put(0, HLLCV1.VERSION);
    buffer1.put(1, (byte) 0);
    buffer1.putShort(2, (short) (2047));
    buffer1.put(HLLCV1.HEADER_NUM_BYTES, (byte) 0x1);

    byte[] arr2 = new byte[HyperLogLogCollector.getLatestNumBytesForDenseStorage()];
    Arrays.fill(arr2, (byte) 0x11);
    ByteBuffer buffer2 = ByteBuffer.wrap(arr2);
    buffer2.put(0, HLLCV1.VERSION);//from  ww w  . ja  v a2s  . c  o  m
    buffer2.put(1, (byte) 0);
    buffer2.putShort(2, (short) (2048));

    HyperLogLogCollector collector = HyperLogLogCollector.makeCollector(buffer1);
    collector.fold(buffer2);

    ByteBuffer outBuffer = collector.toByteBuffer();

    Assert.assertEquals(outBuffer.get(), HLLCV1.VERSION);
    Assert.assertEquals(outBuffer.get(), 1);
    Assert.assertEquals(outBuffer.getShort(), 0);
    outBuffer.get();
    outBuffer.getShort();
    Assert.assertFalse(outBuffer.hasRemaining());
}

From source file:com.twitter.distributedlog.service.TestDistributedLogService.java

@Test(timeout = 60000)
public void testWriteOpChecksumBadData() throws Exception {
    DistributedLogServiceImpl localService = createConfiguredLocalService();
    ByteBuffer buffer = getTestDataBuffer();
    WriteContext ctx = new WriteContext().setCrc32(ProtocolUtils.writeOpCRC32("test", buffer.array()));

    // Overwrite 1 byte to corrupt data.
    buffer.put(1, (byte) 0xab);
    Future<WriteResponse> result = localService.writeWithContext("test", buffer, ctx);
    WriteResponse resp = Await.result(result);
    assertEquals(StatusCode.CHECKSUM_FAILED, resp.getHeader().getCode());
    localService.shutdown();//from  ww  w.j  a v  a 2s  .c  o  m
}

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);
    }/*from   w  w  w  .  j a v  a2s.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:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

/**
 * writes channel LUTs and display ranges for composite mode Could also be
 * expanded to write ROIs, file info, slice labels, and overlays
 *//* w  ww  .  j  a  va 2  s . com*/
private void writeImageJMetadata(int numChannels, String summaryComment) throws IOException {
    String info = summaryMDString_;
    if (summaryComment != null && summaryComment.length() > 0) {
        info = "Acquisition comments: \n" + summaryComment + "\n\n\n" + summaryMDString_;
    }
    //size entry (4 bytes) + 4 bytes file info size + 4 bytes for channel display 
    //ranges length + 4 bytes per channel LUT
    int mdByteCountsBufferSize = 4 + 4 + 4 + 4 * numChannels;
    int bufferPosition = 0;

    ByteBuffer mdByteCountsBuffer = ByteBuffer.allocate(mdByteCountsBufferSize).order(BYTE_ORDER);

    //nTypes is number actually written among: fileInfo, slice labels, display ranges, channel LUTS,
    //slice labels, ROI, overlay, and # of extra metadata entries
    int nTypes = 3; //file info, display ranges, and channel LUTs
    int mdBufferSize = 4 + nTypes * 8;

    //Header size: 4 bytes for magic number + 8 bytes for label (int) and count (int) of each type
    mdByteCountsBuffer.putInt(bufferPosition, 4 + nTypes * 8);
    bufferPosition += 4;

    //2 bytes per a character of file info
    mdByteCountsBuffer.putInt(bufferPosition, 2 * info.length());
    bufferPosition += 4;
    mdBufferSize += info.length() * 2;

    //display ranges written as array of doubles (min, max, min, max, etc)
    mdByteCountsBuffer.putInt(bufferPosition, numChannels * 2 * 8);
    bufferPosition += 4;
    mdBufferSize += numChannels * 2 * 8;

    for (int i = 0; i < numChannels; i++) {
        //768 bytes per LUT
        mdByteCountsBuffer.putInt(bufferPosition, 768);
        bufferPosition += 4;
        mdBufferSize += 768;
    }

    //Header (1) File info (1) display ranges (1) LUTS (1 per channel)
    int numMDEntries = 3 + numChannels;
    ByteBuffer ifdCountAndValueBuffer = ByteBuffer.allocate(8).order(BYTE_ORDER);
    ifdCountAndValueBuffer.putInt(0, numMDEntries);
    ifdCountAndValueBuffer.putInt(4, (int) filePosition_);
    fileChannel_.write(ifdCountAndValueBuffer, ijMetadataCountsTagPosition_ + 4);

    fileChannel_.write(mdByteCountsBuffer, filePosition_);
    filePosition_ += mdByteCountsBufferSize;

    //Write metadata types and counts
    ByteBuffer mdBuffer = ByteBuffer.allocate(mdBufferSize).order(BYTE_ORDER);
    bufferPosition = 0;

    //All the ints declared below are non public field in TiffDecoder
    final int ijMagicNumber = 0x494a494a;
    mdBuffer.putInt(bufferPosition, ijMagicNumber);
    bufferPosition += 4;

    //Write ints for each IJ metadata field and its count
    final int fileInfo = 0x696e666f;
    mdBuffer.putInt(bufferPosition, fileInfo);
    bufferPosition += 4;
    mdBuffer.putInt(bufferPosition, 1);
    bufferPosition += 4;

    final int displayRanges = 0x72616e67;
    mdBuffer.putInt(bufferPosition, displayRanges);
    bufferPosition += 4;
    mdBuffer.putInt(bufferPosition, 1);
    bufferPosition += 4;

    final int luts = 0x6c757473;
    mdBuffer.putInt(bufferPosition, luts);
    bufferPosition += 4;
    mdBuffer.putInt(bufferPosition, numChannels);
    bufferPosition += 4;

    //write actual metadata
    //FileInfo
    for (char c : info.toCharArray()) {
        mdBuffer.putChar(bufferPosition, c);
        bufferPosition += 2;
    }
    try {
        JSONArray channels = masterMPTiffStorage_.getDisplayAndComments().getJSONArray("Channels");
        JSONObject channelSetting;
        for (int i = 0; i < numChannels; i++) {
            channelSetting = channels.getJSONObject(i);
            //Display Ranges: For each channel, write min then max
            mdBuffer.putDouble(bufferPosition, channelSetting.getInt("Min"));
            bufferPosition += 8;
            mdBuffer.putDouble(bufferPosition, channelSetting.getInt("Max"));
            bufferPosition += 8;
        }

        //LUTs
        for (int i = 0; i < numChannels; i++) {
            channelSetting = channels.getJSONObject(i);
            LUT lut = ImageUtils.makeLUT(new Color(channelSetting.getInt("Color")),
                    channelSetting.getDouble("Gamma"));
            for (byte b : lut.getBytes()) {
                mdBuffer.put(bufferPosition, b);
                bufferPosition++;
            }
        }
    } catch (JSONException ex) {
        ReportingUtils.logError(
                "Problem with displayAndComments: Couldn't write ImageJ display settings as a result");
    }

    ifdCountAndValueBuffer = ByteBuffer.allocate(8).order(BYTE_ORDER);
    ifdCountAndValueBuffer.putInt(0, mdBufferSize);
    ifdCountAndValueBuffer.putInt(4, (int) filePosition_);
    fileChannel_.write(ifdCountAndValueBuffer, ijMetadataTagPosition_ + 4);

    fileChannel_.write(mdBuffer, filePosition_);
    filePosition_ += mdBufferSize;
}