Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:com.sm.store.Utils.java

public static byte[] putInt(int k) {
    return ByteBuffer.allocate(4).putInt(k).array();
}

From source file:Main.java

public static long getCommentLength(final FileChannel fileChannel) throws IOException {
    // End of central directory record (EOCD)
    // Offset    Bytes     Description[23]
    // 0           4       End of central directory signature = 0x06054b50
    // 4           2       Number of this disk
    // 6           2       Disk where central directory starts
    // 8           2       Number of central directory records on this disk
    // 10          2       Total number of central directory records
    // 12          4       Size of central directory (bytes)
    // 16          4       Offset of start of central directory, relative to start of archive
    // 20          2       Comment length (n)
    // 22          n       Comment
    // For a zip with no archive comment, the
    // end-of-central-directory record will be 22 bytes long, so
    // we expect to find the EOCD marker 22 bytes from the end.

    final long archiveSize = fileChannel.size();
    if (archiveSize < ZIP_EOCD_REC_MIN_SIZE) {
        throw new IOException("APK too small for ZIP End of Central Directory (EOCD) record");
    }/*from   www .  j av  a 2  s  . c om*/
    // ZIP End of Central Directory (EOCD) record is located at the very end of the ZIP archive.
    // The record can be identified by its 4-byte signature/magic which is located at the very
    // beginning of the record. A complication is that the record is variable-length because of
    // the comment field.
    // The algorithm for locating the ZIP EOCD record is as follows. We search backwards from
    // end of the buffer for the EOCD record signature. Whenever we find a signature, we check
    // the candidate record's comment length is such that the remainder of the record takes up
    // exactly the remaining bytes in the buffer. The search is bounded because the maximum
    // size of the comment field is 65535 bytes because the field is an unsigned 16-bit number.
    final long maxCommentLength = Math.min(archiveSize - ZIP_EOCD_REC_MIN_SIZE, UINT16_MAX_VALUE);
    final long eocdWithEmptyCommentStartPosition = archiveSize - ZIP_EOCD_REC_MIN_SIZE;
    for (int expectedCommentLength = 0; expectedCommentLength <= maxCommentLength; expectedCommentLength++) {
        final long eocdStartPos = eocdWithEmptyCommentStartPosition - expectedCommentLength;

        final ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        fileChannel.position(eocdStartPos);
        fileChannel.read(byteBuffer);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);

        if (byteBuffer.getInt(0) == ZIP_EOCD_REC_SIG) {
            final ByteBuffer commentLengthByteBuffer = ByteBuffer.allocate(2);
            fileChannel.position(eocdStartPos + ZIP_EOCD_COMMENT_LENGTH_FIELD_OFFSET);
            fileChannel.read(commentLengthByteBuffer);
            commentLengthByteBuffer.order(ByteOrder.LITTLE_ENDIAN);

            final int actualCommentLength = commentLengthByteBuffer.getShort(0);
            if (actualCommentLength == expectedCommentLength) {
                return actualCommentLength;
            }
        }
    }
    throw new IOException("ZIP End of Central Directory (EOCD) record not found");
}

From source file:com.fujitsu.dc.test.jersey.bar.BarInstallTestUtils.java

/**
 * bar?.//  w  w w .  ja  va2s . c o  m
 * @param barFile bar?
 * @return ??bar
 */
public static byte[] readBarFile(File barFile) {
    InputStream is = ClassLoader.getSystemResourceAsStream(barFile.getPath());
    ByteBuffer buff = ByteBuffer.allocate(READ_BUFFER_SIZE);
    log.debug(String.valueOf(buff.capacity()));
    try {
        byte[] bbuf = new byte[SIZE_KB];
        int size;
        while ((size = is.read(bbuf)) != -1) {
            buff.put(bbuf, 0, size);
        }
    } catch (IOException e) {
        throw new RuntimeException("failed to load bar file:" + barFile.getPath(), e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException("failed to close bar file:" + barFile.getPath(), e);
        }
    }
    int size = buff.position();
    buff.flip();
    byte[] retv = new byte[size];
    buff.get(retv, 0, size);
    return retv;
}

From source file:com.linkedin.pinot.perf.BenchmarkFileRead.java

@Setup
public void loadData() {
    try {//from ww w .  ja v a2s.  c o m
        file = new File("/Users/jfim/index_dir/sTest_OFFLINE/sTest_0_0/daysSinceEpoch.sv.unsorted.fwd");
        raf = new RandomAccessFile(file, "rw");
        length = (int) file.length();
        byteBuffer = ByteBuffer.allocate(length);
        raf.getChannel().read(byteBuffer);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.datatorrent.contrib.hdht.HDHTWriterTest.java

public static Slice newKey(long bucketId, long sequenceId) {
    byte[] bytes = ByteBuffer.allocate(16).putLong(sequenceId).putLong(bucketId).array();
    return new Slice(bytes, 0, bytes.length);
}

From source file:jsave.Utils.java

public static int read_long(final RandomAccessFile raf) throws IOException {
    byte[] data = new byte[4];
    raf.read(data);/*  w  w  w.  ja  v  a 2 s  . c  om*/
    ByteBuffer bb = ByteBuffer.allocate(data.length);
    bb.put(data);
    return bb.getInt(0);
}

From source file:com.codeabovelab.dm.common.security.token.SignedTokenServiceBackend.java

@Override
public TokenData createToken(TokenConfiguration config) {
    final long creationTime = System.currentTimeMillis();

    byte[] serverSecret = computeServerSecretApplicableAt(creationTime);
    byte[] content = contentPack(creationTime, generateRandom(), serverSecret,
            Utf8.encode(pack(config.getUserName(), config.getDeviceHash())));

    byte[] sign = sign(content);
    ByteBuffer buffer = ByteBuffer.allocate(1 + sign.length + 1 + content.length);
    store(buffer, content);/*  w ww.j a  v  a2s.  c  o  m*/
    store(buffer, sign);
    String key = base32.encodeAsString(buffer.array());

    return new TokenDataImpl(creationTime, TokenUtils.getKeyWithTypeAndToken(TYPE, key), config.getUserName(),
            config.getDeviceHash());
}

From source file:com.github.neoio.net.message.staging.file.TestFileMessageStaging.java

@Test
public void test_tempWrite() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.flip();//  w w  w .jav a  2s  . c o m
    staging.writeTempWriteBytes(buffer);
    Assert.assertTrue(staging.hasTempWriteBytes());

    buffer.clear();
    staging.readTempWriteBytes(buffer);
    Assert.assertEquals("Hello World",
            new String(ArrayUtils.subarray(buffer.array(), 0, "Hello World".getBytes().length)));
    staging.resetTempWriteBytes();

    Assert.assertFalse(staging.hasTempWriteBytes());
}

From source file:com.offbynull.peernetic.debug.actornetwork.messages.TransitMessage.java

/**
 * Constructs a {@link TransitMessage} object.
 * @param source source//from www .j  av a 2s.  c  o  m
 * @param destination destination
 * @param data contents
 * @param departTime time packet departed
 * @param duration duration the packet should stay in transit (before arriving)
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code duration} is negative
 */
public TransitMessage(A source, A destination, ByteBuffer data, Instant departTime, Duration duration) {
    Validate.notNull(source);
    Validate.notNull(destination);
    Validate.notNull(data);
    Validate.notNull(departTime);
    Validate.notNull(duration);
    Validate.isTrue(!duration.isNegative());
    this.source = source;
    this.destination = destination;
    this.data = ByteBuffer.allocate(data.remaining());
    this.data.put(data);
    this.data.flip();
    this.departTime = departTime;
    this.duration = duration;
}

From source file:com.sm.store.Utils.java

public static byte[] putLong(long k) {
    return ByteBuffer.allocate(8).putLong(k).array();
}