Example usage for com.google.common.hash Hasher putByte

List of usage examples for com.google.common.hash Hasher putByte

Introduction

In this page you can find the example usage for com.google.common.hash Hasher putByte.

Prototype

@Override
    Hasher putByte(byte b);

Source Link

Usage

From source file:org.sonatype.nexus.common.hash.MultiHashingInputStream.java

@Override
public int read() throws IOException {
    int b = in.read();
    if (b != -1) {
        for (Hasher hasher : hashers.values()) {
            hasher.putByte((byte) b);
        }//w  ww  . j a va  2  s  .  com
        count++;
    }
    return b;
}

From source file:com.facebook.buck.cxx.toolchain.objectfile.LcUuidContentsScrubber.java

@Override
public void scrubFile(FileChannel file) throws IOException, ScrubException {
    if (!Machos.isMacho(file)) {
        return;/*from  www.j  av  a  2  s  .c  om*/
    }

    long size = file.size();
    MappedByteBuffer map = file.map(FileChannel.MapMode.READ_WRITE, 0, size);

    try {
        Machos.setUuidIfPresent(map, ZERO_UUID);
    } catch (Machos.MachoException e) {
        throw new ScrubException(e.getMessage());
    }
    map.rewind();

    Hasher hasher = Hashing.sha1().newHasher();
    while (map.hasRemaining()) {
        hasher.putByte(map.get());
    }

    map.rewind();
    try {
        Machos.setUuidIfPresent(map, Arrays.copyOf(hasher.hash().asBytes(), 16));
    } catch (Machos.MachoException e) {
        throw new ScrubException(e.getMessage());
    }
}

From source file:com.facebook.buck.cxx.LcUuidScrubber.java

@Override
public void scrubFile(FileChannel file) throws IOException, ScrubException {
    if (!Machos.isMacho(file)) {
        return;/* w w w.  j  a  va2 s  .  c  o  m*/
    }

    long size = file.size();
    MappedByteBuffer map = file.map(FileChannel.MapMode.READ_WRITE, 0, size);

    try {
        Machos.setUuid(map, ZERO_UUID);
    } catch (Machos.MachoException e) {
        throw new ScrubException(e.getMessage());
    }
    map.rewind();

    Hasher hasher = Hashing.sha1().newHasher();
    while (map.hasRemaining()) {
        hasher.putByte(map.get());
    }

    map.rewind();
    try {
        Machos.setUuid(map, Arrays.copyOf(hasher.hash().asBytes(), 16));
    } catch (Machos.MachoException e) {
        throw new ScrubException(e.getMessage());
    }
}

From source file:com.facebook.buck.util.hash.AppendingHasher.java

@Override
public Hasher putByte(byte b) {
    for (Hasher hasher : hashers) {
        hasher.putByte(b);
    }//  w  w w.  j  ava  2 s  . co m
    return this;
}

From source file:nextflow.util.CacheHelper.java

public static Hasher hasher(Hasher hasher, Object value, HashMode mode) {

    if (value == null)
        return hasher;

    if (value instanceof Boolean)
        return hasher.putBoolean((Boolean) value);

    if (value instanceof Short)
        return hasher.putShort((Short) value);

    if (value instanceof Integer)
        return hasher.putInt((Integer) value);

    if (value instanceof Long)
        return hasher.putLong((Long) value);

    if (value instanceof Float)
        return hasher.putFloat((Float) value);

    if (value instanceof Double)
        return hasher.putDouble((Double) value);

    if (value instanceof Number)
        // reduce all other number types (BigInteger, BigDecimal, AtomicXxx, etc) to string equivalent
        return hasher.putUnencodedChars(value.toString());

    if (value instanceof Character)
        return hasher.putChar((Character) value);

    if (value instanceof CharSequence)
        return hasher.putUnencodedChars((CharSequence) value);

    if (value instanceof Byte)
        return hasher.putByte((Byte) value);

    if (value instanceof byte[])
        return hasher.putBytes((byte[]) value);

    if (value instanceof Object[]) {
        for (Object item : ((Object[]) value))
            hasher = CacheHelper.hasher(hasher, item, mode);
        return hasher;
    }/* www . j a va 2  s .c  o  m*/

    if (value instanceof Map) {
        // note: should map be order invariant as Set ?
        for (Object item : ((Map) value).values())
            hasher = CacheHelper.hasher(hasher, item, mode);
        return hasher;
    }

    if (value instanceof Bag || value instanceof Set)
        return hashUnorderedCollection(hasher, (Collection) value, mode);

    if (value instanceof Collection) {
        for (Object item : ((Collection) value))
            hasher = CacheHelper.hasher(hasher, item, mode);
        return hasher;
    }

    if (value instanceof FileHolder)
        return CacheHelper.hasher(hasher, ((FileHolder) value).getSourceObj(), mode);

    if (value instanceof Path)
        return hashFile(hasher, (Path) value, mode);

    if (value instanceof java.io.File)
        return hashFile(hasher, (java.io.File) value, mode);

    if (value instanceof UUID) {
        UUID uuid = (UUID) value;
        return hasher.putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits());
    }

    log.debug("[WARN] Unknown hashing type: {} -- {}", value.getClass(), value);
    return hasher.putInt(value.hashCode());
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.join.HashJoinImpl.java

private HashCode hashResultSetRow(int[] columns, PrimitiveDataType[] columnDataTypes, ResultSet resultSet)
        throws ResultSetException {
    Hasher columnHash = hashFunction.newHasher();

    for (int columnI = 0; columnI < columns.length; columnI++) {
        int column = columns[columnI];
        switch (columnDataTypes[columnI].getName()) {
        case "boolean":
            columnHash.putBoolean(resultSet.getBoolean(column));
            break;
        case "byte":
            columnHash.putByte(resultSet.getByte(column));
            break;
        case "double":
            columnHash.putDouble(resultSet.getDouble(column));
            break;
        case "float":
            columnHash.putFloat(resultSet.getFloat(column));
            break;
        case "integer":
            columnHash.putInt(resultSet.getInt(column));
            break;
        case "long":
            columnHash.putLong(resultSet.getLong(column));
            break;
        default:/*www.ja v a  2s . c  o m*/
            columnHash.putString(resultSet.getString(column), Charsets.UTF_8);
            break;
        }
    }

    return columnHash.hash();
}

From source file:org.protelis.vm.util.CodePath.java

/**
 * @param stack//from w w  w .ja  v a  2 s  .com
 *            The numerical markers forming an execution trace to be
 *            represented
 */
public CodePath(final TByteList stack) {
    size = stack.size();
    safe = size < 4;
    if (safe) {
        /*
         * Very short stack, an int suffices.
         */
        path = null;
        int tempHash = 0;
        for (int i = 0; i < stack.size(); i++) {
            /*
             * Suppose we have bytes [1, 2, 3].
             * 
             * First, we map the byte to an int, using the operation
             * described in the comment above. Our first byte, which is the
             * hex number 0x01, becomes 0x00000001. Then, we shift the byte
             * towards left of 0 positions (so it remains exactly equal) and
             * then join it with the current 0x00000000 result through a or
             * operator, so that the current result is 0x00000001.
             * 
             * Our second byte is 0x02. It becomes 0x00000002 first, then
             * gets shifted of 8 bits, namely of two positions in
             * hexadecimal notation. It becomes 0x00000200, and gets
             * combined with the current result (0x00000001) with an or, so
             * the current result becomes 0x00000201.
             * 
             * At the end of our procedure, when the third value has been
             * processed, the resulting value is 0x00030201
             * 
             */
            tempHash |= (stack.get(i) & INT_MASK) << (BITS_PER_BYTE * i);
        }
        hash = tempHash;
    } else {
        final Hasher hashGen = HASH_FUNCTION.newHasher(size);
        path = new long[(stack.size() - 1) / (Long.SIZE / Byte.SIZE) + 1];
        /*
         * Here, we run across all the bytes, and we do two operations at
         * the same time:
         * 
         * 1) We feed our hasher
         * 
         * 2) We fill the long[]. This long[] is filled using a strategy
         * very similar to the one used above for the int hash in case of
         * size < 4.
         */
        for (int i = 0; i < stack.size(); i++) {
            final byte b = stack.get(i);
            hashGen.putByte(b);
            path[i / (Long.SIZE / Byte.SIZE)] |= (b & LONG_MASK) << (BITS_PER_BYTE
                    * (i % (Long.SIZE / Byte.SIZE)));
        }
        hash = hashGen.hash().asInt();
    }
}

From source file:com.facebook.buck.android.ComputeExopackageDepsAbi.java

@Override
public List<Step> getBuildSteps(BuildContext context, final BuildableContext buildableContext) {
    return ImmutableList.<Step>of(new AbstractExecutionStep("compute_android_binary_deps_abi") {
        @Override/* w w  w  . j a  v  a2s.c  o m*/
        public int execute(ExecutionContext context) {
            try {
                ProjectFilesystem filesystem = context.getProjectFilesystem();

                AndroidTransitiveDependencies transitiveDependencies = androidResourceDepsFinder
                        .getAndroidTransitiveDependencies();
                AndroidDexTransitiveDependencies dexTransitiveDependencies = androidResourceDepsFinder
                        .getAndroidDexTransitiveDependencies(uberRDotJava);

                // For exopackages, the only significant thing android_binary does is apkbuilder,
                // so we need to include all of the apkbuilder inputs in the ABI key.
                final Hasher hasher = Hashing.sha1().newHasher();
                // The first input to apkbuilder is the ap_ produced by aapt package.
                // Get its hash from the buildable that created it.
                hasher.putUnencodedChars(aaptPackageResources.getResourcePackageHash().toString());
                // Next is the primary dex.  Same plan.
                hasher.putUnencodedChars(preDexMerge.get().getPrimaryDexHash().toString());
                // Non-english strings packaged as assets.
                if (packageStringAssets.isPresent()) {
                    hasher.putUnencodedChars(packageStringAssets.get().getStringAssetsZipHash().toString());
                }

                // We currently don't use any resource directories, so nothing to add there.

                // Collect files whose sha1 hashes need to be added to our ABI key.
                // This maps from the file to the role it plays, so changing (for example)
                // a native library to an asset will change the ABI key.
                // We assume that these are all order-insensitive to avoid having our ABI key
                // affected by filesystem iteration order.
                ImmutableSortedMap.Builder<Path, String> filesToHash = ImmutableSortedMap.naturalOrder();

                // We add native libraries in apkbuilder, so we need to include their hashes.
                // AndroidTransitiveDependencies doesn't provide BuildRules, only paths.
                // We could augment it, but our current native libraries are small enough that
                // we can just hash them all without too much of a perf hit.
                for (final Path libDir : transitiveDependencies.nativeLibsDirectories) {
                    for (Path nativeFile : filesystem.getFilesUnderPath(libDir)) {
                        filesToHash.put(nativeFile, "native_lib");
                    }
                }

                // Resources get copied from third-party JARs, so hash them.
                for (Path jar : dexTransitiveDependencies.pathsToThirdPartyJars) {
                    filesToHash.put(jar, "third-party jar");
                }

                // The last input is the keystore.
                filesToHash.put(keystore.getPathToStore(), "keystore");
                filesToHash.put(keystore.getPathToPropertiesFile(), "keystore properties");

                for (Map.Entry<Path, String> entry : filesToHash.build().entrySet()) {
                    Path path = entry.getKey();
                    hasher.putUnencodedChars(path.toString());
                    hasher.putByte((byte) 0);
                    hasher.putUnencodedChars(filesystem.computeSha1(path));
                    hasher.putByte((byte) 0);
                }

                buildableContext.addMetadata(METADATA_KEY, hasher.hash().toString());
                return 0;
            } catch (IOException e) {
                context.logError(e, "Error computing ABI hash.");
                return 1;
            }
        }
    });
}