Example usage for com.google.common.io ByteSource hash

List of usage examples for com.google.common.io ByteSource hash

Introduction

In this page you can find the example usage for com.google.common.io ByteSource hash.

Prototype

public HashCode hash(HashFunction hashFunction) throws IOException 

Source Link

Document

Hashes the contents of this byte source using the given hash function.

Usage

From source file:com.xebialabs.overtherepy.DirectoryDiff.java

/**
 * Calculate an MD5 hash for the given file.
 *
 * @param file for which MD5 should be calculated.
 * @return MD5 hash/*from w w  w .  j ava  2s.  c  o m*/
 * @throws IOException
 */
public static String md5(final OverthereFile file) throws IOException {
    File sourceFile = new File(file.getPath());
    ByteSource source = Files.asByteSource(sourceFile);
    return source.hash(Hashing.md5()).toString();
}

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

/**
 * @return an Optional that will be absent if there was an error.
 *///from ww  w .j a v  a2  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:com.android.builder.signing.SignedJarApkCreator.java

private static void configureStoredEntry(JarEntry entry, File inputFile) throws IOException {
    ByteSource byteSource = Files.asByteSource(inputFile);
    long size = inputFile.length();

    entry.setMethod(ZipEntry.STORED);
    entry.setSize(size);/*from  www  .j  a  va2s .  c  om*/
    entry.setCompressedSize(size);
    entry.setCrc(byteSource.hash(Hashing.crc32()).padToLong());
}

From source file:net.derquinse.bocas.BocasHashFunction.java

/** Constructor. */
private BocasHashFunction(final HashFunction f) {
    checkNotNull(f);//from  w ww  . ja  v a 2  s.co m
    this.cache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).weakKeys()
            .build(new CacheLoader<ByteSource, ByteString>() {
                public ByteString load(ByteSource key) throws Exception {
                    HashCode h = key.hash(f);
                    return ByteString.copyFrom(h);
                }
            });
}

From source file:com.xebialabs.overtherepy.DirectoryDiff.java

private HashCode hash(final OverthereFile file, HashFunction hashFunction) throws IOException {
    File sourceFile = new File(file.getPath());
    ByteSource source = Files.asByteSource(sourceFile);
    return source.hash(hashFunction);
}

From source file:org.jclouds.karaf.commands.blobstore.BlobWriteCommand.java

@Override
protected Object doExecute() throws Exception {
    BlobStore blobStore = getBlobStore();

    BlobBuilder builder = blobStore.blobBuilder(blobName);
    if (stringPayload) {
        builder = builder.payload(payload.getBytes()); // use default Charset
    } else if (urlPayload) {
        InputStream input = new URL(payload).openStream();
        try {//from  w  w  w . j a v  a 2 s.  com
            builder = builder.payload(ByteStreams.toByteArray(input));
        } finally {
            input.close();
        }
    } else {
        ByteSource byteSource = Files.asByteSource(new File(payload));
        BlobBuilder.PayloadBlobBuilder payloadBuilder = builder.payload(byteSource)
                .contentLength(byteSource.size());
        if (!multipartUpload) {
            payloadBuilder = payloadBuilder.contentMD5(byteSource.hash(Hashing.md5()).asBytes());
        }
        builder = payloadBuilder;
    }

    PutOptions options = multipartUpload ? new PutOptions().multipart(true) : PutOptions.NONE;

    write(blobStore, containerName, blobName, builder.build(), options, signedRequest);

    cacheProvider.getProviderCacheForType("container").put(blobStore.getContext().unwrap().getId(),
            containerName);
    cacheProvider.getProviderCacheForType("blob").put(blobStore.getContext().unwrap().getId(), blobName);

    return null;
}

From source file:com.facebook.buck.io.DefaultProjectFilesystemDelegate.java

@Override
public Sha1HashCode computeSha1(Path pathRelativeToProjectRootOrJustAbsolute) throws IOException {
    final Path fileToHash = getPathForRelativePath(pathRelativeToProjectRootOrJustAbsolute);

    // Normally, we would just use `Files.hash(fileToHash.toFile(), Hashing.sha1())`, but if
    // fileToHash is backed by Jimfs, its toFile() method throws an UnsupportedOperationException.
    // Creating the input stream via java.nio.file.Files.newInputStream() avoids this issue.
    ByteSource source = new ByteSource() {
        @Override/*from ww  w . j a va  2s  .c  o  m*/
        public InputStream openStream() throws IOException {
            // No need to wrap with BufferedInputStream because ByteSource uses ByteStreams.copy(),
            // which already buffers.
            return Files.newInputStream(fileToHash);
        }
    };
    HashCode hashCode = source.hash(Hashing.sha1());
    return Sha1HashCode.fromHashCode(hashCode);
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemDelegate.java

@Override
public Sha1HashCode computeSha1(Path pathRelativeToProjectRootOrJustAbsolute) throws IOException {
    Path fileToHash = getPathForRelativePath(pathRelativeToProjectRootOrJustAbsolute);
    try {/*  w  w  w . ja  v a 2s.com*/
        // Normally, we would just use `Files.hash(fileToHash.toFile(), Hashing.sha1())`, but if
        // fileToHash is backed by Jimfs, its toFile() method throws an UnsupportedOperationException.
        // Creating the input stream via java.nio.file.Files.newInputStream() avoids this issue.
        ByteSource source = new ByteSource() {
            @Override
            public InputStream openStream() throws IOException {
                // No need to wrap with BufferedInputStream because ByteSource uses
                // ByteStreams.copy(), which already buffers.
                return Files.newInputStream(fileToHash);
            }
        };
        HashCode hashCode = source.hash(Hashing.sha1());

        return Sha1HashCode.fromHashCode(hashCode);

    } catch (IOException e) {
        String msg = String.format("Error computing Sha1 for %s: %s", fileToHash.toString(), e.getMessage());

        throw new IOException(msg, e);
    }
}

From source file:com.pinterest.pinlater.commons.config.ConfigFileWatcher.java

/**
 * Adds a watch on the specified file. The file must exist, otherwise a FileNotFoundException
 * is returned. If the file is deleted after a watch is established, the watcher will log errors
 * but continue to monitor it, and resume watching if it is recreated.
 *
 * @param filePath path to the file to watch.
 * @param onUpdate function to call when a change is detected to the file. The entire contents
 *                 of the file will be passed in to the function. Note that onUpdate will be
 *                 called once before this call completes, which facilities initial load of data.
 *                 This callback is executed synchronously on the watcher thread - it is
 *                 important that the function be non-blocking.
 *///from w  w w.  ja va  2  s.com
public synchronized void addWatch(String filePath, Function<byte[], Void> onUpdate) throws IOException {
    MorePreconditions.checkNotBlank(filePath);
    Preconditions.checkNotNull(onUpdate);

    // Read the file and make the initial onUpdate call.
    File file = new File(filePath);
    ByteSource byteSource = Files.asByteSource(file);
    onUpdate.apply(byteSource.read());

    // Add the file to our map if it isn't already there, and register the new change watcher.
    ConfigFileInfo configFileInfo = watchedFileMap.get(filePath);
    if (configFileInfo == null) {
        configFileInfo = new ConfigFileInfo(file.lastModified(), byteSource.hash(HASH_FUNCTION));
        watchedFileMap.put(filePath, configFileInfo);
    }
    configFileInfo.changeWatchers.add(onUpdate);
}

From source file:org.obiba.mica.study.service.StudyPackageImportServiceImpl.java

private void saveTempFile(Attachment attachment, ByteSource content) throws IOException {
    TempFile tempFile = new TempFile();
    tempFile.setId(attachment.getId());/*from   www  .  j  a  v  a  2s  .  c o  m*/
    tempFile.setName(attachment.getName());
    tempFileService.addTempFile(tempFile, content.openStream());
    attachment.setMd5(content.hash(Hashing.md5()).toString());
    attachment.setSize(content.size());
}