summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java')
-rw-r--r--src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java77
1 files changed, 77 insertions, 0 deletions
diff --git a/src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java b/src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java
new file mode 100644
index 0000000..04f6a22
--- /dev/null
+++ b/src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java
@@ -0,0 +1,77 @@
+package org.openslx.imagemaster.crcchecker;
+
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.zip.CRC32;
+
+import org.apache.log4j.Logger;
+
+
+public class CRCChecker
+{
+
+ private static Logger log = Logger.getLogger( CRCChecker.class );
+
+ /**
+ * Checks the CRC sum of given blocks of a given imageFile against a given crcFile.
+ * @param imageFile The imageFile to check
+ * @param crcFile The crcFile to check against
+ * @param blocks The blocks to check
+ * @return The blocks where the crc was right
+ */
+ public static List<Integer> checkCRC(String imageFile, String crcFile, List<Integer> blocks) throws IOException
+ {
+ List<Integer> result = new LinkedList<>();
+
+ final int blockSize = 16 * 1024 * 1024;
+
+ ImageFile image = new ImageFile( imageFile, blockSize );
+ CRCFile crc = new CRCFile( crcFile );
+
+ log.debug( "Checking image file: '" + imageFile + "' with crc file: '" + crcFile + "'");
+ try {
+ if (!crc.isValid()) return result; // TODO: this needs to be handled in another way
+ } catch (IOException e) {
+ throw new IOException( "Could not read CRC file", e );
+ }
+
+ // file is smaller than one block - no need to check crc yet
+ if (image.length() < blockSize) {
+ return result;
+ }
+ // check all blocks
+ for (Integer blockN : blocks) {
+ byte[] block;
+ try {
+ block = image.getBlock( blockN );
+ } catch ( IOException e ) {
+ throw new IOException( "Could not read image file", e );
+ }
+
+ if (block == null) continue; // some error occured (for example: someone tried to check a block that is not in the file)
+
+ // check this block with CRC32
+ // add this block to result, if check was ok with CRC file
+
+ CRC32 crcCalc = new CRC32();
+ crcCalc.update( block );
+ int crcSum = Integer.reverseBytes( (int) crcCalc.getValue() );
+ log.debug( "Got crc for block '" + blockN + "': '" + crcSum + "'" );
+ int crcSumFromFile;
+ try {
+ crcSumFromFile = crc.getCRCSum( blockN );
+ } catch ( IOException e ) {
+ throw new IOException( "Could not read CRC file", e );
+ }
+ log.debug( "And read crc from file: '" + crcSumFromFile + "'" );
+
+ if (crcSum == crcSumFromFile) result.add( blockN );
+ }
+
+ return result;
+ }
+}