Example usage for com.google.common.primitives Longs fromByteArray

List of usage examples for com.google.common.primitives Longs fromByteArray

Introduction

In this page you can find the example usage for com.google.common.primitives Longs fromByteArray.

Prototype

public static long fromByteArray(byte[] bytes) 

Source Link

Document

Returns the long value whose big-endian representation is stored in the first 8 bytes of bytes ; equivalent to ByteBuffer.wrap(bytes).getLong() .

Usage

From source file:io.warp10.crypto.CryptoUtils.java

/**
 * Check the MAC and return the verified content or null if the verification failed
 * /*  w ww  .j a  v a 2 s.  co m*/
 * @param key
 * @param data
 * @return
 */
public static byte[] removeMAC(byte[] key, byte[] data) {
    long hash = SipHashInline.hash24_palindromic(key, data, 0, data.length - 8);
    long mac = Longs.fromByteArray(Arrays.copyOfRange(data, data.length - 8, data.length));

    if (mac == hash) {
        return Arrays.copyOf(data, data.length - 8);
    } else {
        return null;
    }
}

From source file:org.voltdb.VoltSystemProcedure.java

/**
 * Since sysprocs still use long fragids in places (rather than sha1 hashes),
 * provide a utility method to convert between longs and hashes. This method
 * is the inverse of {@link VoltSystemProcedure#fragIdToHash(long)}.
 *
 * @param hash 20bytes of hash value (last 12 bytes ignored)
 * @return 8 bytes of fragid//ww  w.  j  ava  2  s  .  c o m
 */
public static long hashToFragId(byte[] hash) {
    return Longs.fromByteArray(hash);
}

From source file:org.gaul.s3proxy.NullBlobStore.java

@Override
public Blob getBlob(String container, String name, GetOptions options) {
    Blob blob = super.getBlob(container, name, options);
    if (blob == null) {
        return null;
    }//w w w.j  av a  2s .  c  om

    byte[] array;
    try (InputStream is = blob.getPayload().openStream()) {
        array = ByteStreams.toByteArray(is);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    long length = Longs.fromByteArray(array);
    ByteSourcePayload payload = new ByteSourcePayload(new NullByteSource().slice(0, length));
    payload.setContentMetadata(blob.getPayload().getContentMetadata());
    payload.getContentMetadata().setContentLength(length);
    payload.getContentMetadata().setContentMD5((HashCode) null);
    blob.setPayload(payload);
    return blob;
}

From source file:io.warp10.crypto.CryptoUtils.java

public static byte[] removeMAC(long[] key, byte[] data) {
    long hash = SipHashInline.hash24_palindromic(key[0], key[1], data, 0, data.length - 8);
    long mac = Longs.fromByteArray(Arrays.copyOfRange(data, data.length - 8, data.length));

    if (mac == hash) {
        return Arrays.copyOf(data, data.length - 8);
    } else {/*www  . jav  a2 s . com*/
        return null;
    }
}

From source file:se.sics.caracaldb.utils.TimestampIdFactory.java

private UUID nextId() {
    byte[] lower = new byte[8];
    byte[] upper = new byte[8];
    lastId = ts.add(counter);//ww  w . j a v a2s  .c  o  m
    counter.inc();
    byte[] idB = lastId.array();
    if (idB.length < 10) {
        LOG.error("Timestamp underflow! Should be 10 bytes but is only {}", idB.length);
        throw new RuntimeException("Fuck BigIntegers -.-");
    }
    if (idB.length > 10) {
        LOG.error("Timestamp overflow! It must be the end of days -.-");
        throw new RuntimeException("Out of timestamps! Try again in another universe...");
    }
    System.arraycopy(idB, 0, upper, 0, 8);
    System.arraycopy(idB, 8, lower, 0, 2);
    System.arraycopy(address, 0, lower, 2, 6);
    long up = Longs.fromByteArray(upper);
    long low = Longs.fromByteArray(lower);
    return new UUID(up, low);
}

From source file:cn.codepub.redis.directory.RedisDirectory.java

/**
 * @param name file name/* ww  w.j  av a 2 s  .  c om*/
 * @return Returns the length of a file in the directory.
 * @throws IOException an I/O error
 */
@Override
public final long fileLength(String name) throws IOException {
    ensureOpen();
    long current = 0;
    byte[] b = inputOutputStream.hget(Constants.DIR_METADATA_BYTES, name.getBytes(), FILE_LENGTH);
    if (b != null) {
        current = Longs.fromByteArray(b);
    }
    return current;
}

From source file:org.apache.hadoop.hdfs.util.BestEffortLongFile.java

private void lazyOpen() throws IOException {
    if (ch != null) {
        return;//from  w w  w .  j a v  a  2  s . co  m
    }

    // Load current value.
    byte[] data = null;
    try {
        data = Files.toByteArray(file);
    } catch (FileNotFoundException fnfe) {
        // Expected - this will use default value.
    }

    if (data != null && data.length != 0) {
        if (data.length != Longs.BYTES) {
            throw new IOException("File " + file + " had invalid length: " + data.length);
        }
        value = Longs.fromByteArray(data);
    } else {
        value = defaultVal;
    }

    // Now open file for future writes.
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    try {
        ch = raf.getChannel();
    } finally {
        if (ch == null) {
            IOUtils.closeStream(raf);
        }
    }
}

From source file:Model.Leader.java

/**
 * Listens for messages from group requesting an election.  The packets being
 * received will contain the amount of free memory in the sender.  The local 
 * client will compare against its own memory at startup and determine if it
 * should rebroadcast using <code> startElection</code>
 * claiming it has more free memory or accept the new leader
 * because they have more available resources.  
 * //w  w  w. j a  v a  2  s. c om
 * This may result in a flood of broadcasts temporarily as the leader is 
 * sorted in theory.  E.g. if this is the lowest id peer, then all other 
 * peers might respond and end up with a Big O(n2) transmissions.  
 * 
 * Each peer with greater id will respond, until only one peer responds and 
 * other peers set it as the leader.
 */
public void receiveMessage() {
    byte[] buffer;
    long id;
    while (run) {
        try {
            buffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            while (serverSocket != null) {
                serverSocket.receive(packet);
                buffer = packet.getData();
                id = Longs.fromByteArray(buffer);
                if (id < ownID) {
                    startElection();
                } else {
                    localPeerNode.setLeader(packet.getAddress());
                    long timestamp = Longs.fromBytes(buffer[9], buffer[10], buffer[11], buffer[12], buffer[13],
                            buffer[14], buffer[15], buffer[16]);
                    System.out.println("received update for leader " + timestamp);
                    localPeerNode.updateVectorForPeer(packet.getAddress().getHostAddress(), timestamp);
                }
            }
            buffer = null;
        } catch (IOException ex) {
            Logger.getLogger(PeerNode.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        serverSocket.leaveGroup(group);
    } catch (IOException ex) {
        Logger.getLogger(Leader.class.getName()).log(Level.SEVERE, null, ex);
    }
    serverSocket.close();
}

From source file:cn.codepub.redis.directory.RedisDirectory.java

@Override
public void deleteFile(String name) throws IOException {
    ensureOpen();/*w  w w  .  j a  va2  s.c o m*/
    boolean b = fileNameExists(name);
    if (b) {
        byte[] hget = inputOutputStream.hget(Constants.DIR_METADATA_BYTES, name.getBytes(), FILE_LENGTH);
        long length = Longs.fromByteArray(hget);
        long blockSize = getBlockSize(length);
        inputOutputStream.deleteFile(Constants.DIRECTORY_METADATA, Constants.FILE_METADATA, name, blockSize);
    } else {
        log.error("Delete file {} does not exists!", name);
    }
}

From source file:org.onosproject.ipfix.packet.MessageHeader.java

public static MessageHeader parse(byte[] data) throws HeaderException {
    try {//from ww w.j  av a  2s  .c  o  m
        if (data.length < HEADER_LENGTH) {
            throw new HeaderException("Data array too short.");
        }
        MessageHeader mh = new MessageHeader();
        // version number
        byte[] versionNumber = new byte[2];
        System.arraycopy(data, 0, versionNumber, 0, 2);
        mh.setVersionNumber(Ints.fromByteArray(versionNumber));
        // length
        byte[] length = new byte[2];
        System.arraycopy(data, 2, length, 0, 2);
        mh.setLength(Ints.fromByteArray(length));
        // export time
        byte[] exportTime = new byte[4];
        System.arraycopy(data, 4, exportTime, 0, 4);
        long secondsSinceEpoche = Longs.fromByteArray(exportTime);
        long milliSecondsSinceEpoche = secondsSinceEpoche * 1000;
        mh.setExportTime(new Date(milliSecondsSinceEpoche));
        // sequence number
        byte[] sequenceNumber = new byte[4];
        System.arraycopy(data, 8, sequenceNumber, 0, 4);
        mh.setSequenceNumber(Longs.fromByteArray(sequenceNumber));
        // observation domain id
        byte[] observationDomainID = new byte[4];
        System.arraycopy(data, 12, observationDomainID, 0, 4);
        mh.setObservationDomainID(Longs.fromByteArray(observationDomainID));
        // set header
        int offset = HEADER_LENGTH;

        while ((mh.getLength() - offset) > 0) {
            byte[] subData = new byte[mh.getLength() - offset];
            System.arraycopy(data, offset, subData, 0, subData.length);
            SetHeader sh = SetHeader.parse(subData);
            mh.getSetHeaders().add(sh);
            offset += sh.getLength();
        }
        if ((mh.getLength() - offset) != 0) {
            LOGGER.log(Level.INFO, "Unused bytes: " + (mh.getLength() - offset));
        }
        return mh;
    } catch (Exception e) {
        throw new HeaderException("Parse error: " + e.getMessage());
    }
}