1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
public class FileComparator
{
// Singleton instance
protected static FileComparator instance = null;
private static FileComparator getInstance() throws NoSuchAlgorithmException
{
if(instance==null)
instance = new FileComparator();
return instance;
}
public static String calculateChecksum(File file) throws IOException, NoSuchAlgorithmException
{
return getInstance().compute(file);
}
public static String getEncoding() throws NoSuchAlgorithmException
{
return getInstance().getChecksum().getEncoding();
}
public static String getMethod() throws NoSuchAlgorithmException
{
return getInstance().getChecksum().getName();
}
// File comparator logic
protected AbstractChecksum checksum;
private FileComparator() throws NoSuchAlgorithmException
{
// TODO set theses values from configuration settings
String method = "md5";
String encoding = AbstractChecksum.HEX;
// Initialize the checksum
try
{
checksum = JacksumAPI.getChecksumInstance(method);
checksum.setEncoding(encoding);
}
catch (NoSuchAlgorithmException e)
{
logger.error("Unable to initialize the file comparator tool", e);
throw e;
}
}
private AbstractChecksum getChecksum()
{
return checksum;
}
private String compute(File file) throws IOException
{
getChecksum().reset();
getChecksum().readFile(file.getAbsolutePath());
return getChecksum().format("#CHECKSUM");
}
@Test
public void test()
{
File file_1 = null;
File file_2 = null;
try
{
file_1 = File.createTempFile("ads_test"/*prefix*/, ".txt"/*suffix*/);
file_2 = File.createTempFile("ads_test"/*prefix*/, ".txt"/*suffix*/);
// Input data the files
String fileContent = "blabla &$& ";
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file_1));
out.write(fileContent);
out.close();
out = new BufferedWriter(new FileWriter(file_2));
out.write(fileContent);
out.close();
} catch (IOException e) {
e.printStackTrace();
Assert.fail("Unable to init file data");
}
Assert.assertTrue(FileComparator.calculateChecksum(file_1).equals(FileComparator.calculateChecksum(file_2)));
Assert.assertTrue(file_1.length()==file_2.length());
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file_2, true));
out.write(fileContent);
out.close();
} catch (IOException e) {
e.printStackTrace();
Assert.fail("Unable to init file data");
}
Assert.assertFalse(FileComparator.calculateChecksum(file_1).equals(FileComparator.calculateChecksum(file_2)));
Assert.assertFalse(file_1.length()==file_2.length());
}
catch(Exception ex )
{
ex.printStackTrace();
Assert.fail("Exception during JUnit run.");
}
finally
{
if(file_1!=null)
file_1.deleteOnExit();
if(file_2!=null)
file_2.deleteOnExit();
}
}
} |
Partager