Added BAEL-3604 code (#9020)

* Added BAEL-3604 code
This commit is contained in:
Sam Millington
2020-04-08 18:40:34 +01:00
committed by GitHub
parent 5b39f14fc9
commit c66e7c89f7
3 changed files with 85 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
package com.baeldung.checksums;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;
public class ChecksumUtils {
public static long getChecksumCRC32(byte[] bytes) {
Checksum crc32 = new CRC32();
crc32.update(bytes, 0, bytes.length);
return crc32.getValue();
}
public static long getChecksumCRC32(InputStream stream, int bufferSize) throws IOException {
CheckedInputStream checkedInputStream = new CheckedInputStream(stream, new CRC32());
byte[] buffer = new byte[bufferSize];
while (checkedInputStream.read(buffer, 0, buffer.length) >= 0) {}
return checkedInputStream.getChecksum().getValue();
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.checksums;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.*;
class ChecksumUtilsUnitTest {
byte[] arr;
@Before
void setUp() {
arr = new byte[]{0,10,21,20,35,40,120,56,72,22};
}
@Test
void givenByteArray_whenChecksumCreated_checkCorrect() {
long checksum = ChecksumUtils.getChecksumCRC32(arr);
assertEquals(3915397664L, checksum);
}
@Test
void givenTwoDifferentStrings_whenChecksumCreated_checkCollision() {
String plumless = "plumless";
String buckeroo = "buckeroo";
long plumlessChecksum = ChecksumUtils.getChecksumCRC32(plumless.getBytes());
long buckerooChecksum = ChecksumUtils.getChecksumCRC32(buckeroo.getBytes());
assertEquals(plumlessChecksum, buckerooChecksum);
}
@Test
void givenInputString_whenChecksumCreated_checkCorrect() throws IOException {
InputStream inputStream = new ByteArrayInputStream(arr);
long checksum = ChecksumUtils.getChecksumCRC32(inputStream, 10);
assertEquals(3915397664L, checksum);
}
}