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:dti.tdl.messaging.TDLMessageHandler.java

public static void deFraming(byte[] bytes) {
    int size = bytes.length;
    int startIdx = -1;
    int endIdx = -1;
    int startMsgIdx = -1;
    int endMsgIdx = -1;
    //        try {
    String rxMsgT = new String(bytes);

    String rcvStr = "Rx Frame: ";
    for (int j = 0; j < bytes.length; j++) {
        rcvStr = rcvStr + " " + (int) bytes[j];

    }/*from   ww  w.  j ava2  s. c  o m*/
    System.out.println(rcvStr);
    //            System.out.println(rxMsgT);
    //            System.out.println(size);
    //        } catch (UnsupportedEncodingException ex) {
    //            Logger.getLogger(TDLMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    //        for (int k = 0; k < bytes.length; k++) {
    //            System.out.println("Rx frame Byte " + k + ": " + (int) bytes[k]);
    //        }
    for (int i = 0; i < size; i++) {
        if (bytes[i] == (byte) 1) {
            if (startIdx == -1)
                startIdx = i;

        }

        if (bytes[i] == (byte) 2) {
            if (startMsgIdx == -1)
                startMsgIdx = i;

        }
        if (bytes[i] == (byte) 3) {
            if (endMsgIdx == -1 && i > startIdx && i > startMsgIdx)
                endMsgIdx = i;

        }
        if (bytes[i] == (byte) 4) {
            if (endIdx == -1 && i > startIdx && i > startMsgIdx && i > endMsgIdx && bytes[i - 1] == (byte) 3)
                endIdx = i;

        }
    }

    if (startIdx == -1 || endIdx == -1 || endMsgIdx < startMsgIdx || endIdx < startMsgIdx || endIdx < endMsgIdx
            || startMsgIdx < startIdx) {
        String err = "Corrupted Message: invalid frame";
        TDLMessage rxMsg = new TDLMessage(null, null, null, null, (byte) 48, err.getBytes());
        //            rxStack.add(rxMsg);
        rxStack.offer(rxMsg);
        return;
    }
    byte[] msgType = { bytes[startIdx + 1] };
    byte[] fromId = { bytes[startIdx + 2], bytes[startIdx + 3] };
    byte[] toId = { bytes[startIdx + 4], bytes[startIdx + 5] };
    byte[] profileId = { bytes[startIdx + 6], bytes[startIdx + 7], bytes[startIdx + 8], bytes[startIdx + 9] };
    //int checksumSize = startMsgIdx - startIdx+9;
    byte[] checksum = Arrays.copyOfRange(bytes, startIdx + 10, startIdx + 18);
    byte[] msg = Arrays.copyOfRange(bytes, startMsgIdx + 1, endMsgIdx);
    //try {
    //      String rxMsg = new String(msg);
    //      System.out.println(rxMsg);

    long newChecksum = CRC32Checksum(msg);
    //        System.out.println(startIdx);
    //        System.out.println(startMsgIdx);
    //        System.out.println(endIdx);
    //        System.out.println(checksum.length);
    //long receiveChecksum = ByteUtil.bytesToLong(checksum);
    long receiveChecksum = Longs.fromByteArray(checksum);
    //System.out.println(checksum.toString());
    //System.out.println(newChecksum);
    //System.out.println(receiveChecksum);
    String profileStr = new String(profileId);
    String fromStr = "";
    for (int i = 0; i < fromId.length; i++) {
        int fromBI = (int) fromId[i];
        fromStr = fromStr + String.format("%02x", Byte.parseByte(Integer.toString(fromBI)));
    }
    if (newChecksum != receiveChecksum) {
        String err = "Corrupted Message: checksum not matched";
        TDLMessage rxMsgObj = new TDLMessage(profileStr, fromStr, toId.toString(), null, (byte) 48,
                err.getBytes());
        //            rxStack.add(rxMsg);
        rxStack.offer(rxMsgObj);
        return;
    }

    TDLMessage rxMsgObj = new TDLMessage(profileStr, fromStr, toId.toString(), null, msgType[0], msg);
    //            rxStack.add(rxMsg);
    rxStack.offer(rxMsgObj);
    //        } catch (UnsupportedEncodingException ex) {
    //        }

}

From source file:cryptwallet.CryptPasswordController.java

public static Duration getTargetTime() throws IllegalArgumentException {
    return Duration.ofMillis(Longs.fromByteArray(Main.bitcoin.wallet().getTag(TAG).toByteArray()));
}

From source file:org.echocat.marquardt.common.util.InputStreamUtils.java

private long internalReadLong(@Nonnull @WillNotClose final InputStream inputStream) throws IOException {
    final byte[] bytes = readBytes(inputStream, Longs.BYTES);
    return Longs.fromByteArray(bytes);
}

From source file:Model.PeerComms.java

public void leavingP2PNetwork() {
    byte[] buffer = new byte[256];
    long msg = 999999;
    buffer = Longs.toByteArray(msg);/*from ww w .jav a 2s  .  co m*/
    DatagramPacket dPacket = new DatagramPacket(buffer, buffer.length, group, DEST_PORT);
    try {
        dSocket.send(dPacket);
        localPeerNode.setVectorTimeStamp();
        System.out.println("send leaving notification to p2p network");
        System.out.println("packet sent = " + Longs.fromByteArray(dPacket.getData()));
    } catch (IOException ex) {
        Logger.getLogger(PeerComms.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.nec.strudel.tkvs.store.hbase.HBaseTransaction.java

@Override
public boolean commit() {
    prof.commitStart(gName);/*from   www  .j  a va 2  s  . c o  m*/
    //Will only change only Row rowid because
    //one entity group is packed in one row
    Put put = new Put(rowid);
    Delete del = new Delete(rowid);
    for (CollectionBuffer b : buffers()) {
        Map<Key, Record> writes = b.getWrites();
        //collection name is different from group name
        String name = b.getName();
        for (Map.Entry<Key, Record> e : writes.entrySet()) {
            Record r = e.getValue();
            //for put
            if (r != null) {
                put.add(HBaseStore.ENTITYCF, e.getKey().toByteKey(name), r.toBytes());
            } else { // for delete
                del.deleteColumn(HBaseStore.ENTITYCF, e.getKey().toByteKey(name));
            }
        }
    }
    //do batch commit
    byte[] oldVnumBytes = vnum == 0 ? null : Bytes.toBytes(this.vnum);
    if (put.isEmpty() && del.isEmpty()) {
        //read only transaction, fail commit if version is changed
        Get get = new Get(rowid);
        get.addColumn(HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER);
        Result res = null;
        try {
            res = htable.get(get);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        closeTable();
        if (!res.isEmpty()) {
            long newvnum = Longs.fromByteArray(res.value());
            if (newvnum == this.vnum) {
                prof.commitSuccess(gName);
                return true;
            } else {
                prof.commitFail(gName);
                return false;
            }
        } else {
            if (this.vnum == 0L) {
                prof.commitSuccess(gName);
                return true;
            } else {
                prof.commitFail(gName);
                return false;
            }
        }
    } else {
        if (!put.isEmpty() && !del.isEmpty()) {
            try {
                put.add(HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER, Bytes.toBytes(vnum + 1));
                if (!htable.checkAndPut(this.rowid, HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER, oldVnumBytes,
                        put)) {
                    prof.commitFail(gName);
                    closeTable();
                    return false;
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                if (!htable.checkAndDelete(this.rowid, HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER,
                        Bytes.toBytes(vnum + 1), del)) {
                    prof.commitFail(gName);
                    closeTable();
                    return false;
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } else if (del.isEmpty()) {
            try {
                put.add(HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER, Bytes.toBytes(vnum + 1));
                if (!htable.checkAndPut(this.rowid, HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER, oldVnumBytes,
                        put)) {
                    prof.commitFail(gName);
                    closeTable();
                    return false;
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } else {
            //put is empty and del is not empty
            try {
                if (!htable.checkAndDelete(this.rowid, HBaseStore.VERSIONCF, HBaseStore.VERQUALIFIER,
                        oldVnumBytes, del)) {
                    prof.commitFail(gName);
                    closeTable();
                    return false;
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
    prof.commitSuccess(gName);
    closeTable();
    return true;
}

From source file:com.continuuity.loom.common.zookeeper.IdService.java

private long generateId(Type type) {
    idLock.get().acquire();//from ww  w.  j av  a 2 s  . c o  m
    try {
        NodeData nodeData = Futures.getUnchecked(zkClient.getData(type.path));
        long counterVal = Longs.fromByteArray(nodeData.getData());
        Futures.getUnchecked(zkClient.setData(type.path, Longs.toByteArray(counterVal + incrementBy)));
        return counterVal;
    } finally {
        idLock.get().release();
    }
}

From source file:org.dcache.pool.repository.ceph.CephFileStore.java

@Override
public BasicFileAttributeView getFileAttributeView(PnfsId id) throws IOException {
    String imageName = toImageName(id);
    try (RbdImage image = rbd.openReadOnly(imageName)) {

        final RbdImageInfo imageInfo = image.stat();

        return new BasicFileAttributeView() {
            @Override//from w w w .  j av  a  2  s.co m
            public String name() {
                return "basic";
            }

            @Override
            public BasicFileAttributes readAttributes() throws IOException {
                return new BasicFileAttributes() {

                    private FileTime getTimeFromXattr(String image, String attr) {
                        long time;
                        try {
                            byte[] b = new byte[Long.BYTES];
                            ctx.getXattr(toObjName(image), attr, b);
                            time = Longs.fromByteArray(b);
                        } catch (RadosException e) {
                            time = 0;
                        }
                        return FileTime.fromMillis(time);
                    }

                    @Override
                    public FileTime lastModifiedTime() {
                        return getTimeFromXattr(imageName, LAST_MODIFICATION_TIME_ATTR);
                    }

                    @Override
                    public FileTime lastAccessTime() {
                        return getTimeFromXattr(imageName, LAST_ACCESS_TIME_ATTR);
                    }

                    @Override
                    public FileTime creationTime() {
                        return getTimeFromXattr(imageName, CREATION_TIME_ATTR);
                    }

                    @Override
                    public boolean isRegularFile() {
                        return true;
                    }

                    @Override
                    public boolean isDirectory() {
                        return false;
                    }

                    @Override
                    public boolean isSymbolicLink() {
                        return false;
                    }

                    @Override
                    public boolean isOther() {
                        return false;
                    }

                    @Override
                    public long size() {
                        return imageInfo.obj_size.longValue();
                    }

                    @Override
                    public Object fileKey() {
                        return null;
                    }
                };
            }

            private void setTimeToXattr(String image, String attr, FileTime time) throws RadosException {
                ctx.setXattr(toObjName(image), attr, Longs.toByteArray(time.toMillis()));
            }

            @Override
            public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime)
                    throws IOException {

                if (lastModifiedTime != null) {
                    setTimeToXattr(imageName, LAST_MODIFICATION_TIME_ATTR, lastModifiedTime);
                }

                if (lastAccessTime != null) {
                    setTimeToXattr(imageName, LAST_ACCESS_TIME_ATTR, lastAccessTime);
                }

                if (createTime != null) {
                    setTimeToXattr(imageName, CREATION_TIME_ATTR, createTime);
                }

            }
        };
    } catch (RadosException e) {
        throwIfMappable(e, "Failed to get file's attribute: " + imageName);
        throw e;
    }
}

From source file:org.apache.druid.common.utils.SerializerUtils.java

long readLong(InputStream in) throws IOException {
    byte[] longBytes = new byte[Long.BYTES];

    ByteStreams.readFully(in, longBytes);

    return Longs.fromByteArray(longBytes);
}

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

@Override
public void renameFile(String source, String dest) throws IOException {
    List<byte[]> values = new ArrayList<>();
    //get??// w w  w.jav  a2 s  .com
    //
    //Get the file length with old file name
    byte[] hget = inputOutputStream.hget(Constants.DIR_METADATA_BYTES, source.getBytes(), FILE_LENGTH);
    long length = Longs.fromByteArray(hget);
    long blockSize = getBlockSize(length);
    for (int i = 0; i < blockSize; i++) {
        //Get the contents with old file name
        byte[] res = inputOutputStream.hget(Constants.FILE_METADATA_BYTES, getBlockName(source, i), FILE_DATA);
        values.add(res);
    }
    inputOutputStream.rename(Constants.DIRECTORY_METADATA, Constants.FILE_METADATA, source, dest, values,
            length);
    log.debug("Rename file success from {} to {}", source, dest);
}

From source file:com.google.cloud.hadoop.gcsio.FileInfo.java

/**
 * Gets the modification time of this file if one is set, otherwise the value of
 * {@link #getCreationTime()} is returned.
 *
 * Time is expressed as milliseconds since January 1, 1970 UTC.
 *//*from  w  w w .j a  va2 s  . c  o  m*/
public long getModificationTime() {
    if (attributes.containsKey(FILE_MODIFICATION_TIMESTAMP_KEY)
            && attributes.get(FILE_MODIFICATION_TIMESTAMP_KEY) != null) {
        try {
            return Longs.fromByteArray(attributes.get(FILE_MODIFICATION_TIMESTAMP_KEY));
        } catch (IllegalArgumentException iae) {
            LOG.debug("Failed to parse modification time '{}' millis for object {}",
                    attributes.get(FILE_MODIFICATION_TIMESTAMP_KEY), itemInfo.getObjectName());
        }
    }
    return getCreationTime();
}