Java Code Examples for com.google.common.io.Files#hash()

The following examples show how to use com.google.common.io.Files#hash() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MapDefinition.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public boolean shouldReload() {
    if(context == null) return true;
    if(!configuration.autoReload()) return false;
    if(context.loadedFiles().isEmpty()) return configuration.reloadWhenError();

    try {
        for(Map.Entry<Path, HashCode> loaded : context.loadedFiles().entrySet()) {
            HashCode latest = Files.hash(loaded.getKey().toFile(), Hashing.sha256());
            if(!latest.equals(loaded.getValue())) return true;
        }

        return false;
    } catch (IOException e) {
        return true;
    }
}
 
Example 2
Source File: ConcreteOneDownloadIntegrationTest.java    From OneDriveJavaSDK with MIT License 6 votes vote down vote up
@Test
   public void simpleDownloadTest() throws InstantiationException,
           IllegalAccessException, IllegalArgumentException,
		InvocationTargetException, NoSuchFieldException, SecurityException, OneDriveException, IOException, InterruptedException {
	OneDriveSDK api = TestSDKFactory.getInstance();

	OneFolder folder = api.getFolderByPath("/IntegrationTesting/FolderForDownload");
	List<OneFile> files = folder.getChildFiles();


	for (OneFile file : files){
		File localCopy = File.createTempFile(file.getName(), ".bin");

		OneDownloadFile f = file.download(localCopy);
		f.startDownload();

		HashCode code = Files.hash(localCopy, Hashing.sha1());
           assertEquals(file.getName() + " mismatch", code.toString().toUpperCase(), file.getSHA1Hash());
       }
}
 
Example 3
Source File: PreProcessCache.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private static HashCode getHash(@NonNull File file) {
    try {
        return Files.hash(file, Hashing.sha1());
    } catch (IOException ignored) {
    }

    return null;
}
 
Example 4
Source File: Tools.java    From torrenttunes-client with GNU General Public License v3.0 5 votes vote down vote up
public static String sha2FileChecksum(File file) {
	HashCode hc = null;
	try {
		hc = Files.hash(file, Hashing.sha256());
	} catch (IOException e) {
		e.printStackTrace();
	}
	return hc.toString();
}
 
Example 5
Source File: SystemUtils.java    From Raigad with Apache License 2.0 5 votes vote down vote up
/**
 * Get a Md5 string which is similar to OS Md5sum
 */
public static String md5(File file) {
    try {
        HashCode hc = Files.hash(file, Hashing.md5());
        return toHex(hc.asBytes());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: PreProcessCache.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
protected Node createItemNode(
        @NonNull Document document,
        @NonNull T itemKey,
        @NonNull BaseItem item) throws IOException {
    if (!item.areOutputFilesPresent()) {
        return null;
    }

    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;
}
 
Example 7
Source File: TestPropertiesMojoTest.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
private HashCode sha1(File basedir, String path) throws IOException {
  return Files.hash(new File(basedir, path), Hashing.sha1());
}
 
Example 8
Source File: S3Dispatcher.java    From s3ninja with MIT License 4 votes vote down vote up
/**
 * Handles GET /bucket/id with an <tt>x-amz-copy-source</tt> header.
 *
 * @param ctx    the context describing the current request
 * @param bucket the bucket containing the object to use as destination
 * @param id     name of the object to use as destination
 */
private void copyObject(WebContext ctx, Bucket bucket, String id, String copy) throws IOException {
    StoredObject object = bucket.getObject(id);
    if (!copy.contains(PATH_DELIMITER)) {
        signalObjectError(ctx,
                          null,
                          null,
                          S3ErrorCode.InvalidRequest,
                          String.format("Source '%s' must contain '/'", copy));
        return;
    }
    String srcBucketName = copy.substring(1, copy.lastIndexOf(PATH_DELIMITER));
    String srcId = copy.substring(copy.lastIndexOf(PATH_DELIMITER) + 1);
    Bucket srcBucket = storage.getBucket(srcBucketName);
    if (!srcBucket.exists()) {
        signalObjectError(ctx,
                          srcBucketName,
                          srcId,
                          S3ErrorCode.NoSuchBucket,
                          String.format("Source bucket '%s' does not exist", srcBucketName));
        return;
    }
    StoredObject src = srcBucket.getObject(srcId);
    if (!src.exists()) {
        signalObjectError(ctx,
                          srcBucketName,
                          srcId,
                          S3ErrorCode.NoSuchKey,
                          String.format("Source object '%s/%s' does not exist", srcBucketName, srcId));
        return;
    }
    Files.copy(src.getFile(), object.getFile());
    if (src.getPropertiesFile().exists()) {
        Files.copy(src.getPropertiesFile(), object.getPropertiesFile());
    }
    HashCode hash = Files.hash(object.getFile(), Hashing.md5());
    String etag = BaseEncoding.base16().encode(hash.asBytes()).toLowerCase();

    XMLStructuredOutput structuredOutput = ctx.respondWith().addHeader(HTTP_HEADER_NAME_ETAG, etag(etag)).xml();
    structuredOutput.beginOutput("CopyObjectResult");
    structuredOutput.beginObject("LastModified");
    structuredOutput.text(ISO8601_INSTANT.format(object.getLastModifiedInstant()));
    structuredOutput.endObject();
    structuredOutput.beginObject(HTTP_HEADER_NAME_ETAG);
    structuredOutput.text(etag(etag));
    structuredOutput.endObject();
    structuredOutput.endOutput();
    signalObjectSuccess(ctx);
}
 
Example 9
Source File: ConcreteOneDriveSDKTest.java    From OneDriveJavaSDK with MIT License 3 votes vote down vote up
@Test
public void uploadBigFile() throws IOException, OneDriveException, NoSuchAlgorithmException, InterruptedException {
    OneDriveSDK api = this.connect();

    int fileLength = 10000;
    String fileName = "src/test/resources/uploadTest.big";
    String targetPath = "/IntegrationTesting/FolderForUploads";
    String downloadDestination = "src/test/resources/uploadTest_download.big";

    File localFile = new File(fileName);
    File destinationFile = new File(downloadDestination);

    this.generateFile(fileName, fileLength);

    HashCode sourceHash = Files.hash(localFile, Hashing.sha1());

    OneFolder targetFolder = api.getFolderByPath(targetPath);
    final OneUploadFile upload = targetFolder.uploadFile(localFile);

    upload.startUpload();

    Thread.sleep(2000);

    OneFile remoteFile = api.getFileByPath("/IntegrationTesting/FolderForUploads/" + localFile.getName());
    Assert.assertEquals(sourceHash.toString().toUpperCase(), remoteFile.getSHA1Hash());

    OneDownloadFile downloadedFile = remoteFile.download(destinationFile);
    downloadedFile.startDownload();

    HashCode downloadedHash = Files.hash(destinationFile, Hashing.sha1());

    if (!localFile.delete())
        System.err.println("Local file could not be deleted.");

    if (!destinationFile.delete())
        System.err.println("Downloaded file could not be deleted.");

    Assert.assertEquals(sourceHash.toString().toUpperCase(), downloadedHash.toString().toUpperCase());
}
 
Example 10
Source File: PreDex.java    From javaide with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Returns the hash of a file.
 *
 * @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();
}