Example usage for java.lang Long BYTES

List of usage examples for java.lang Long BYTES

Introduction

In this page you can find the example usage for java.lang Long BYTES.

Prototype

int BYTES

To view the source code for java.lang Long BYTES.

Click Source Link

Document

The number of bytes used to represent a long value in two's complement binary form.

Usage

From source file:org.apache.airavata.gfac.core.GFacUtils.java

public static long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bytes);//from w ww  . j  a  va2 s  . c  o  m
    buffer.flip();//need flip
    return buffer.getLong();
}

From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java

private void setupKeepAlive(final int keepAliveInterval) {
    if (keepAliveHandle != null)
        LOG.fatal("Setting up a KeepAlive runnable while the previous one seems to still be active!!");

    Runnable keepAliveRunnable = () -> {
        if (socket.isOpen() && socket.isOpen() && !udpSocket.isClosed()) {
            send(new JSONObject().put("op", 3).put("d", System.currentTimeMillis()).toString());

            long seq = 0;
            try {
                ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + 1);
                buffer.put((byte) 0xC9);
                buffer.putLong(seq);/*  w w  w.  j  a v a  2s. co m*/
                DatagramPacket keepAlivePacket = new DatagramPacket(buffer.array(), buffer.array().length,
                        address);
                udpSocket.send(keepAlivePacket);

            } catch (NoRouteToHostException e) {
                LOG.warn("Closing AudioConnection due to inability to ping audio packets.");
                LOG.warn("Cannot send audio packet because JDA navigate the route to Discord.\n"
                        + "Are you sure you have internet connection? It is likely that you've lost connection.");
                AudioWebSocket.this.close(ConnectionStatus.ERROR_LOST_CONNECTION);
            } catch (IOException e) {
                LOG.log(e);
            }
        }
    };

    try {
        keepAliveHandle = keepAlivePool.scheduleAtFixedRate(keepAliveRunnable, 0, keepAliveInterval,
                TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException ignored) {
    } //ignored because this is probably caused due to a race condition
      // related to the threadpool shutdown.
}

From source file:org.apache.storm.cluster.StormClusterStateImpl.java

/**
 * If znode exists and timestamp is non-positive, delete;
 * if exists and timestamp is larger than 0, update the timestamp;
 * if not exists and timestamp is larger than 0, create the znode and set the timestamp;
 * if not exists and timestamp is non-positive, do nothing.
 * @param stormId The topology Id//from  ww w. ja v a2 s . co  m
 * @param node The node id
 * @param port The port number
 * @param timestamp The backpressure timestamp. Non-positive means turning off the worker backpressure
 */
@Override
public void workerBackpressure(String stormId, String node, Long port, long timestamp) {
    String path = ClusterUtils.backpressurePath(stormId, node, port);
    boolean existed = stateStorage.node_exists(path, false);
    if (existed) {
        if (timestamp <= 0) {
            stateStorage.delete_node(path);
        } else {
            byte[] data = ByteBuffer.allocate(Long.BYTES).putLong(timestamp).array();
            stateStorage.set_data(path, data, acls);
        }
    } else {
        if (timestamp > 0) {
            byte[] data = ByteBuffer.allocate(Long.BYTES).putLong(timestamp).array();
            stateStorage.set_ephemeral_node(path, data, acls);
        }
    }
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> createMarkerData(int segmentNumber, long timestamp) {
    byte[] b = new byte[Long.BYTES];
    BitConverter.writeLong(b, 0, timestamp);
    synchronized (markersLock) {
        markers.putIfAbsent(segmentNumber, new Data<>(b, 0));
    }/* ww w .  j a v  a  2s . c  o m*/
    return CompletableFuture.completedFuture(null);
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

@Override
public Long decryptRange(SeekableByteChannel encryptedFile, OutputStream plaintextFile, long pos, long length)
        throws IOException {
    // read iv:// w  ww .ja va2  s .  c  o  m
    encryptedFile.position(0);
    final ByteBuffer countingIv = ByteBuffer.allocate(AES_BLOCK_LENGTH);
    final int numIvBytesRead = encryptedFile.read(countingIv);

    // check validity of header:
    if (numIvBytesRead != AES_BLOCK_LENGTH) {
        throw new IOException("Failed to read file header.");
    }

    // seek relevant position and update iv:
    long firstRelevantBlock = pos / AES_BLOCK_LENGTH; // cut of fraction!
    long beginOfFirstRelevantBlock = firstRelevantBlock * AES_BLOCK_LENGTH;
    long offsetInsideFirstRelevantBlock = pos - beginOfFirstRelevantBlock;
    countingIv.putLong(AES_BLOCK_LENGTH - Long.BYTES, firstRelevantBlock);

    // fast forward stream:
    encryptedFile.position(64 + beginOfFirstRelevantBlock);

    // generate cipher:
    final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.DECRYPT_MODE);

    // read content
    final InputStream in = new SeekableByteChannelInputStream(encryptedFile);
    final InputStream cipheredIn = new CipherInputStream(in, cipher);
    return IOUtils.copyLarge(cipheredIn, plaintextFile, offsetInsideFirstRelevantBlock, length);
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

@Override
public Long encryptFile(InputStream plaintextFile, SeekableByteChannel encryptedFile) throws IOException {
    // truncate file
    encryptedFile.truncate(0);/*from  w  ww . j a  v  a2  s . co m*/

    // use an IV, whose last 8 bytes store a long used in counter mode and write initial value to file.
    final ByteBuffer countingIv = ByteBuffer.wrap(randomData(AES_BLOCK_LENGTH));
    countingIv.putLong(AES_BLOCK_LENGTH - Long.BYTES, 0l);
    countingIv.position(0);
    encryptedFile.write(countingIv);

    // init crypto stuff:
    final Mac mac = this.hmacSha256(hMacMasterKey);
    final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.ENCRYPT_MODE);

    // init mac buffer and skip 32 bytes
    final ByteBuffer macBuffer = ByteBuffer.allocate(mac.getMacLength());
    encryptedFile.write(macBuffer);

    // init filesize buffer and skip 16 bytes
    final ByteBuffer encryptedFileSizeBuffer = ByteBuffer.allocate(AES_BLOCK_LENGTH);
    encryptedFile.write(encryptedFileSizeBuffer);

    // write content:
    final OutputStream out = new SeekableByteChannelOutputStream(encryptedFile);
    final OutputStream macOut = new MacOutputStream(out, mac);
    final OutputStream cipheredOut = new CipherOutputStream(macOut, cipher);
    final OutputStream blockSizeBufferedOut = new BufferedOutputStream(cipheredOut, AES_BLOCK_LENGTH);
    final Long plaintextSize = IOUtils.copyLarge(plaintextFile, blockSizeBufferedOut);

    // ensure total byte count is a multiple of the block size, in CTR mode:
    final int remainderToFillLastBlock = AES_BLOCK_LENGTH - (int) (plaintextSize % AES_BLOCK_LENGTH);
    blockSizeBufferedOut.write(new byte[remainderToFillLastBlock]);

    // append a few blocks of fake data:
    final int numberOfPlaintextBlocks = (int) Math.ceil(plaintextSize / AES_BLOCK_LENGTH);
    final int upToTenPercentFakeBlocks = (int) Math.ceil(Math.random() * 0.1 * numberOfPlaintextBlocks);
    final byte[] emptyBytes = new byte[AES_BLOCK_LENGTH];
    for (int i = 0; i < upToTenPercentFakeBlocks; i += AES_BLOCK_LENGTH) {
        blockSizeBufferedOut.write(emptyBytes);
    }
    blockSizeBufferedOut.flush();

    // write MAC of total ciphertext:
    macBuffer.position(0);
    macBuffer.put(mac.doFinal());
    macBuffer.position(0);
    encryptedFile.position(16); // right behind the IV
    encryptedFile.write(macBuffer); // 256 bit MAC

    // encrypt and write plaintextSize
    try {
        final ByteBuffer fileSizeBuffer = ByteBuffer.allocate(Long.BYTES);
        fileSizeBuffer.putLong(plaintextSize);
        final Cipher sizeCipher = aesEcbCipher(primaryMasterKey, Cipher.ENCRYPT_MODE);
        final byte[] encryptedFileSize = sizeCipher.doFinal(fileSizeBuffer.array());
        encryptedFileSizeBuffer.position(0);
        encryptedFileSizeBuffer.put(encryptedFileSize);
        encryptedFileSizeBuffer.position(0);
        encryptedFile.position(48); // right behind the IV and MAC
        encryptedFile.write(encryptedFileSizeBuffer);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        throw new IllegalStateException(
                "Block size must be valid, as padding is requested. BadPaddingException not possible in encrypt mode.",
                e);
    }

    return plaintextSize;
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@Test(timeout = SHORT_TIMEOUT_MILLIS, expected = IllegalArgumentException.class)
public void mappingFileWithPageSizeSmallerThanLongSizeBytesMustThrow() throws IOException {
    // Because otherwise we cannot ensure that our branch-free bounds checking always lands within a page boundary.
    PageCache cache = getPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL);
    cache.map(file("a"), Long.BYTES - 1); // this must throw
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@Test(timeout = SHORT_TIMEOUT_MILLIS, expected = IllegalArgumentException.class)
public void mappingFileWithPageSizeSmallerThanLongSizeBytesMustThrowEvenWithAnyPageSizeOpenOptionAndNoExistingMapping()
        throws IOException {
    // Because otherwise we cannot ensure that our branch-free bounds checking always lands within a page boundary.
    PageCache cache = getPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL);
    cache.map(file("a"), Long.BYTES - 1, PageCacheOpenOptions.ANY_PAGE_SIZE); // this must throw
}