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:com.outerspacecat.util.Cookies.java

/**
 * Parses a session cookie previously generated by
 * {@link #generateSessionCookie(byte[], byte[], byte[], byte[])}.
 * //from  ww w  .  j  a va  2s  . c o m
 * @param key the key that was used to create the cookie. Must be non
 *        {@code null}.
 * @param sessionKey the session key that was used to create the cookie. Must
 *        be non {@code null}.
 * @param cookie the cookie value to parse. Must be non {@code null}.
 * @return a tuple containing the id and data used to create the cookie, along
 *         with a timestamp of when the cookie was created. Never {@code null}
 *         , all tuple values are non {@code null}.
 * @throws IOException if {@code cookie} is not a valid cookie or if it was
 *         not created using {@code key} and {@code sessionKey}.
 */
public static Tuple3<byte[], byte[], Instant> parseSessionCookie(final byte[] key, final byte[] sessionKey,
        final CharSequence cookie) throws IOException {
    Preconditions.checkNotNull(key, "key required");
    Preconditions.checkNotNull(sessionKey, "sessionKey required");
    Preconditions.checkNotNull(cookie, "cookie required");

    String[] parts = cookie.toString().split("\\$");
    if (parts[0].equals("1")) {
        if (parts.length != 6)
            throw new IllegalArgumentException("invalid cookie: " + cookie);

        if (parts[1].length() % 2 != 0 || !HEX_PATTERN.matcher(parts[1]).matches() || parts[2].length() != 16
                || !HEX_PATTERN.matcher(parts[2]).matches() || parts[3].length() != 32
                || !HEX_PATTERN.matcher(parts[3]).matches() || parts[4].length() % 2 != 0
                || !HEX_PATTERN.matcher(parts[4]).matches() || parts[5].length() % 2 != 0
                || !HEX_PATTERN.matcher(parts[5]).matches())
            throw new IOException("invalid cookie: " + cookie);

        byte[] id = Utils.fromHex(parts[1].toCharArray());

        byte[] created = Utils.fromHex(parts[2].toCharArray());

        byte[] k = Utils.hmacSha1(Bytes.concat(id, created), key);

        byte[] iv = Utils.fromHex(parts[3].toCharArray());

        byte[] data = Utils.decryptAes128Cbc(Utils.fromHex(parts[4].toCharArray()), Utils.md5(k), iv);

        byte[] hmac = Utils.hmacSha1(Bytes.concat(id, created, data, sessionKey), k);

        if (!Utils.constantEquals(parts[5], new String(Utils.toHex(hmac))))
            throw new IOException("cookie tampering detected: " + cookie);

        return Tuple3.of(id, data, Instant.ofEpochMilli(Longs.fromByteArray(created)));
    } else {
        throw new IOException("invalid cookie: " + cookie);
    }
}

From source file:pl.coffeepower.blog.messagebus.MessageBusTestHelper.java

Future<Boolean> createSubscriberFuture(final String cloudNode, final Engine engine) {
    return cloud.node(cloudNode).submit((Callable<Boolean> & Serializable) () -> {
        Fixtures fixtures = new Fixtures();
        AtomicBoolean state = new AtomicBoolean(true);
        AtomicLong lastReceived = new AtomicLong();
        AtomicLong messagesCounter = new AtomicLong();
        Subscriber subscriber = Guice.createInjector(Stage.PRODUCTION, new TestConfigurationModule(),
                new BytesEventModule(), engine.getModule()).getInstance(Subscriber.class);
        subscriber.register((data, length) -> {
            messagesCounter.incrementAndGet();
            if (state.get()) {
                long prevReceivedValue = lastReceived.getAndSet(Longs.fromByteArray(data));
                long lastReceivedValue = lastReceived.get();
                if (lastReceivedValue != (prevReceivedValue + 1)
                        || data[length - 1] != fixtures.getLastAdditionalDataByte()) {
                    state.set(false);/*from w w w. j a va  2 s  . c o  m*/
                }
            }
        });
        IdleStrategy idleStrategy = new SleepingIdleStrategy(TimeUnit.MICROSECONDS.toNanos(1L));
        while (state.get() && lastReceived.get() < fixtures.getNumberOfMessages()) {
            idleStrategy.idle();
        }
        subscriber.close();
        if (!state.get()) {
            System.out.println("Broken connection on messageId=" + lastReceived.get());
            System.out.println("Last messageId=" + lastReceived);
        }
        return state.get();
    });
}

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

private RedisFile loadRedisToFile(String fileName) {
    byte[] hget = inputOutputStream.hget(Constants.DIR_METADATA_BYTES, fileName.getBytes(), FILE_LENGTH);
    long lenght = Longs.fromByteArray(hget);
    RedisFile redisFile = new RedisFile(fileName, lenght);
    long blockSize = getBlockSize(lenght);
    List<byte[]> bytes = inputOutputStream.loadFileOnce(Constants.FILE_METADATA, fileName, blockSize);
    redisFile.setBuffers(bytes);//from  www .ja  va2  s.  c  om
    return redisFile;
}

From source file:org.apache.storm.verify.VerifyUtils.java

public static String toString(byte[] bytes, Class type) {
    if (String.class.equals(type)) {
        return new String(bytes);
    } else if (Long.class.equals(type)) {
        return String.valueOf(Longs.fromByteArray(bytes));
    } else if (Integer.class.equals(type)) {
        return String.valueOf(Ints.fromByteArray(bytes));
    } else {/*from w ww.j  a  v  a  2 s  .com*/
        throw new IllegalArgumentException("currently we only support String, Long and Integer types");
    }
}

From source file:org.opendedup.mtools.FDisk.java

private void checkDedupFile(File mapFile) throws IOException {
    if (closed) {
        this.failed = true;
        return;//  w w w. j  a  v  a2 s.  c  o m
    }
    LongByteArrayMap mp = null;
    try {
        if (mapFile.getName().endsWith(".lz4"))
            mp = LongByteArrayMap.getMap(mapFile.getName().substring(0, mapFile.getName().length() - 8));
        else
            mp = LongByteArrayMap.getMap(mapFile.getName().substring(0, mapFile.getName().length() - 4));

        if (closed) {
            this.failed = true;
            return;
        }
        mp.iterInit();
        SparseDataChunk ck = mp.nextValue(false);
        while (ck != null) {
            if (closed) {
                this.failed = true;
                return;
            }
            List<HashLocPair> al = ck.getFingers();
            for (HashLocPair p : al) {
                boolean added = DedupFileStore.addRef(p.hash, Longs.fromByteArray(p.hashloc));
                if (!added)
                    SDFSLogger.getLog().warn("ref not added for " + mapFile + " at " + ck.getFpos());

            }
            ck = mp.nextValue(false);
        }

        synchronized (fEvt) {
            fEvt.curCt++;
        }
    } catch (Throwable e) {
        SDFSLogger.getLog().info("error while checking file [" + mapFile.getPath() + "]", e);
        this.failed = true;
    } finally {
        mp.close();
        mp = null;
    }
    this.files.incrementAndGet();
}

From source file:com.liaison.javabasics.serialization.BytesUtil.java

/**
 * TODO//from w  ww .ja v a  2 s.  c o  m
 * @param bytes TODO
 * @return TODO
 */
public static Long toLong(final byte[] bytes) {
    // TODO: determine constant values programmatically, or make them constant
    if (bytes != null && bytes.length >= 8) {
        return Long.valueOf(Longs.fromByteArray(bytes));
    }
    return null;
}

From source file:org.voltdb.sysprocs.saverestore.CSVSnapshotWritePlan.java

static private List<Long> computeDedupedLocalSites(long txnId, SiteTracker tracker) {
    MessageDigest digest;// ww  w. j  a  va2  s  . co m
    try {
        digest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }

    /*
     * List of partitions to include if this snapshot is
     * going to be deduped. Attempts to break up the work
     * by seeding and RNG selecting
     * a random replica to do the work. Will not work in failure
     * cases, but we don't use dedupe when we want durability.
     *
     * Originally used the partition id as the seed, but it turns out
     * that nextInt(2) returns a 1 for seeds 0-4095. Now use SHA-1
     * on the txnid + partition id.
     */
    List<Long> sitesToInclude = new ArrayList<Long>();
    for (long localSite : tracker.getLocalSites()) {
        final int partitionId = tracker.getPartitionForSite(localSite);
        List<Long> sites = new ArrayList<Long>(
                tracker.getSitesForPartition(tracker.getPartitionForSite(localSite)));
        Collections.sort(sites);

        digest.update(Longs.toByteArray(txnId));
        final long seed = Longs.fromByteArray(Arrays.copyOf(digest.digest(Ints.toByteArray(partitionId)), 8));

        int siteIndex = new java.util.Random(seed).nextInt(sites.size());
        if (localSite == sites.get(siteIndex)) {
            sitesToInclude.add(localSite);
        }
    }
    return sitesToInclude;
}

From source file:org.apache.apex.malhar.lib.state.managed.IncrementalCheckpointManager.java

/**
 * Retrieves artifacts available for all the windows saved by the enclosing partitions.
 * @return  artifact saved per window.//from  www. j  ava 2  s  .  com
 * @throws IOException
 */
public Map<Long, Object> retrieveAllWindows() throws IOException {
    Map<Long, Object> artifactPerWindow = new HashMap<>();
    FileSystemWAL.FileSystemWALReader reader = getWal().getReader();
    reader.seek(getWal().getWalStartPointer());

    Slice windowSlice = readNext(reader);
    while (reader.getCurrentPointer().compareTo(getWal().getWalEndPointerAfterRecovery()) < 0
            && windowSlice != null) {
        long window = Longs.fromByteArray(windowSlice.toByteArray());
        Object data = fromSlice(readNext(reader));
        artifactPerWindow.put(window, data);
        windowSlice = readNext(reader); //null or next window
    }
    reader.seek(getWal().getWalStartPointer());
    return artifactPerWindow;
}

From source file:org.roqmessaging.core.SubscriberConnectionManager.java

public void run() {
    knownHosts = new ArrayList<String>();
    //      Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();
    int counter = 0;
    while (init() != 0) {
        try {//w ww.java2  s.c o  m
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            logger.error("Error when thread sleeping (init phase)", e);
        }
        logger.info("Retrying connection...");
    }

    this.items = new ZMQ.Poller(2);
    this.items.register(monitorSub);
    this.items.register(exchSub);

    Timer timer = new Timer();
    timer.schedule(new Stats(), 0, 60000);

    logger.info("Worker connected");

    while (running) {
        items.poll(10);
        if (items.pollin(0)) { // Info from Monitor

            String info[] = new String(monitorSub.recv(0)).split(",");
            int infoCode = Integer.parseInt(info[0]);

            if (infoCode == RoQConstant.REQUEST_UPDATE_EXCHANGE_LIST && !info[1].equals("")) {
                // new Exchange  available message
                connectToBroker(info[1]);

            }
        }

        if (items.pollin(1)) {//From Exchange
            byte[] request = null;
            //Get the key
            exchSub.recv(0);
            if (exchSub.hasReceiveMore()) {
                //the ID of the publisher
                request = exchSub.recv(0);
            }
            if (exchSub.hasReceiveMore()) {
                //the payload
                request = exchSub.recv(0);
            }
            if (exchSub.hasReceiveMore()) {
                //the time stamp
                byte[] bTimeStamp = exchSub.recv(0);
                counter++;
                if (counter == 1000) {
                    computeLatency(Longs.fromByteArray(bTimeStamp));
                    counter = 0;
                }
            }
            //logger.debug("Recieving message " +  new String(request,0,request.length) + " key : "+ new String(request,0,request.length));
            //delivering to the message listener
            this.subscriber.onEvent(request != null ? request : new byte[] {});
            received++;
        }
    }
    this.logger.debug("Closing subscriber sockets");
    timer.cancel();
    timer.purge();
    knownHosts.clear();
    this.exchSub.setLinger(0);
    this.exchSub.close();
    this.initReq.setLinger(0);
    this.initReq.close();
    logger.info("Closed.");
}

From source file:com.indeed.lsmtree.recordcache.MemcachedCache.java

public boolean checkAvailability(String key) {
    long time = System.nanoTime();
    key += "-" + UUID.randomUUID().toString();
    OperationFuture<Boolean> future = memcache.set(key, CACHE_EXPIRY_SECONDS, Longs.toByteArray(time),
            identityTranscoder);//from  w w  w  .  j  av  a 2  s.  c  o m
    try {
        if (!future.get())
            return false;
    } catch (Exception e) {
        return false;
    }
    byte[] bytes = memcache.get(key, identityTranscoder);
    memcache.delete(key);
    return bytes != null && Longs.fromByteArray(bytes) == time;
}