Example usage for com.google.common.hash Hashing sha1

List of usage examples for com.google.common.hash Hashing sha1

Introduction

In this page you can find the example usage for com.google.common.hash Hashing sha1.

Prototype

public static HashFunction sha1() 

Source Link

Document

Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the SHA-1 MessageDigest .

Usage

From source file:com.google.collide.dtogen.DtoGenerator.java

private static String getApiHash(File interfaceJar) throws IOException {
    byte[] fileBytes = Files.toByteArray(interfaceJar);
    HashCode hashCode = Hashing.sha1().hashBytes(fileBytes);
    return hashCode.toString();
}

From source file:io.macgyver.plugin.cloud.vsphere.VSphereScanner.java

public String computeMacId(ManagedObjectReference mor) {
    Preconditions.checkNotNull(mor, "ManagedObjectReference cannot be null");

    Preconditions.checkArgument(!ManagedObjectTypes.VIRTUAL_MACHINE.equals(mor.getType()),
            "cannot call computeMacId() with mor.type=VirtualMachine");

    return Hashing.sha1().hashString(getVCenterId() + mor.getType() + mor.getVal(), Charsets.UTF_8).toString();
}

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//ww w.j a  v  a 2s.c  om
        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;
            }
        }
    });
}

From source file:com.ifedorenko.m2e.sourcelookup.internal.PomPropertiesScanner.java

public List<T> scan(File location) throws CoreException {
    Set<T> result = new LinkedHashSet<T>();
    for (Properties pomProperties : SCANNER.scan(location, "pom.properties")) {
        T t;/*www.  j  a va2 s  .  c o  m*/

        String projectName = pomProperties.getProperty("m2e.projectName");
        File projectLocation = getFile(pomProperties, "m2e.projectLocation");
        IProject project = projectName != null
                ? ResourcesPlugin.getWorkspace().getRoot().getProject(projectName)
                : null;
        if (project != null && project.isAccessible()
                && project.getLocation().toFile().equals(projectLocation)) {
            IMavenProjectFacade mavenProject = projectRegistry.getProject(project);

            if (mavenProject != null) {
                t = visitMavenProject(mavenProject);
            } else {
                t = visitProject(project);
            }
        } else {
            String groupId = pomProperties.getProperty("groupId");
            String artifactId = pomProperties.getProperty("artifactId");
            String version = pomProperties.getProperty("version");
            t = visitGAVC(groupId, artifactId, version, null);
        }

        if (t != null) {
            result.add(t);
        }
    }

    if (location.isFile()) {
        IndexedArtifactFile indexed = identifyNexusIndexer(location);
        if (indexed != null) {
            ArtifactKey a = indexed.getArtifactKey();
            T t = visitGAVC(a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getClassifier());
            if (t != null) {
                result.add(t);
            }
        }

        try {
            String sha1 = Files.hash(location, Hashing.sha1()).toString();
            URL url = new URL("https://search.maven.org/solrsearch/select?q=1:" + sha1);
            try (InputStreamReader reader = new InputStreamReader(url.openStream(), Charsets.UTF_8)) {
                JsonObject container = new Gson().fromJson(reader, JsonObject.class);
                JsonArray docs = container.get("response").getAsJsonObject().get("docs").getAsJsonArray();
                for (int i = 0; i < docs.size(); i++) {
                    JsonObject doc = docs.get(i).getAsJsonObject();
                    String g = doc.get("g").getAsString();
                    String a = doc.get("a").getAsString();
                    String v = doc.get("v").getAsString();
                    T t = visitGAVC(g, a, v, null);
                    if (t != null) {
                        result.add(t);
                    }
                }
            }
        } catch (IOException e) {
            // XXX
        }
    }

    return new ArrayList<T>(result);
}

From source file:com.torchmind.stockpile.server.controller.v1.BlacklistController.java

/**
 * Checks a hostname against the blacklist.
 *
 * @param hostname a hostname.//  w w  w.jav a 2s.  c  o m
 * @return a blacklist result.
 */
@Nonnull
private BlacklistResult checkHostname(@Nonnull String hostname) {
    List<String> hostnameParts = Splitter.on('.').splitToList(hostname);

    for (int i = 1; i < hostnameParts.size(); ++i) {
        String currentHostname = "*." + Joiner.on('.').join(hostnameParts.subList(i, hostnameParts.size()));
        String hash = Hashing.sha1().hashString(currentHostname, StandardCharsets.ISO_8859_1).toString();

        if (this.hashes.contains(hash)) {
            return new BlacklistResult(currentHostname, true);
        }
    }

    return new BlacklistResult(hostname, false);
}

From source file:org.lendingclub.mercator.vmware.VMWareScanner.java

public String computeUniqueId(ManagedObjectReference mor) {
    Preconditions.checkNotNull(mor, "ManagedObjectReference cannot be null");

    Preconditions.checkArgument(!ManagedObjectTypes.VIRTUAL_MACHINE.equals(mor.getType()),
            "cannot call computeMacId() with mor.type=VirtualMachine");

    return Hashing.sha1().hashString(getVCenterId() + mor.getType() + mor.getVal(), Charsets.UTF_8).toString();
}

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

/**
 * @return an Optional that will be absent if there was an error.
 *//*from   w  ww .  j  av a2s.c om*/
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:org.obm.push.calendar.EventServiceImpl.java

private byte[] hashEventExtId(String eventExtId) {
    HashCode hashCode = Hashing.sha1().hashString(eventExtId, Charsets.US_ASCII);
    return hashCode.asBytes();
}

From source file:org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.impl.SessionCookie.java

private String mkCookie(String user, Date expiry) {
    return new StringBuilder().append(user).append(COOKIE_STRING_SEPARATOR).append(expiry.toString())
            .append(COOKIE_STRING_SEPARATOR).append(Hashing.sha1()
                    .hashString(SERVER_SECRET + user + expiry.getTime() / 1000, StandardCharsets.UTF_8))
            .toString();/*from   w  ww.j av a2 s  .  c  o m*/
}

From source file:com.facebook.buck.java.intellij.IjProjectWriter.java

@VisibleForTesting
protected void writeToFile(ST contents, Path path) throws IOException {
    StringWriter stringWriter = new StringWriter();
    AutoIndentWriter noIndentWriter = new AutoIndentWriter(stringWriter);
    contents.write(noIndentWriter);/*from   w ww  . j  av a 2s  .  c o  m*/
    byte[] renderedContentsBytes = noIndentWriter.toString().getBytes(StandardCharsets.UTF_8);
    if (projectFilesystem.exists(path)) {
        String fileSha1 = projectFilesystem.computeSha1(path);
        String contentsSha1 = Hashing.sha1().hashBytes(renderedContentsBytes).toString();
        if (fileSha1.equals(contentsSha1)) {
            return;
        }
    }

    boolean danglingTempFile = false;
    Path tempFile = projectFilesystem.createTempFile(
            projectFilesystem.getPathForRelativePath(IDEA_CONFIG_DIR_PREFIX), path.getFileName().toString(),
            ".tmp");
    try {
        danglingTempFile = true;
        try (OutputStream outputStream = projectFilesystem.newFileOutputStream(tempFile)) {
            outputStream.write(contents.render().getBytes());
        }
        projectFilesystem.createParentDirs(path);
        projectFilesystem.move(tempFile, path, StandardCopyOption.REPLACE_EXISTING);
        danglingTempFile = false;
    } finally {
        if (danglingTempFile) {
            projectFilesystem.deleteFileAtPath(tempFile);
        }
    }
}