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

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

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string containing each byte of #asBytes , in order, as a two-digit unsigned hexadecimal number in lower case.

Usage

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

private void addDeserializationInputs(HashCode hash, FileTreeBuilder inputsBuilder) throws IOException {
    class DataAdder {
        void addData(Path root, String hash, Node node) throws IOException {
            inputsBuilder.addFile(root.resolve("__value__"), () -> new InputFile(hash, node.data.length, false,
                    () -> new ByteArrayInputStream(node.data)));
            for (Map.Entry<String, Node> child : node.children.entrySet()) {
                addData(root.resolve(child.getKey()), child.getKey(), child.getValue());
            }//ww w .  j a  v a2  s  .  c  om
        }
    }

    new DataAdder().addData(Paths.get("__data__").resolve(hash.toString()), hash.toString(),
            Preconditions.checkNotNull(nodeMap.get(hash)));
}

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

/** Deserializes the BuildableAndTarget corresponding to hash and builds it. */
public void build(HashCode hash) throws IOException, StepFailedException, InterruptedException {
    final Instant start = Instant.now();
    Deserializer deserializer = new Deserializer(filesystemFunction, classFinder,
            buildContext::getSourcePathResolver,
            // TODO(cjhopman): This gets toolchains from the root cell (instead of the cell the rule
            // is in).
            toolchainProviderFunction.apply(Optional.empty()));

    BuildableAndTarget reconstructed;//from   ww w .  ja v a 2 s.c  om
    try (Scope ignored = LeafEvents.scope(eventBus, "deserializing")) {
        reconstructed = deserializer.deserialize(getProvider(dataRoot.resolve(hash.toString())),
                BuildableAndTarget.class);
    }

    try (Scope ignored = LeafEvents.scope(eventBus, "steps")) {
        ProjectFilesystem filesystem = filesystemFunction.apply(reconstructed.target.getCell());
        ModernBuildRule.injectFieldsIfNecessary(filesystem, reconstructed.target, reconstructed.buildable,
                new SourcePathRuleFinder(new AbstractBuildRuleResolver() {
                    @Override
                    public Optional<BuildRule> getRuleOptional(BuildTarget buildTarget) {
                        throw new RuntimeException("Cannot resolve rules in deserialized MBR state.");
                    }
                }));

        final Instant deserializationComplete = Instant.now();
        LOG.info(String.format("Finished deserializing the rule at [%s], took %d ms. Running the build now.",
                new java.util.Date(),
                deserializationComplete.minusMillis(start.toEpochMilli()).toEpochMilli()));

        for (Step step : ModernBuildRule.stepsForBuildable(buildContext, reconstructed.buildable, filesystem,
                reconstructed.target)) {
            new DefaultStepRunner().runStepForBuildTarget(executionContext, step,
                    Optional.of(reconstructed.target));
        }

        LOG.info(String.format("Finished running the build at [%s], took %d ms. Exiting buck now.",
                new java.util.Date(),
                Instant.now().minusMillis(deserializationComplete.toEpochMilli()).toEpochMilli()));
    }
}

From source file:com.facebook.buck.rules.RuleKeyBuilder.java

public RuleKeyBuilder setPath(Path absolutePath, Path ideallyRelative) throws IOException {
    // TODO(shs96c): Enable this precondition once setPath(Path) has been removed.
    // Preconditions.checkState(absolutePath.isAbsolute());
    HashCode sha1 = hashCache.get(absolutePath);
    if (sha1 == null) {
        throw new RuntimeException("No SHA for " + absolutePath);
    }/* w ww.j a v a 2s . com*/

    Path addToKey;
    if (ideallyRelative.isAbsolute()) {
        logger.warn("Attempting to add absolute path to rule key. Only using file name: %s", ideallyRelative);
        addToKey = ideallyRelative.getFileName();
    } else {
        addToKey = ideallyRelative;
    }

    if (logElms != null) {
        logElms.add(String.format("path(%s:%s):", addToKey, sha1));
    }

    feed(addToKey.toString().getBytes());
    feed(sha1.toString().getBytes());
    return this;
}

From source file:com.android.builder.internal.compiler.PreProcessCache.java

@Nullable
protected Node createItemNode(@NonNull Document document, @NonNull T itemKey, @NonNull BaseItem item)
        throws IOException {
    if (!item.areOutputFilesPresent()) {
        return null;
    }//w w  w. j  a va 2s . com

    Node itemNode = document.createElement(NODE_ITEM);

    Attr attr = document.createAttribute(ATTR_JAR);
    attr.setValue(item.getSourceFile().getPath());
    itemNode.getAttributes().setNamedItem(attr);

    attr = document.createAttribute(ATTR_REVISION);
    attr.setValue(itemKey.getBuildToolsRevision().toString());
    itemNode.getAttributes().setNamedItem(attr);

    HashCode hashCode = item.getSourceHash();
    if (hashCode == null) {
        try {
            hashCode = Files.hash(item.getSourceFile(), Hashing.sha1());
        } catch (IOException ex) {
            // If we can't compute the hash for whatever reason, simply skip this entry.
            return null;
        }
    }
    attr = document.createAttribute(ATTR_SHA1);
    attr.setValue(hashCode.toString());
    itemNode.getAttributes().setNamedItem(attr);

    for (File dexFile : item.getOutputFiles()) {

        Node dexNode = document.createElement(NODE_DEX);
        itemNode.appendChild(dexNode);

        attr = document.createAttribute(ATTR_DEX);
        attr.setValue(dexFile.getPath());
        dexNode.getAttributes().setNamedItem(attr);
    }

    return itemNode;
}

From source file:de.schildbach.pte.AbstractHafasMobileProvider.java

private HttpUrl requestUrl(final String body) {
    final HttpUrl.Builder url = checkNotNull(mgateEndpoint).newBuilder();
    if (requestChecksumSalt != null) {
        final HashCode checksum = MD5.newHasher().putString(body, Charsets.UTF_8)
                .putString(requestChecksumSalt, Charsets.UTF_8).hash();
        url.addQueryParameter("checksum", checksum.toString());
    }/*from   w w  w .  j  ava  2  s  .  c  o  m*/
    if (requestMicMacSalt != null) {
        final HashCode mic = MD5.newHasher().putString(body, Charsets.UTF_8).hash();
        url.addQueryParameter("mic", HEX.encode(mic.asBytes()));
        final HashCode mac = MD5.newHasher().putString(HEX.encode(mic.asBytes()), Charsets.UTF_8)
                .putBytes(HEX.decode(requestMicMacSalt)).hash();
        url.addQueryParameter("mac", HEX.encode(mac.asBytes()));
    }
    return url.build();
}

From source file:com.android.ide.eclipse.adt.internal.build.BuildHelper.java

private String getDexFileName(File inputFile) {
    // get the filename
    String name = inputFile.getName();
    // remove the extension
    int pos = name.lastIndexOf('.');
    if (pos != -1) {
        name = name.substring(0, pos);//from  w w w .j  a v a  2 s . co  m
    }

    // add a hash of the original file path
    HashFunction hashFunction = Hashing.md5();
    HashCode hashCode = hashFunction.hashString(inputFile.getAbsolutePath());

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

From source file:org.graylog2.web.resources.WebInterfaceAssetsResource.java

private Response getResponse(Request request, String filename, URL resourceUrl, boolean fromPlugin)
        throws IOException, URISyntaxException {
    final Date lastModified;
    final InputStream stream;
    final HashCode hashCode;

    switch (resourceUrl.getProtocol()) {
    case "file": {
        final File file = new File(resourceUrl.toURI());
        lastModified = new Date(file.lastModified());
        stream = new FileInputStream(file);
        hashCode = Files.hash(file, Hashing.sha256());
        break;/* w  ww .  ja va 2 s  .c  om*/
    }
    case "jar": {
        final URI uri = resourceUrl.toURI();
        final FileSystem fileSystem = fileSystemCache.getUnchecked(uri);
        final java.nio.file.Path path = fileSystem.getPath(pluginPrefixFilename(fromPlugin, filename));
        final FileTime lastModifiedTime = java.nio.file.Files.getLastModifiedTime(path);
        lastModified = new Date(lastModifiedTime.toMillis());
        stream = resourceUrl.openStream();
        hashCode = Resources.asByteSource(resourceUrl).hash(Hashing.sha256());
        break;
    }
    default:
        throw new IllegalArgumentException("Not a jar or file");
    }

    final EntityTag entityTag = new EntityTag(hashCode.toString());

    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified, entityTag);
    if (response != null) {
        return response.build();
    }

    final String contentType = firstNonNull(mimeTypes.getContentType(filename),
            MediaType.APPLICATION_OCTET_STREAM);
    final CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge((int) TimeUnit.DAYS.toSeconds(365));
    cacheControl.setNoCache(false);
    cacheControl.setPrivate(false);
    return Response.ok(stream).header(HttpHeaders.CONTENT_TYPE, contentType).tag(entityTag)
            .cacheControl(cacheControl).lastModified(lastModified).build();
}

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;/* w w w  .  ja va  2s  . 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:org.eclipse.andmore.internal.build.BuildHelper.java

private String getDexFileName(File inputFile) {
    // get the filename
    String name = inputFile.getName();
    // remove the extension
    int pos = name.lastIndexOf('.');
    if (pos != -1) {
        name = name.substring(0, pos);/*  w  w w. j  a  v  a 2s .co m*/
    }

    // add a hash of the original file path
    HashFunction hashFunction = Hashing.md5();
    HashCode hashCode = hashFunction.hashString(inputFile.getAbsolutePath(), Charset.defaultCharset());

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

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

private MerkleTreeNode getSerializationTreeAndInputs(HashCode hash,
        Map<Digest, UploadDataSupplier> requiredDataBuilder) {
    Map<Path, FileNode> fileNodes = new HashMap<>();
    class DataAdder {
        void addData(Path root, String hash, Node node) {
            String fileName = "__value__";
            Path valuePath = root.resolve(fileName);
            Digest digest = protocol.newDigest(hash, node.data.length);
            fileNodes.put(valuePath, protocol.newFileNode(digest, fileName, false));
            requiredDataBuilder.put(digest, new UploadDataSupplier() {
                @Override//from w w  w . java 2 s  . c o m
                public InputStream get() {
                    return new ByteArrayInputStream(node.data);
                }

                @Override
                public String describe() {
                    return String.format("Serialized java object (size:%s).", node.data.length);
                }
            });

            for (Map.Entry<String, Node> child : node.children.entrySet()) {
                addData(root.resolve(child.getKey()), child.getKey(), child.getValue());
            }
        }
    }

    new DataAdder().addData(Paths.get("__data__").resolve(hash.toString()), hash.toString(),
            Objects.requireNonNull(nodeMap.get(hash)));

    return nodeCache.createNode(fileNodes, ImmutableMap.of());
}