01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2002,2008 Oracle. All rights reserved.
05: *
06: * $Id: ChecksumValidator.java,v 1.31.2.3 2008/01/07 15:14:13 cwl Exp $
07: */
08:
09: package com.sleepycat.je.log;
10:
11: import java.nio.ByteBuffer;
12: import java.util.zip.Checksum;
13:
14: import com.sleepycat.je.dbi.EnvironmentImpl;
15: import com.sleepycat.je.utilint.Adler32;
16: import com.sleepycat.je.utilint.DbLsn;
17:
18: /**
19: * Checksum validator is used to check checksums on log entries.
20: */
21: class ChecksumValidator {
22: private static final boolean DEBUG = false;
23:
24: private Checksum cksum;
25:
26: ChecksumValidator() {
27: cksum = Adler32.makeChecksum();
28: }
29:
30: void reset() {
31: cksum.reset();
32: }
33:
34: /**
35: * Add this byte buffer to the checksum. Assume the byte buffer is already
36: * positioned at the data.
37: * @param buf target buffer
38: * @param length of data
39: */
40: void update(EnvironmentImpl env, ByteBuffer buf, int length,
41: boolean anticipateChecksumErrors)
42: throws DbChecksumException {
43:
44: if (buf == null) {
45: throw new DbChecksumException(
46: (anticipateChecksumErrors ? null : env),
47: "null buffer given to checksum validation, probably "
48: + " result of 0's in log file. "
49: + anticipateChecksumErrors);
50: }
51:
52: int bufStart = buf.position();
53:
54: if (DEBUG) {
55: System.out.println("bufStart = " + bufStart + " length = "
56: + length);
57: }
58:
59: if (buf.hasArray()) {
60: cksum.update(buf.array(), bufStart, length);
61: } else {
62: for (int i = bufStart; i < (length + bufStart); i++) {
63: cksum.update(buf.get(i));
64: }
65: }
66: }
67:
68: void validate(EnvironmentImpl env, long expectedChecksum, long lsn)
69: throws DbChecksumException {
70:
71: if (expectedChecksum != cksum.getValue()) {
72: throw new DbChecksumException(env, "Location "
73: + DbLsn.getNoFormatString(lsn) + " expected "
74: + expectedChecksum + " got " + cksum.getValue());
75: }
76: }
77:
78: void validate(EnvironmentImpl env, long expectedChecksum,
79: long fileNum, long fileOffset,
80: boolean anticipateChecksumErrors)
81: throws DbChecksumException {
82:
83: if (expectedChecksum != cksum.getValue()) {
84: long problemLsn = DbLsn.makeLsn(fileNum, fileOffset);
85:
86: /*
87: * Pass null for env so that RunRecoveryException() does not
88: * invalidate the environment.
89: */
90: throw new DbChecksumException(
91: (anticipateChecksumErrors ? null : env),
92: "Location " + DbLsn.getNoFormatString(problemLsn)
93: + " expected " + expectedChecksum + " got "
94: + cksum.getValue());
95: }
96: }
97: }
|