summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/crcchecker/CRCChecker.java
blob: b7f288eb77d2a8bcc98510f0894ee57947bdbf3d (plain) (blame)
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
package org.openslx.imagemaster.crcchecker;

import java.io.IOException;
import java.util.zip.CRC32;

public class CRCChecker
{
	private static final int blockSize = 16 * 1024 * 1024;

	private ImageFile imageFile;
	private CRCFile crcFile;

	private byte[] block = new byte[ blockSize ];	// array that is used to read the blocks

	/**
	 * Initialize a crc checker with an image file and a crc file.
	 * 
	 * @param imageFile The image file to check
	 * @param crcFile The crc file to check against
	 */
	public CRCChecker( String imageFilename, String crcFilename )
	{
		this.imageFile = new ImageFile( imageFilename, blockSize );
	}

	public void done()
	{
		imageFile.close();
	}

	public boolean hasValidCrcFile()
	{
		try {
			return crcFile.isValid();
		} catch ( IOException e ) {
			return false;
		}
	}

	/**
	 * Checks a chosen block against the crc file.
	 * 
	 * @param block The block to check
	 * @return Whether the block was valid or not
	 * @throws IOException When image or crc file could not be read.
	 */
	public boolean checkBlock( int blockNumber ) throws IOException
	{
		if ( !this.hasValidCrcFile() )
			return false;

		int length;
		try {
			length = imageFile.getBlock( blockNumber, block );
		} catch ( IOException e ) {
			throw new IOException( "Could not read image file", e );
		}

		if ( length <= 0 )
			return false;

		CRC32 crcCalc = new CRC32();
		if ( length == blockSize ) {
			crcCalc.update( block );
		} else {
			crcCalc.update( block, 0, length );
		}

		int crcSum = Integer.reverseBytes( (int)crcCalc.getValue() );
		int crcSumFromFile;
		try {
			crcSumFromFile = crcFile.getCRCSum( blockNumber );
		} catch ( IOException e ) {
			throw new IOException( "Could not read CRC file", e );
		}

		return ( crcSum == crcSumFromFile );
	}
}