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.android.build.gradle.tasks.JillTask.java

/**
 * Returns the hash of a file.//from   w w  w. j a  v  a 2s.c  o  m
 *
 * @param file the file to hash
 */
private static String getFileHash(@NonNull File file) throws IOException {
    HashCode hashCode = Files.hash(file, Hashing.sha1());
    return hashCode.toString();
}

From source file:org.sonatype.nexus.rapture.internal.ui.StateComponent.java

public static String hash(final Object value) {
    if (value != null) {
        // TODO is there another way to not use serialized json? :D
        return Hashing.sha1().hashString(gson.toJson(value), Charsets.UTF_8).toString();
    }//from   w  w w  .  j  a v  a2  s  . c o m
    return null;
}

From source file:com.palantir.typescript.preferences.TsConfigPreferences.java

private String getFileSHA1(IFile tsConfigFile) throws IOException {
    return Files.hash(tsConfigFile.getRawLocation().toFile(), Hashing.sha1()).toString();
}

From source file:com.netflix.exhibitor.core.rest.ConfigResource.java

@Path("get-state")
@GET//  w  w w  .ja  v  a  2 s  . c o  m
@Produces(MediaType.APPLICATION_JSON)
public Response getSystemState(@Context Request request) throws Exception {
    InstanceConfig config = context.getExhibitor().getConfigManager().getConfig();

    String response = new FourLetterWord(FourLetterWord.Word.RUOK, config,
            context.getExhibitor().getConnectionTimeOutMs()).getResponse();
    ServerList serverList = new ServerList(config.getString(StringConfigs.SERVERS_SPEC));
    ServerSpec us = Iterables.find(serverList.getSpecs(),
            ServerList.isUs(context.getExhibitor().getThisJVMHostname()), null);

    ObjectNode mainNode = JsonNodeFactory.instance.objectNode();
    ObjectNode configNode = JsonNodeFactory.instance.objectNode();
    ObjectNode controlPanelNode = JsonNodeFactory.instance.objectNode();

    mainNode.put("version", context.getExhibitor().getVersion());
    mainNode.put("running", "imok".equals(response));
    mainNode.put("backupActive", context.getExhibitor().getBackupManager().isActive());
    mainNode.put("standaloneMode", context.getExhibitor().getConfigManager().isStandaloneMode());
    mainNode.put("extraHeadingText", context.getExhibitor().getExtraHeadingText());
    mainNode.put("nodeMutationsAllowed", context.getExhibitor().nodeMutationsAllowed());

    configNode.put("rollInProgress", context.getExhibitor().getConfigManager().isRolling());
    configNode.put("rollStatus",
            context.getExhibitor().getConfigManager().getRollingConfigState().getRollingStatus());
    configNode.put("rollPercentDone",
            context.getExhibitor().getConfigManager().getRollingConfigState().getRollingPercentDone());

    configNode.put("hostname", context.getExhibitor().getThisJVMHostname());
    configNode.put("serverId", (us != null) ? us.getServerId() : -1);
    for (StringConfigs c : StringConfigs.values()) {
        configNode.put(fixName(c), config.getString(c));
    }
    for (IntConfigs c : IntConfigs.values()) {
        String fixedName = fixName(c);
        int value = config.getInt(c);

        configNode.put(fixedName, value);
    }

    EncodedConfigParser zooCfgParser = new EncodedConfigParser(config.getString(StringConfigs.ZOO_CFG_EXTRA));
    ObjectNode zooCfgNode = JsonNodeFactory.instance.objectNode();
    for (EncodedConfigParser.FieldValue fv : zooCfgParser.getFieldValues()) {
        zooCfgNode.put(fv.getField(), fv.getValue());
    }
    configNode.put("zooCfgExtra", zooCfgNode);

    if (context.getExhibitor().getBackupManager().isActive()) {
        ObjectNode backupExtraNode = JsonNodeFactory.instance.objectNode();
        EncodedConfigParser parser = context.getExhibitor().getBackupManager().getBackupConfigParser();
        List<BackupConfigSpec> configs = context.getExhibitor().getBackupManager().getConfigSpecs();
        for (BackupConfigSpec c : configs) {
            String value = parser.getValue(c.getKey());
            backupExtraNode.put(c.getKey(), (value != null) ? value : "");
        }
        configNode.put("backupExtra", backupExtraNode);
    }

    configNode.put("controlPanel", controlPanelNode);
    mainNode.put("config", configNode);

    String json = JsonUtil.writeValueAsString(mainNode);
    EntityTag tag = new EntityTag(Hashing.sha1().hashString(json).toString());

    Response.ResponseBuilder builder = request.evaluatePreconditions(tag);
    if (builder == null) {
        builder = Response.ok(json).tag(tag);
    }

    return builder.build();
}

From source file:com.android.build.gradle.tasks.JackPreDexTransform.java

/**
 * Returns a unique file name for the converted library, even if there are 2 libraries with the
 * same file names (but different paths)
 *
 * @param inputFile the library/*ww w .j a va  2  s.co m*/
 */
@NonNull
public static String getJackFileName(@NonNull File inputFile) {
    // get the filename
    String name = inputFile.getName();
    // remove the extension
    int pos = name.lastIndexOf('.');
    if (pos != -1) {
        name = name.substring(0, pos);
    }

    // add a hash of the original file path.
    String input = inputFile.getAbsolutePath();
    HashFunction hashFunction = Hashing.sha1();
    HashCode hashCode = hashFunction.hashString(input, Charsets.UTF_16LE);

    return name + "-" + hashCode.toString();
}

From source file:com.spotify.scio.util.RemoteFileUtil.java

private static Path getDestination(URI src) throws IOException {
    String scheme = src.getScheme();
    if (scheme == null) {
        scheme = "file";
    }/*from   ww w.  ja  v  a 2s.  c o  m*/

    // Sparkey expects a pair of ".spi" and ".spl" files with the same path. Hash URI prefix
    // before filename so that URIs with the same remote path have the same local one. E.g.
    // gs://bucket/path/data.spi -> /tmp/fd-gs-a1b2c3d4/data.spi
    // gs://bucket/path/data.spl -> /tmp/fd-gs-a1b2c3d4/data.spl
    String path = src.toString();
    int idx = path.lastIndexOf('/');
    String hash = Hashing.sha1().hashString(path.substring(0, idx), Charsets.UTF_8).toString().substring(0,
            HASH_LENGTH);
    String filename = path.substring(idx + 1);

    String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
    Path parent = Paths.get(tmpDir, String.format("fd-%s-%s", scheme, hash));
    Files.createDirectories(parent);
    return parent.resolve(filename);
}

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

/**
 * @return an Optional that will be absent if there was an error.
 *//*from  w w  w  . j a  v  a  2 s  . co m*/
private Optional<ImmutableSortedMap<String, HashCode>> calculateClassHashes(ExecutionContext context,
        Path path) {
    final ImmutableSortedMap.Builder<String, HashCode> classNamesBuilder = ImmutableSortedMap.naturalOrder();
    ClasspathTraversal traversal = new ClasspathTraversal(Collections.singleton(path),
            context.getProjectFilesystem()) {
        @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);
            InputSupplier<InputStream> input = new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return fileLike.getInput();
                }
            };
            HashCode value = ByteStreams.hash(input, Hashing.sha1());
            classNamesBuilder.put(key, value);
        }
    };

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

    return Optional.of(classNamesBuilder.build());
}

From source file:org.dcache.gridsite.DelegationService.java

private String generateDelegationId(Subject subject) throws DelegationException {
    String generator = Subjects.getDn(subject) + Subjects.getFqans(subject);
    byte[] raw = generator.getBytes(Charsets.UTF_8);
    byte[] digest = Hashing.sha1().hashBytes(raw).asBytes();
    return BaseEncoding.base16().encode(digest, 0, 20);
}

From source file:com.facebook.buck.rules.modern.builders.RemoteExecution.java

@Override
public void build(ExecutionContext executionContext, FileTreeBuilder inputsBuilder, Set<Path> outputs,
        Path projectRoot, HashCode hash, BuildTarget buildTarget, Path cellPrefixRoot)
        throws IOException, InterruptedException, StepFailedException {

    HashMap<Digest, ThrowingSupplier<InputStream, IOException>> requiredDataBuilder;
    Digest commandDigest;//from w  w w  .  j a v  a2 s .  c o  m
    Digest inputsRootDigest;

    try (Scope ignored = LeafEvents.scope(eventBus, "deleting_stale_outputs")) {
        for (Path path : outputs) {
            MostFiles.deleteRecursivelyIfExists(cellPrefixRoot.resolve(path));
        }
    }

    try (Scope ignored = LeafEvents.scope(eventBus, "computing_action")) {
        ImmutableList<Path> isolatedClasspath = processClasspath(inputsBuilder, cellPrefixRoot,
                Holder.classPath);
        ImmutableList<Path> isolatedBootstrapClasspath = processClasspath(inputsBuilder, cellPrefixRoot,
                Holder.bootstrapClassPath);

        Path trampolinePath = Paths.get("./__trampoline__.sh");
        ImmutableList<String> command = getBuilderCommand(trampolinePath, projectRoot, hash.toString());
        ImmutableSortedMap<String, String> commandEnvironment = getBuilderEnvironmentOverrides(
                isolatedBootstrapClasspath, isolatedClasspath);

        inputsBuilder.addFile(trampolinePath, () -> trampoline,
                data -> Hashing.sha1().hashBytes(data).toString(), true);

        Protocol.Command actionCommand = getProtocol().newCommand(command, commandEnvironment);

        requiredDataBuilder = new HashMap<>();
        ProtocolTreeBuilder grpcTreeBuilder = new ProtocolTreeBuilder(requiredDataBuilder::put, directory -> {
        }, getProtocol());
        inputsRootDigest = inputsBuilder.buildTree(grpcTreeBuilder);
        byte[] commandData = getProtocol().toByteArray(actionCommand);
        commandDigest = getProtocol().computeDigest(commandData);
        requiredDataBuilder.put(commandDigest, () -> new ByteArrayInputStream(commandData));
    }

    try (Scope scope = LeafEvents.scope(eventBus, "uploading_inputs")) {
        getStorage().addMissing(ImmutableMap.copyOf(requiredDataBuilder));
    }
    ExecutionResult result11 = getExecutionService().execute(commandDigest, inputsRootDigest, outputs);
    try (Scope scope = LeafEvents.scope(eventBus, "materializing_outputs")) {
        getStorage().materializeOutputs(result11.getOutputDirectories(), result11.getOutputFiles(),
                cellPrefixRoot);
    }
    ExecutionResult result = result11;

    if (result.getExitCode() != 0) {
        throw StepFailedException
                .createForFailingStepWithExitCode(new AbstractExecutionStep("remote_execution") {
                    @Override
                    public StepExecutionResult execute(ExecutionContext context) {
                        throw new RuntimeException();
                    }
                }, executionContext, StepExecutionResult.of(result.getExitCode(), result.getStderr()),
                        Optional.of(buildTarget));
    }
}

From source file:com.facebook.buck.js.ReactNativeDeps.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, final BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();

    final Path output = BuildTargets.getScratchPath(getBuildTarget(), "__%s/deps.txt");
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), output.getParent()));

    steps.add(new ShellStep(getProjectFilesystem().getRootPath()) {
        @Override//w  ww  .  j  a  v  a2  s .co  m
        protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
            ImmutableList.Builder<String> builder = ImmutableList.builder();

            builder.add(getResolver().getAbsolutePath(jsPackager).toString(), "list-dependencies",
                    platform.toString(),
                    getProjectFilesystem().resolve(getResolver().getAbsolutePath(entryPath)).toString(),
                    "--output", getProjectFilesystem().resolve(output).toString());

            if (packagerFlags.isPresent()) {
                builder.addAll(Arrays.asList(packagerFlags.get().split(" ")));
            }

            return builder.build();
        }

        @Override
        public String getShortName() {
            return "react-native-deps";
        }
    });

    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), outputDir));

    steps.add(new AbstractExecutionStep("hash_js_inputs") {
        @Override
        public int execute(ExecutionContext context) throws IOException {
            ImmutableList<Path> paths;
            try {
                paths = FluentIterable.from(getProjectFilesystem().readLines(output))
                        .transform(MorePaths.TO_PATH).transform(getProjectFilesystem().getRelativizer())
                        .toSortedList(Ordering.natural());
            } catch (IOException e) {
                context.logError(e, "Error reading output of the 'react-native-deps' step.");
                return 1;
            }

            FluentIterable<SourcePath> unlistedSrcs = FluentIterable.from(paths)
                    .transform(SourcePaths.toSourcePath(getProjectFilesystem()))
                    .filter(Predicates.not(Predicates.in(srcs)));
            if (!unlistedSrcs.isEmpty()) {
                context.logError(new RuntimeException(),
                        "Entry path '%s' transitively uses the following source files which were not "
                                + "included in 'srcs':\n%s",
                        entryPath, Joiner.on('\n').join(unlistedSrcs));
                return 1;
            }

            Hasher hasher = Hashing.sha1().newHasher();
            for (Path path : paths) {
                try {
                    hasher.putUnencodedChars(getProjectFilesystem().computeSha1(path));
                } catch (IOException e) {
                    context.logError(e, "Error hashing input file: %s", path);
                    return 1;
                }
            }

            String inputsHash = hasher.hash().toString();
            buildableContext.addMetadata(METADATA_KEY_FOR_INPUTS_HASH, inputsHash);
            getProjectFilesystem().writeContentsToPath(inputsHash, inputsHashFile);
            return 0;
        }
    });

    return steps.build();
}