public static FileCache create(File dir, Logger logger) { return new FileCache(dir, new FileHashes(), logger); }
/** * Computes the hash of given stream. The stream is closed by this method. */ public String of(InputStream input) { try(InputStream is = input) { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] hash = digest(is, digest); return toHex(hash); } catch (Exception e) { throw new IllegalStateException("Fail to compute hash", e); } }
public String of(File file) { try { return of(new FileInputStream(file)); } catch (IOException e) { throw new IllegalStateException("Fail to compute hash of: " + file.getAbsolutePath(), e); } }
private void cacheMiss(File targetFile, String expectedHash, Downloader downloader) { File tempFile = newTempFile(); download(downloader, targetFile.getName(), tempFile); String downloadedHash = hashes.of(tempFile); if (!expectedHash.equals(downloadedHash)) { throw new IllegalStateException("INVALID HASH: File " + tempFile.getAbsolutePath() + " was expected to have hash " + expectedHash + " but was downloaded with hash " + downloadedHash); } mkdirQuietly(targetFile.getParentFile()); renameQuietly(tempFile, targetFile); }