Example usage for com.google.common.hash HashingInputStream hash

List of usage examples for com.google.common.hash HashingInputStream hash

Introduction

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

Prototype

@CheckReturnValue
public HashCode hash() 

Source Link

Document

Returns the HashCode based on the data read from this stream.

Usage

From source file:org.jclouds.io.ByteStreams2.java

public static HashCode hashAndClose(InputStream input, HashFunction hashFunction) throws IOException {
    checkNotNull(input, "input");
    checkNotNull(hashFunction, "hashFunction");
    try {//from w w w  .j  a  v  a  2 s  .c  o  m
        HashingInputStream his = new HashingInputStream(hashFunction, input);
        ByteStreams.copy(his, ByteStreams.nullOutputStream());
        return his.hash();
    } finally {
        closeQuietly(input);
    }
}

From source file:org.jclouds.glacier.util.TreeHash.java

/**
 * Builds the Hash and the TreeHash values of the payload.
 *
 * @return The calculated TreeHash./*from   w w  w . j a  v  a2  s.com*/
 * @see <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html" />
 */
public static TreeHash buildTreeHashFromPayload(Payload payload) throws IOException {
    InputStream is = null;
    try {
        is = checkNotNull(payload, "payload").openStream();
        Builder<HashCode> list = ImmutableList.builder();
        HashingInputStream linearHis = new HashingInputStream(Hashing.sha256(), is);
        while (true) {
            HashingInputStream chunkedHis = new HashingInputStream(Hashing.sha256(),
                    ByteStreams.limit(linearHis, CHUNK_SIZE));
            long count = ByteStreams.copy(chunkedHis, ByteStreams.nullOutputStream());
            if (count == 0) {
                break;
            }
            list.add(chunkedHis.hash());
        }
        //The result list contains exactly one element now.
        return new TreeHash(hashList(list.build()), linearHis.hash());
    } finally {
        closeQuietly(is);
    }
}

From source file:org.jclouds.glacier.util.AWSRequestSignerV4.java

private static HashCode buildHashedPayload(HttpRequest request) {
    HashingInputStream his = null;
    try {/*w  w  w. j  av  a 2  s .c  o m*/
        his = new HashingInputStream(Hashing.sha256(),
                request.getPayload() == null ? ByteSource.empty().openStream()
                        : request.getPayload().openStream());
        ByteStreams.copy(his, ByteStreams.nullOutputStream());
        return his.hash();
    } catch (IOException e) {
        throw new HttpException("Error signing request", e);
    } finally {
        closeQuietly(his);
    }
}

From source file:org.jclouds.s3.filters.Aws4SignerBase.java

/**
 * hash input with sha256/* www .jav  a  2s .  c  o m*/
 *
 * @param input
 * @return hash result
 * @throws HTTPException
 */
public static byte[] hash(InputStream input) throws HTTPException {
    HashingInputStream his = new HashingInputStream(Hashing.sha256(), input);
    try {
        ByteStreams.copy(his, ByteStreams.nullOutputStream());
        return his.hash().asBytes();
    } catch (IOException e) {
        throw new HttpException("Unable to compute hash while signing request: " + e.getMessage(), e);
    }
}

From source file:org.swiftexplorer.util.FileUtils.java

public static String readAllAndgetMD5(InputStream in) throws IOException {
    com.google.common.hash.HashingInputStream his = null;
    try {/*from w  w  w .j  a  v  a2  s. com*/
        his = new com.google.common.hash.HashingInputStream(Hashing.md5(), in);

        final int bufferSize = 2097152;
        final ReadableByteChannel inputChannel = Channels.newChannel(his);
        final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
        while (inputChannel.read(buffer) != -1) {
            buffer.clear();
        }
        /*
        byte[] bytesBuffer = new byte[bufferSize] ;
        int r = his.read(bytesBuffer, 0, bufferSize) ;
        while (r != -1)
           r = his.read(bytesBuffer) ;
        */
        HashCode hc = his.hash();
        return (hc != null) ? (hc.toString()) : (null);
    } finally {
        if (his != null)
            his.close();
    }
}

From source file:com.lithium.flow.util.HashEncoder.java

@Nonnull
public String process(@Nonnull InputStream in) throws IOException {
    checkNotNull(in);// w w w .jav  a2 s  .  c o  m
    try {
        HashingInputStream hashIn = new HashingInputStream(function, in);
        IOUtils.copy(hashIn, ByteStreams.nullOutputStream());
        return encoding.encode(hashIn.hash().asBytes());
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.jclouds.jdbc.service.JdbcService.java

@Transactional(rollbackOn = IOException.class)
public BlobEntity createOrModifyBlob(String containerName, Blob blob, BlobAccess blobAccess)
        throws IOException {
    List<Long> chunks;
    HashingInputStream his = new HashingInputStream(Hashing.md5(), blob.getPayload().openStream());
    try {/* ww  w.  j a v  a 2  s.  c  o  m*/
        chunks = storeData(his);
    } finally {
        Closeables2.closeQuietly(his);
    }
    HashCode actualHashCode = his.hash();
    HashCode expectedHashCode = blob.getPayload().getContentMetadata().getContentMD5AsHashCode();
    if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) {
        throw new IOException(
                "MD5 hash code mismatch, actual: " + actualHashCode + " expected: " + expectedHashCode);
    }

    String key = blob.getMetadata().getName();
    Date creationDate = null;
    BlobEntity oldBlobEntity = findBlobById(containerName, key);
    if (oldBlobEntity != null) {
        creationDate = oldBlobEntity.getCreationDate();
    }
    BlobEntity blobEntity = blobToBlobEntity.apply(blob);
    blobEntity.getPayload().setChunks(chunks);
    blobEntity.setContainerEntity(containerRepository.findContainerByName(containerName));
    blobEntity.setKey(key);
    blobEntity.setBlobAccess(blobAccess);
    blobEntity.setTier(blob.getMetadata().getTier());
    blobEntity.setCreationDate(creationDate);
    blobEntity.setLastModified(new Date());
    blobEntity.setEtag(base16().lowerCase().encode(actualHashCode.asBytes()));
    blobEntity.getPayload().setContentMD5(actualHashCode.asBytes());

    BlobEntity result = blobRepository.save(blobEntity);
    return result;
}

From source file:org.apache.james.blob.objectstorage.ObjectStorageBlobsDAO.java

private CompletableFuture<BlobId> save(InputStream data, BlobId id) {
    String containerName = this.containerName.value();
    HashingInputStream hashingInputStream = new HashingInputStream(Hashing.sha256(), data);
    Payload payload = payloadCodec.write(hashingInputStream);
    Blob blob = blobStore.blobBuilder(id.asString()).payload(payload).build();

    return CompletableFuture.supplyAsync(() -> blobStore.putBlob(containerName, blob), executor)
            .thenApply(any -> blobIdFactory.from(hashingInputStream.hash().toString()));
}

From source file:org.openscoring.service.ModelRegistry.java

@SuppressWarnings(value = { "resource" })
public Model load(InputStream is) throws Exception {
    CountingInputStream countingIs = new CountingInputStream(is);

    HashingInputStream hashingIs = new HashingInputStream(Hashing.md5(), countingIs);

    ModelEvaluator<?> evaluator = unmarshal(hashingIs, this.validate);

    PMML pmml = evaluator.getPMML();//from ww w  . j  a va2s.  c  o m

    for (Class<? extends Visitor> visitorClazz : this.visitorClazzes) {
        Visitor visitor = visitorClazz.newInstance();

        visitor.applyTo(pmml);
    }

    evaluator.verify();

    Model model = new Model(evaluator);
    model.putProperty(Model.PROPERTY_FILE_SIZE, countingIs.getCount());
    model.putProperty(Model.PROPERTY_FILE_MD5SUM, (hashingIs.hash()).toString());

    return model;
}

From source file:org.haiku.haikudepotserver.pkg.job.PkgScreenshotImportArchiveJobRunner.java

/**
 * <p>Goes through the archive and captures information about each screenshot.</p>
 *///from w w w  . ja v a  2  s . c  o m

private void collectScreenshotMetadataFromArchive(Map<String, ScreenshotImportMetadatas> data,
        ArchiveInputStream archiveInputStream, ArchiveEntry archiveEntry, String pkgName, int order) {

    ScreenshotImportMetadatas metadatas = data.get(pkgName);

    if (null == metadatas) {
        metadatas = new ScreenshotImportMetadatas();
        ObjectContext context = serverRuntime.newContext();
        Optional<Pkg> pkgOptional = Pkg.tryGetByName(context, pkgName);

        if (!pkgOptional.isPresent()) {
            metadatas.setNotFound();
        }

        data.put(pkgName, metadatas);
    }

    if (!metadatas.isNotFound()) {
        HashingInputStream hashingInputStream = new HashingInputStream(HASH_FUNCTION, archiveInputStream);

        try {
            ByteStreams.copy(hashingInputStream, ByteStreams.nullOutputStream());
        } catch (IOException ioe) {
            throw new UncheckedIOException(ioe);
        }

        metadatas.add(new FromArchiveScreenshotMetadata(order, archiveEntry.getSize(),
                hashingInputStream.hash(), archiveEntry.getName()));
    }
}