Example usage for java.nio ByteBuffer putInt

List of usage examples for java.nio ByteBuffer putInt

Introduction

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

Prototype

public abstract ByteBuffer putInt(int value);

Source Link

Document

Writes the given int to the current position and increases the position by 4.

Usage

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

private void writePreV2Journal(File journalDir, int numEntries) throws Exception {
    long logId = System.currentTimeMillis();
    File fn = new File(journalDir, Long.toHexString(logId) + ".txn");

    FileChannel fc = new RandomAccessFile(fn, "rw").getChannel();

    ByteBuffer zeros = ByteBuffer.allocate(512);
    fc.write(zeros, 4 * 1024 * 1024);/*from   w ww.  j a  v a2s  .  c  o  m*/
    fc.position(0);

    byte[] data = "JournalTestData".getBytes();
    long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID;
    for (int i = 1; i <= numEntries; i++) {
        ByteBuffer packet = ClientUtil.generatePacket(1, i, lastConfirmed, i * data.length, data)
                .toByteBuffer();
        lastConfirmed = i;
        ByteBuffer lenBuff = ByteBuffer.allocate(4);
        lenBuff.putInt(packet.remaining());
        lenBuff.flip();

        fc.write(lenBuff);
        fc.write(packet);
    }
}

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

private JournalChannel writeV2Journal(File journalDir, int numEntries) throws Exception {
    long logId = System.currentTimeMillis();
    JournalChannel jc = new JournalChannel(journalDir, logId);

    moveToPosition(jc, JournalChannel.VERSION_HEADER_SIZE);

    BufferedChannel bc = jc.getBufferedChannel();

    byte[] data = new byte[1024];
    Arrays.fill(data, (byte) 'X');
    long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID;
    for (int i = 1; i <= numEntries; i++) {
        ByteBuffer packet = ClientUtil.generatePacket(1, i, lastConfirmed, i * data.length, data)
                .toByteBuffer();/*w ww. j  a va2 s . c  o  m*/
        lastConfirmed = i;
        ByteBuffer lenBuff = ByteBuffer.allocate(4);
        lenBuff.putInt(packet.remaining());
        lenBuff.flip();

        bc.write(lenBuff);
        bc.write(packet);
    }
    bc.flush(true);

    updateJournalVersion(jc, JournalChannel.V2);

    return jc;
}

From source file:io.pcp.parfait.dxm.PcpMmvWriter.java

/**
 * Writes out a PCP MMV table-of-contents block.
 * //from w w w  .  j  a  va  2s .  c  o m
 * @param dataFileBuffer
 *            ByteBuffer positioned at the correct offset in the file for the block
 * @param tocType
 *            the type of TOC block to write
 * @param entryCount
 *            the number of blocks of type tocType to be found in the file
 * @param firstEntryOffset
 *            the offset of the first tocType block, relative to start of the file
 */
private void writeToc(ByteBuffer dataFileBuffer, TocType tocType, int entryCount, int firstEntryOffset) {
    dataFileBuffer.putInt(tocType.identifier);
    dataFileBuffer.putInt(entryCount);
    dataFileBuffer.putLong(firstEntryOffset);
}

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

private JournalChannel writeV3Journal(File journalDir, int numEntries, byte[] masterKey) throws Exception {
    long logId = System.currentTimeMillis();
    JournalChannel jc = new JournalChannel(journalDir, logId);

    moveToPosition(jc, JournalChannel.VERSION_HEADER_SIZE);

    BufferedChannel bc = jc.getBufferedChannel();

    byte[] data = new byte[1024];
    Arrays.fill(data, (byte) 'X');
    long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID;
    for (int i = 0; i <= numEntries; i++) {
        ByteBuffer packet;/*from  w w  w .  j a  va2  s. c o  m*/
        if (i == 0) {
            packet = generateMetaEntry(1, masterKey);
        } else {
            packet = ClientUtil.generatePacket(1, i, lastConfirmed, i * data.length, data).toByteBuffer();
        }
        lastConfirmed = i;
        ByteBuffer lenBuff = ByteBuffer.allocate(4);
        lenBuff.putInt(packet.remaining());
        lenBuff.flip();

        bc.write(lenBuff);
        bc.write(packet);
    }
    bc.flush(true);

    updateJournalVersion(jc, JournalChannel.V3);

    return jc;
}

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

private JournalChannel writeV4Journal(File journalDir, int numEntries, byte[] masterKey) throws Exception {
    long logId = System.currentTimeMillis();
    JournalChannel jc = new JournalChannel(journalDir, logId);

    moveToPosition(jc, JournalChannel.VERSION_HEADER_SIZE);

    BufferedChannel bc = jc.getBufferedChannel();

    byte[] data = new byte[1024];
    Arrays.fill(data, (byte) 'X');
    long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID;
    for (int i = 0; i <= numEntries; i++) {
        ByteBuffer packet;/*from w ww.  j  a v a 2  s.  c o m*/
        if (i == 0) {
            packet = generateMetaEntry(1, masterKey);
        } else {
            packet = ClientUtil.generatePacket(1, i, lastConfirmed, i * data.length, data).toByteBuffer();
        }
        lastConfirmed = i;
        ByteBuffer lenBuff = ByteBuffer.allocate(4);
        lenBuff.putInt(packet.remaining());
        lenBuff.flip();
        bc.write(lenBuff);
        bc.write(packet);
    }
    // write fence key
    ByteBuffer packet = generateFenceEntry(1);
    ByteBuffer lenBuf = ByteBuffer.allocate(4);
    lenBuf.putInt(packet.remaining());
    lenBuf.flip();
    bc.write(lenBuf);
    bc.write(packet);
    bc.flush(true);
    updateJournalVersion(jc, JournalChannel.V4);
    return jc;
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

public void setSampleRateManual(int frequency, int divider) throws UsbException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(8);

    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(frequency);
    buffer.putInt(divider);/*from   w  ww. j av  a2 s  . c o m*/

    write(Request.SET_SAMPLE_RATE, 0, 0, buffer);
}

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

private JournalChannel writeV5Journal(File journalDir, int numEntries, byte[] masterKey) throws Exception {
    long logId = System.currentTimeMillis();
    JournalChannel jc = new JournalChannel(journalDir, logId);

    BufferedChannel bc = jc.getBufferedChannel();

    ByteBuffer paddingBuff = ByteBuffer.allocateDirect(2 * JournalChannel.SECTOR_SIZE);
    ZeroBuffer.put(paddingBuff);//from w w  w . j  a  v  a2s  .c om
    byte[] data = new byte[4 * 1024 * 1024];
    Arrays.fill(data, (byte) 'X');
    long lastConfirmed = LedgerHandle.INVALID_ENTRY_ID;
    long length = 0;
    for (int i = 0; i <= numEntries; i++) {
        ByteBuffer packet;
        if (i == 0) {
            packet = generateMetaEntry(1, masterKey);
        } else {
            packet = ClientUtil.generatePacket(1, i, lastConfirmed, length, data, 0, i).toByteBuffer();
        }
        lastConfirmed = i;
        length += i;
        ByteBuffer lenBuff = ByteBuffer.allocate(4);
        lenBuff.putInt(packet.remaining());
        lenBuff.flip();
        bc.write(lenBuff);
        bc.write(packet);
        Journal.writePaddingBytes(jc, paddingBuff, JournalChannel.SECTOR_SIZE);
    }
    // write fence key
    ByteBuffer packet = generateFenceEntry(1);
    ByteBuffer lenBuf = ByteBuffer.allocate(4);
    lenBuf.putInt(packet.remaining());
    lenBuf.flip();
    bc.write(lenBuf);
    bc.write(packet);
    Journal.writePaddingBytes(jc, paddingBuff, JournalChannel.SECTOR_SIZE);
    bc.flush(true);
    updateJournalVersion(jc, JournalChannel.V5);
    return jc;
}

From source file:tor.TorCircuit.java

/**
 * Creates a stream using this circuit and connects to a host
 *
 * @param host Hostname/ip/*from  w  ww. java  2s.co  m*/
 * @param port Port
 * @param list A listener for stream events
 * @return TorStream object
 */
public TorStream createStream(String host, int port, TorStream.TorStreamListener list) throws IOException {
    if (state == STATES.DESTROYED) {
        log.error("Trying to use destroyed circuit");
        throw new RuntimeException("Trying to use destroyed circuit");
    }

    byte b[] = new byte[100];
    ByteBuffer buf = ByteBuffer.wrap(b);
    buf.put((host + ":" + port).getBytes("UTF-8"));
    buf.put((byte) 0); // null terminator
    buf.putInt(0);
    //TODO: allocate stream and circuit IDS properly
    int stid = streamId_counter++;
    send(b, RELAY_BEGIN, false, (short) stid);
    TorStream st = new TorStream(stid, this, list);
    streams.put(stid, st);
    return st;
}

From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java

@Test
public void testMultipleGetWithRangeAsync() throws IOException, URISyntaxException, InterruptedException {
    final String testResourceUrl = servletRoot + "/foo.txt";

    // prepare 8MiB test data:
    final byte[] plaintextData = new byte[2097152 * Integer.BYTES];
    final ByteBuffer plaintextDataByteBuffer = ByteBuffer.wrap(plaintextData);
    for (int i = 0; i < 2097152; i++) {
        plaintextDataByteBuffer.putInt(i);
    }//from w  w  w  .  j  ava  2s.  c o m
    try (WritableFile w = fs.file("foo.txt").openWritable()) {
        plaintextDataByteBuffer.flip();
        w.write(plaintextDataByteBuffer);
    }

    final MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager();
    cm.getParams().setDefaultMaxConnectionsPerHost(50);
    final HttpClient client = new HttpClient(cm);

    // multiple async range requests:
    final List<ForkJoinTask<?>> tasks = new ArrayList<>();
    final Random generator = new Random(System.currentTimeMillis());

    final AtomicBoolean success = new AtomicBoolean(true);

    // 10 full interrupted requests:
    for (int i = 0; i < 10; i++) {
        final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> {
            try {
                final HttpMethod getMethod = new GetMethod(testResourceUrl);
                final int statusCode = client.executeMethod(getMethod);
                if (statusCode != 200) {
                    LOG.error("Invalid status code for interrupted full request");
                    success.set(false);
                }
                getMethod.getResponseBodyAsStream().read();
                getMethod.getResponseBodyAsStream().close();
                getMethod.releaseConnection();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        tasks.add(task);
    }

    // 50 crappy interrupted range requests:
    for (int i = 0; i < 50; i++) {
        final int lower = generator.nextInt(plaintextData.length);
        final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> {
            try {
                final HttpMethod getMethod = new GetMethod(testResourceUrl);
                getMethod.addRequestHeader("Range", "bytes=" + lower + "-");
                final int statusCode = client.executeMethod(getMethod);
                if (statusCode != 206) {
                    LOG.error("Invalid status code for interrupted range request");
                    success.set(false);
                }
                getMethod.getResponseBodyAsStream().read();
                getMethod.getResponseBodyAsStream().close();
                getMethod.releaseConnection();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        tasks.add(task);
    }

    // 50 normal open range requests:
    for (int i = 0; i < 50; i++) {
        final int lower = generator.nextInt(plaintextData.length - 512);
        final int upper = plaintextData.length - 1;
        final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> {
            try {
                final HttpMethod getMethod = new GetMethod(testResourceUrl);
                getMethod.addRequestHeader("Range", "bytes=" + lower + "-");
                final byte[] expected = Arrays.copyOfRange(plaintextData, lower, upper + 1);
                final int statusCode = client.executeMethod(getMethod);
                final byte[] responseBody = new byte[upper - lower + 10];
                final int bytesRead = IOUtils.read(getMethod.getResponseBodyAsStream(), responseBody);
                getMethod.releaseConnection();
                if (statusCode != 206) {
                    LOG.error("Invalid status code for open range request");
                    success.set(false);
                } else if (upper - lower + 1 != bytesRead) {
                    LOG.error("Invalid response length for open range request");
                    success.set(false);
                } else if (!Arrays.equals(expected, Arrays.copyOfRange(responseBody, 0, bytesRead))) {
                    LOG.error("Invalid response body for open range request");
                    success.set(false);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        tasks.add(task);
    }

    // 200 normal closed range requests:
    for (int i = 0; i < 200; i++) {
        final int pos1 = generator.nextInt(plaintextData.length - 512);
        final int pos2 = pos1 + 512;
        final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> {
            try {
                final int lower = Math.min(pos1, pos2);
                final int upper = Math.max(pos1, pos2);
                final HttpMethod getMethod = new GetMethod(testResourceUrl);
                getMethod.addRequestHeader("Range", "bytes=" + lower + "-" + upper);
                final byte[] expected = Arrays.copyOfRange(plaintextData, lower, upper + 1);
                final int statusCode = client.executeMethod(getMethod);
                final byte[] responseBody = new byte[upper - lower + 1];
                final int bytesRead = IOUtils.read(getMethod.getResponseBodyAsStream(), responseBody);
                getMethod.releaseConnection();
                if (statusCode != 206) {
                    LOG.error("Invalid status code for closed range request");
                    success.set(false);
                } else if (upper - lower + 1 != bytesRead) {
                    LOG.error("Invalid response length for closed range request");
                    success.set(false);
                } else if (!Arrays.equals(expected, Arrays.copyOfRange(responseBody, 0, bytesRead))) {
                    LOG.error("Invalid response body for closed range request");
                    success.set(false);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        tasks.add(task);
    }

    Collections.shuffle(tasks, generator);

    final ForkJoinPool pool = new ForkJoinPool(4);
    for (ForkJoinTask<?> task : tasks) {
        pool.execute(task);
    }
    for (ForkJoinTask<?> task : tasks) {
        task.join();
    }
    pool.shutdown();
    cm.shutdown();

    Assert.assertTrue(success.get());
}

From source file:tor.TorCircuit.java

/**
 * Builds a relay cell payload (not including cell header, only relay header)
 *
 * @param toHop   Hop that it's destined for
 * @param cmd     Command ID, see RELAY_
 * @param stream  Stream ID//from   www. j av a 2  s . c  om
 * @param payload Relay cell data
 * @return Constructed relay payload
 */
protected synchronized byte[] buildRelay(TorHop toHop, int cmd, short stream, byte[] payload) {
    byte[] fnl = new byte[509];
    ByteBuffer buf = ByteBuffer.wrap(fnl);
    buf.put((byte) cmd);
    buf.putShort((short) 0); // recognised
    buf.putShort(stream);
    buf.putInt(0); // digest

    if (payload != null) {
        buf.putShort((short) payload.length);
        buf.put(payload);
    } else {
        buf.putShort((short) 0);
    }

    toHop.df_md.update(fnl);
    MessageDigest md;
    try {
        md = (MessageDigest) toHop.df_md.clone();

        byte digest[] = md.digest();

        //byte [] fnl_final = new byte[509];
        System.arraycopy(digest, 0, fnl, 5, 4);

        return fnl;
    } catch (CloneNotSupportedException e) {
        throw new RuntimeException(e);
    }

}