Created
June 14, 2016 09:29
-
-
Save jrialland/8c6a1a5885334be2865bee7872bd15fd to your computer and use it in GitHub Desktop.
md5 sum for etags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Computes the md5 sum (or lookups from a .md5 file) for the provided file. | |
| * | |
| * @param f file path | |
| * @return the base64ed md5 sum of the file | |
| * @throws IOException | |
| * @throws NoSuchAlgorithmException | |
| * @throws DecoderException | |
| */ | |
| private String getMd5(Path f) throws IOException, NoSuchAlgorithmException, DecoderException { | |
| String path = f.toString(); | |
| String md5 = md5Sums.get(path); | |
| if(md5 == null) { | |
| Path md5File = Paths.get(path+".md5"); | |
| if(Files.isRegularFile(md5File)) { | |
| md5 = new String(Files.readAllBytes(md5File)).trim(); | |
| md5 = Base64.getEncoder().encodeToString(Hex.decodeHex(md5.toCharArray())); | |
| md5Sums.put(path, md5); | |
| etags.add("\"" + md5 + "\""); | |
| } else { | |
| MessageDigest md = MessageDigest.getInstance("MD5"); | |
| InputStream is = f.toUri().toURL().openStream(); | |
| byte[] buff = new byte[4096]; | |
| int c = 0; | |
| while( (c = is.read(buff)) > -1) { | |
| md.update(buff, 0, c); | |
| } | |
| is.close(); | |
| byte[] md5bytes = md.digest(); | |
| md5 = Base64.getEncoder().encodeToString(md5bytes); | |
| md5Sums.put(path, md5); | |
| etags.add("\"" + md5 + "\""); | |
| Files.write(md5File, new String(Hex.encodeHex(md5bytes)).getBytes(), StandardOpenOption.WRITE); | |
| } | |
| } | |
| return md5; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment