From be08b3ca873dce25a7a05b78eb781aee7d344c70 Mon Sep 17 00:00:00 2001 From: Simon Brandhof Date: Fri, 8 Feb 2013 10:36:07 +0100 Subject: SONAR-2291 fix performance issue when computing file hashes --- .../src/main/java/org/sonar/home/cache/FileHashes.java | 17 +++++++++++++---- .../test/java/org/sonar/home/cache/FileHashesTest.java | 4 +++- 2 files changed, 16 insertions(+), 5 deletions(-) (limited to 'sonar-home') diff --git a/sonar-home/src/main/java/org/sonar/home/cache/FileHashes.java b/sonar-home/src/main/java/org/sonar/home/cache/FileHashes.java index 89a973fd2f4..28066cf5b94 100644 --- a/sonar-home/src/main/java/org/sonar/home/cache/FileHashes.java +++ b/sonar-home/src/main/java/org/sonar/home/cache/FileHashes.java @@ -36,6 +36,8 @@ import java.security.MessageDigest; */ public class FileHashes { + private static final int STREAM_BUFFER_LENGTH = 1024; + public String of(File file) { try { return of(new FileInputStream(file)); @@ -51,10 +53,7 @@ public class FileHashes { DigestInputStream digestInputStream = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); - digestInputStream = new DigestInputStream(input, digest); - while (digestInputStream.read() != -1) { - } - byte[] hash = digest.digest(); + byte[] hash = digest(input, digest); return toHex(hash); } catch (Exception e) { @@ -66,6 +65,16 @@ public class FileHashes { } } + private byte[] digest(InputStream input, MessageDigest digest) throws IOException { + final byte[] buffer = new byte[STREAM_BUFFER_LENGTH]; + int read = input.read(buffer, 0, STREAM_BUFFER_LENGTH); + while (read > -1) { + digest.update(buffer, 0, read); + read = input.read(buffer, 0, STREAM_BUFFER_LENGTH); + } + return digest.digest(); + } + static String toHex(byte[] bytes) { BigInteger bi = new BigInteger(1, bytes); return String.format("%0" + (bytes.length << 1) + "X", bi); diff --git a/sonar-home/src/test/java/org/sonar/home/cache/FileHashesTest.java b/sonar-home/src/test/java/org/sonar/home/cache/FileHashesTest.java index 08f7227f49c..ff6c01c7a3e 100644 --- a/sonar-home/src/test/java/org/sonar/home/cache/FileHashesTest.java +++ b/sonar-home/src/test/java/org/sonar/home/cache/FileHashesTest.java @@ -33,6 +33,8 @@ import java.math.BigInteger; import java.security.SecureRandom; import static org.fest.assertions.Assertions.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -84,7 +86,7 @@ public class FileHashesTest { thrown.expectMessage("Fail to compute hash"); InputStream input = mock(InputStream.class); - when(input.read()).thenThrow(new IllegalThreadStateException()); + when(input.read(any(byte[].class), anyInt(), anyInt())).thenThrow(new IllegalThreadStateException()); new FileHashes().of(input); } -- cgit v1.2.3