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

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

Introduction

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

Prototype

public static byte[] toByteArray(long value) 

Source Link

Document

Returns a big-endian representation of value in an 8-element byte array; equivalent to ByteBuffer.allocate(8).putLong(value).array() .

Usage

From source file:io.warp10.script.functions.TOHHCODE.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object lon = stack.pop();//  w w  w. jav  a2  s.  com
    Object lat = stack.pop();

    if (!(lon instanceof Number) && !(lat instanceof Number)) {
        throw new WarpScriptException(getName() + " expects a latitude and a longitude on the stack.");
    }

    long geoxppoint = GeoXPLib.toGeoXPPoint(((Number) lat).doubleValue(), ((Number) lon).doubleValue());
    String hhcode = Hex.encodeHexString(Longs.toByteArray(geoxppoint));

    stack.push(hhcode);

    return stack;
}

From source file:integrationtests.ITUtils.java

/**
 * Encodes the provided value as a {@link ByteBuffer}
 *
 * @param value The value to encode/*from   w w  w .j av a 2s  .c  o  m*/
 * @return The buffer representing the provided value
 */
public static ByteBuffer encodeValue(final long value) {
    return ByteBuffer.wrap(Longs.toByteArray(value));
}

From source file:com.outerspacecat.util.Cookies.java

/**
 * Generates a session cookie value. Uses the algorithm described in <a
 * href="http://www.cse.msu.edu/~alexliu/publications/Cookie/cookie.pdf">A
 * Secure Cookie Protocol</a>.//from  w w w.j  ava 2s  .  c o m
 * <p>
 * The paper recommends using an SSL session key for the {@code sessionKey}
 * parameter, another possibility is to use a client IP address. Since both of
 * these approaches have flaws (SSL renegotiation and NAT respectively), an
 * empty array may be used if the risk of replay attacks is acceptable. Replay
 * attack risk may also be mitigated by expiring the cookie after a certain
 * amount of time.
 * 
 * @param id a user identifier. Must be non {@code null}.
 * @param data optional data to be stored in the cookie. The data will be
 *        encrypted using {@code key}. Must be non {@code null}, may be empty.
 * @param sessionKey optional information to prevent replay attacks. Must be
 *        non {@code null}, may be empty.
 * @param key a secret server key. Must be non {@code null}, may be any
 *        length.
 * @return a session cookie value. Never {@code null}.
 */
public static String generateSessionCookie(final byte[] id, final byte[] data, final byte[] sessionKey,
        final byte[] key) {
    Preconditions.checkNotNull(id, "id required");
    Preconditions.checkNotNull(data, "data required");
    Preconditions.checkNotNull(sessionKey, "sessionKey required");
    Preconditions.checkNotNull(key, "key required");

    byte[] created = Longs.toByteArray(System.currentTimeMillis());

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

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

    Tuple2<byte[], byte[]> aesPair = Utils.encryptAes128Cbc(data, Utils.md5(k));

    StringBuilder sb = new StringBuilder(
            6 + id.length * 2 + created.length * 2 + 32 + aesPair.getB().length * 2 + hmac.length * 2);

    sb.append("1$").append(Utils.toHex(id)).append('$').append(Utils.toHex(created)).append('$')
            .append(Utils.toHex(aesPair.getA())).append('$').append(Utils.toHex(aesPair.getB())).append('$')
            .append(Utils.toHex(hmac));

    return sb.toString();
}

From source file:org.apache.tephra.visibility.ReadFence.java

@Override
public Collection<byte[]> getTxChanges() {
    if (tx == null) {
        throw new IllegalStateException("Transaction has not started yet");
    }//from   w  ww. j  a v a2s  .co  m
    return Collections.singleton(Bytes.concat(fenceId, Longs.toByteArray(tx.getTransactionId())));
}

From source file:org.sfs.encryption.SecureSecret.java

protected byte[] toBytes(long v) {
    return Longs.toByteArray(v);
}

From source file:com.nearinfinity.honeycomb.hbase.bulkload.FieldParser.java

/**
 * Try to parse a string into a byte string based on a column type.
 *
 * @param val    String value//from   ww w.ja va2  s.  c  om
 * @param schema Column schema to base value parsing on.
 * @return Byte string
 * @throws ParseException The string value could not be parsed into the column type.
 */
public static ByteBuffer parse(String val, ColumnSchema schema) throws ParseException {
    checkNotNull(val, "Should not be parsing null. Something went terribly wrong.");
    checkNotNull(schema, "Column metadata is null.");

    ColumnType type = schema.getType();

    if (val.length() == 0 && type != ColumnType.STRING && type != ColumnType.BINARY) {
        if (schema.getIsNullable()) {
            return null;
        }

        throw new IllegalArgumentException(
                "Expected a value for a" + " non-null SQL column, but no value was given.");
    }

    switch (type) {
    case LONG:
        return ByteBuffer.wrap(Longs.toByteArray(Long.parseLong(val)));
    case ULONG:
        BigInteger n = new BigInteger(val);
        if (n.compareTo(BigInteger.ZERO) == -1) {
            throw new IllegalArgumentException("negative value provided for unsigned column. value: " + val);
        }
        return ByteBuffer.wrap(Longs.toByteArray(n.longValue()));
    case DOUBLE:
        return ByteBuffer.wrap(Bytes.toBytes(Double.parseDouble(val)));
    case DATE:
        return extractDate(val, "yyyy-MM-dd", "yyyy-MM-dd", "yyyy/MM/dd", "yyyy.MM.dd", "yyyyMMdd");
    case TIME:
        return extractDate(val, "HH:mm:ss", "HH:mm:ss", "HHmmss");
    case DATETIME:
        return extractDate(val, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss",
                "yyyy.MM.dd HH:mm:ss", "yyyyMMdd HHmmss");
    case DECIMAL:
        return extractDecimal(val, schema.getPrecision(), schema.getScale());
    case STRING:
    case BINARY:
    default:
        return ByteBuffer.wrap(val.getBytes(Charset.forName("UTF-8")));
    }
}

From source file:com.yandex.yoctodb.util.mutable.impl.VariableLengthByteArraySortedSet.java

@Override
public void writeTo(@NotNull final OutputStream os) throws IOException {
    // Element count
    os.write(Ints.toByteArray(elements.size()));

    // Element offsets
    long elementOffset = 0;
    for (OutputStreamWritable e : elements) {
        os.write(Longs.toByteArray(elementOffset));
        elementOffset += e.getSizeInBytes();
    }/*from w ww .  j a va2 s.  c  o  m*/
    os.write(Longs.toByteArray(elementOffset));

    // Elements
    for (OutputStreamWritable e : elements)
        e.writeTo(os);
}

From source file:org.echocat.marquardt.example.domain.UserInfo.java

@Override
public void writeTo(@Nonnull @WillNotClose final OutputStream out) throws IOException {
    out.write(VERSION);// ww w  . j av a2s .  c  o m
    out.write(Longs.toByteArray(_userId.getMostSignificantBits()));
    out.write(Longs.toByteArray(_userId.getLeastSignificantBits()));
}

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

public static byte[] addMAC(long[] key, byte[] data) {
    long hash = SipHashInline.hash24_palindromic(key[0], key[1], data);

    byte[] authenticated = Arrays.copyOf(data, data.length + 8);
    System.arraycopy(Longs.toByteArray(hash), 0, authenticated, data.length, 8);

    return authenticated;
}

From source file:cn.codepub.redis.directory.io.JedisClusterStream.java

@Override
public void rename(String fileLengthKey, String fileDataKey, String oldField, String newField,
        List<byte[]> values, long fileLength) {
    //add new file length
    jedisCluster.hset(fileLengthKey.getBytes(), newField.getBytes(), Longs.toByteArray(fileLength));
    //add new file content
    Long blockSize = getBlockSize(fileLength);
    for (int i = 0; i < blockSize; i++) {
        jedisCluster.hset(fileDataKey.getBytes(), getBlockName(newField, i), compressFilter(values.get(i)));
    }/*from  ww  w  . j  a v  a2 s . c  o  m*/
    values.clear();
    deleteFile(fileLengthKey, fileDataKey, oldField, blockSize);
}