Example usage for com.google.common.hash HashCode equals

List of usage examples for com.google.common.hash HashCode equals

Introduction

In this page you can find the example usage for com.google.common.hash HashCode equals.

Prototype

@Override
public final boolean equals(@Nullable Object object) 

Source Link

Document

Returns true if object is a HashCode instance with the identical byte representation to this hash code.

Usage

From source file:com.facebook.buck.jvm.java.AccumulateClassNamesStep.java

/**
 * @param lines that were written in the same format output by {@link #execute(ExecutionContext)}.
 *///  w w w .  j  av  a2s  .  co m
public static ImmutableSortedMap<String, HashCode> parseClassHashes(List<String> lines) {
    final Map<String, HashCode> classNames = new HashMap<>();

    for (String line : lines) {
        List<String> parts = CLASS_NAME_AND_HASH_SPLITTER.splitToList(line);
        Preconditions.checkState(parts.size() == 2);
        String key = parts.get(0);
        HashCode value = HashCode.fromString(parts.get(1));
        HashCode existing = classNames.putIfAbsent(key, value);
        if (existing != null && !existing.equals(value)) {
            throw new IllegalArgumentException(String.format(
                    "Multiple entries with same key but differing values: %1$s=%2$s and %1$s=%3$s", key, value,
                    existing));
        }
    }

    return ImmutableSortedMap.copyOf(classNames, Ordering.natural());
}

From source file:com.facebook.buck.jvm.java.AccumulateClassNamesStep.java

/**
 * @return an Optional that will be absent if there was an error.
 *///w w  w .j a va 2  s. c o  m
public static Optional<ImmutableSortedMap<String, HashCode>> calculateClassHashes(ExecutionContext context,
        ProjectFilesystem filesystem, Path path) {
    final Map<String, HashCode> classNames = new HashMap<>();

    ClasspathTraversal traversal = new ClasspathTraversal(Collections.singleton(path), filesystem) {
        @Override
        public void visit(final FileLike fileLike) throws IOException {
            // When traversing a JAR file, it may have resources or directory entries that do not
            // end in .class, which should be ignored.
            if (!FileLikes.isClassFile(fileLike)) {
                return;
            }

            String key = FileLikes.getFileNameWithoutClassSuffix(fileLike);
            ByteSource input = new ByteSource() {
                @Override
                public InputStream openStream() throws IOException {
                    return fileLike.getInput();
                }
            };
            HashCode value = input.hash(Hashing.sha1());
            HashCode existing = classNames.putIfAbsent(key, value);
            if (existing != null && !existing.equals(value)) {
                throw new IllegalArgumentException(String.format(
                        "Multiple entries with same key but differing values: %1$s=%2$s and %1$s=%3$s", key,
                        value, existing));
            }
        }
    };

    try {
        new DefaultClasspathTraverser().traverse(traversal);
    } catch (IOException e) {
        context.logError(e, "Error accumulating class names for %s.", path);
        return Optional.empty();
    }

    return Optional.of(ImmutableSortedMap.copyOf(classNames, Ordering.natural()));
}

From source file:io.prestosql.plugin.ml.ModelUtils.java

public static Model deserialize(Slice slice) {
    int version = slice.getInt(VERSION_OFFSET);
    checkArgument(version == CURRENT_FORMAT_VERSION, format("Unsupported version: %d", version));

    byte[] modelHashBytes = slice.getBytes(HASH_OFFSET, 32);
    HashCode expectedHash = HashCode.fromBytes(modelHashBytes);
    HashCode actualHash = Hashing.sha256()
            .hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET));
    checkArgument(actualHash.equals(expectedHash), "model hash does not match data");

    int id = slice.getInt(ALGORITHM_OFFSET);
    Class<? extends Model> algorithm = MODEL_SERIALIZATION_IDS.inverse().get(id);
    requireNonNull(algorithm, format("Unsupported algorith %d", id));

    int hyperparameterLength = slice.getInt(HYPERPARAMETER_LENGTH_OFFSET);

    byte[] hyperparameterBytes = slice.getBytes(HYPERPARAMETERS_OFFSET, hyperparameterLength);

    int dataLengthOffset = HYPERPARAMETERS_OFFSET + hyperparameterLength;
    long dataLength = slice.getLong(dataLengthOffset);

    int dataOffset = dataLengthOffset + SIZE_OF_LONG;
    byte[] data = slice.getBytes(dataOffset, (int) dataLength);

    try {/*from  w  ww .java  2  s . c om*/
        Method deserialize = algorithm.getMethod("deserialize", byte[].class);
        return (Model) deserialize.invoke(null, new Object[] { data });
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.facebook.presto.ml.ModelUtils.java

public static Model deserialize(Slice slice) {
    int version = slice.getInt(VERSION_OFFSET);
    checkArgument(version == CURRENT_FORMAT_VERSION, format("Unsupported version: %d", version));

    byte[] modelHashBytes = slice.getBytes(HASH_OFFSET, 32);
    HashCode expectedHash = HashCode.fromBytes(modelHashBytes);
    HashCode actualHash = Hashing.sha256()
            .hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET));
    checkArgument(actualHash.equals(expectedHash), "model hash does not match data");

    int id = slice.getInt(ALGORITHM_OFFSET);
    Class<? extends Model> algorithm = MODEL_SERIALIZATION_IDS.inverse().get(id);
    requireNonNull(algorithm, format("Unsupported algorith %d", id));

    int hyperparameterLength = slice.getInt(HYPERPARAMETER_LENGTH_OFFSET);

    byte[] hyperparameterBytes = slice.getBytes(HYPERPARAMETERS_OFFSET, hyperparameterLength);

    int dataLengthOffset = HYPERPARAMETERS_OFFSET + hyperparameterLength;
    long dataLength = slice.getLong(dataLengthOffset);

    int dataOffset = dataLengthOffset + SIZE_OF_LONG;
    byte[] data = slice.getBytes(dataOffset, (int) dataLength);

    try {//from   w  w w .  j a  v  a 2s  .  com
        Method deserialize = algorithm.getMethod("deserialize", byte[].class);
        return (Model) deserialize.invoke(null, new Object[] { data });
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.gradle.api.internal.changedetection.state.DefaultFileSnapshot.java

@Override
public FileSnapshot withContentHash(HashCode contentHash) {
    if (!contentHash.equals(getContent().getContentMd5())) {
        return new DefaultFileSnapshot(path, relativePath, type, root, new FileHashSnapshot(contentHash));
    }//from w  ww . j a v a  2 s .  c  o  m
    return this;
}

From source file:org.gradle.api.internal.changedetection.state.RegularFileSnapshot.java

@Override
public RegularFileSnapshot withContentHash(HashCode contentHash) {
    if (!contentHash.equals(getContent().getContentMd5())) {
        return new RegularFileSnapshot(path, relativePath, root, new FileHashSnapshot(contentHash));
    }// w w w  .j a va 2s  . co m
    return this;
}

From source file:org.gradle.api.internal.changedetection.state.ResourceSnapshotterCacheService.java

public HashCode hashFile(RegularFileSnapshot fileSnapshot, RegularFileHasher hasher, byte[] configurationHash) {
    HashCode resourceHashCacheKey = resourceHashCacheKey(fileSnapshot, configurationHash);

    HashCode resourceHash = persistentCache.get(resourceHashCacheKey);
    if (resourceHash != null) {
        if (resourceHash.equals(NO_HASH)) {
            return null;
        }/*from ww  w  .j a va  2s .  co  m*/
        return resourceHash;
    }

    resourceHash = hasher.hash(fileSnapshot);

    if (resourceHash != null) {
        persistentCache.put(resourceHashCacheKey, resourceHash);
    } else {
        persistentCache.put(resourceHashCacheKey, NO_HASH);
    }
    return resourceHash;
}

From source file:org.gradle.api.internal.tasks.compile.incremental.jar.JarSnapshot.java

private DependentsSet affectedSince(JarSnapshot other) {
    final Set<String> affected = new HashSet<String>();
    for (Map.Entry<String, HashCode> otherClass : other.getHashes().entrySet()) {
        String otherClassName = otherClass.getKey();
        HashCode otherClassBytes = otherClass.getValue();
        HashCode thisClsBytes = getHashes().get(otherClassName);
        if (thisClsBytes == null || !thisClsBytes.equals(otherClassBytes)) {
            //removed since or changed since
            affected.add(otherClassName);
            DependentsSet dependents = other.getAnalysis().getRelevantDependents(otherClassName);
            if (dependents.isDependencyToAll()) {
                return dependents;
            }/*w w w.  ja v  a  2  s .  com*/
            affected.addAll(dependents.getDependentClasses());
        }
    }
    return new DefaultDependentsSet(affected);
}

From source file:org.apache.pulsar.broker.service.schema.SchemaRegistryServiceImpl.java

private boolean isCompatible(SchemaAndMetadata existingSchema, SchemaData newSchema,
        SchemaCompatibilityStrategy strategy) {
    HashCode existingHash = hashFunction.hashBytes(existingSchema.schema.getData());
    HashCode newHash = hashFunction.hashBytes(newSchema.getData());
    return newHash.equals(existingHash)
            || compatibilityChecks.getOrDefault(newSchema.getType(), SchemaCompatibilityCheck.DEFAULT)
                    .isCompatible(existingSchema.schema, newSchema, strategy);
}

From source file:com.google.devtools.build.lib.worker.WorkerFactory.java

/** The worker is considered to be valid when its files have not changed on disk. */
@Override// ww w  . j a va  2 s. c o m
public boolean validateObject(WorkerKey key, PooledObject<Worker> p) {
    Worker worker = p.getObject();
    boolean hashMatches = key.getWorkerFilesCombinedHash().equals(worker.getWorkerFilesCombinedHash());

    if (reporter != null && !hashMatches) {
        StringBuilder msg = new StringBuilder();
        msg.append(String.format(
                "%s worker (id %d) can no longer be used, because its files have changed on disk:",
                key.getMnemonic(), worker.getWorkerId()));
        TreeSet<PathFragment> files = new TreeSet<>();
        files.addAll(key.getWorkerFilesWithHashes().keySet());
        files.addAll(worker.getWorkerFilesWithHashes().keySet());
        for (PathFragment file : files) {
            HashCode oldHash = key.getWorkerFilesWithHashes().get(file);
            HashCode newHash = worker.getWorkerFilesWithHashes().get(file);
            if (!oldHash.equals(newHash)) {
                msg.append("\n").append(file.getPathString()).append(": ")
                        .append(oldHash != null ? oldHash : "<none>").append(" -> ")
                        .append(newHash != null ? newHash : "<none>");
            }
        }

        reporter.handle(Event.warn(msg.toString()));
    }

    return hashMatches;
}