01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2002,2008 Oracle. All rights reserved.
05: *
06: * $Id: PersistComparator.java,v 1.8.2.2 2008/01/07 15:14:20 cwl Exp $
07: */
08:
09: package com.sleepycat.persist.impl;
10:
11: import java.io.Serializable;
12: import java.util.Comparator;
13: import java.util.List;
14:
15: import com.sleepycat.persist.model.FieldMetadata;
16:
17: /**
18: * The btree comparator for persistent key classes. The serialized form of
19: * this comparator is stored in the BDB JE database descriptor so that the
20: * comparator can be re-created during recovery.
21: *
22: * @author Mark Hayes
23: */
24: public class PersistComparator implements Comparator<Object>,
25: Serializable {
26:
27: private static final long serialVersionUID = 5221576538843355317L;
28:
29: private String keyClassName;
30: private String[] comositeFieldOrder;
31: private transient PersistKeyBinding binding;
32:
33: public PersistComparator(String keyClassName,
34: List<FieldMetadata> compositeKeyFields,
35: PersistKeyBinding binding) {
36: this .keyClassName = keyClassName;
37: this .binding = binding;
38:
39: if (compositeKeyFields != null) {
40: comositeFieldOrder = CompositeKeyFormat
41: .getFieldNameArray(compositeKeyFields);
42: }
43: }
44:
45: public int compare(Object o1, Object o2) {
46:
47: /*
48: * The binding will be null after the comparator is deserialized, i.e.,
49: * during BDB JE recovery. We must construct it here, without access
50: * to the stored catalog since recovery is not complete.
51: */
52: if (binding == null) {
53: Class keyClass;
54: try {
55: keyClass = SimpleCatalog.classForName(keyClassName);
56: } catch (ClassNotFoundException e) {
57: throw new IllegalStateException(e);
58: }
59: binding = new PersistKeyBinding(keyClass,
60: comositeFieldOrder);
61: }
62:
63: byte[] b1 = (byte[]) o1;
64: byte[] b2 = (byte[]) o2;
65:
66: Comparable k1 = (Comparable) binding.bytesToObject(b1, 0,
67: b1.length);
68: Comparable k2 = (Comparable) binding.bytesToObject(b2, 0,
69: b2.length);
70:
71: return k1.compareTo(k2);
72: }
73: }
|