01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2002,2008 Oracle. All rights reserved.
05: *
06: * $Id: PersistKeyBinding.java,v 1.17.2.4 2008/01/07 15:14:20 cwl Exp $
07: */
08:
09: package com.sleepycat.persist.impl;
10:
11: import com.sleepycat.bind.EntryBinding;
12: import com.sleepycat.bind.tuple.TupleBase;
13: import com.sleepycat.je.DatabaseEntry;
14:
15: /**
16: * A persistence key binding for a given key class.
17: *
18: * @author Mark Hayes
19: */
20: public class PersistKeyBinding implements EntryBinding {
21:
22: Catalog catalog;
23: Format keyFormat;
24: boolean rawAccess;
25:
26: /**
27: * Creates a key binding for a given key class.
28: */
29: public PersistKeyBinding(Catalog catalog, String clsName,
30: boolean rawAccess) {
31: this .catalog = catalog;
32: keyFormat = catalog.getFormat(clsName);
33: if (keyFormat == null) {
34: throw new IllegalArgumentException(
35: "Class is not persistent: " + clsName);
36: }
37: if (!keyFormat.isSimple()
38: && (keyFormat.getClassMetadata() == null || keyFormat
39: .getClassMetadata().getCompositeKeyFields() == null)) {
40: throw new IllegalArgumentException(
41: "Key class is not a simple type or a composite key class "
42: + "(composite keys must include @KeyField annotations): "
43: + clsName);
44: }
45: this .rawAccess = rawAccess;
46: }
47:
48: /**
49: * Creates a key binding dynamically for use by PersistComparator. Formats
50: * are created from scratch rather than using a shared catalog.
51: */
52: PersistKeyBinding(Class cls, String[] compositeFieldOrder) {
53: catalog = SimpleCatalog.getInstance();
54: if (compositeFieldOrder != null) {
55: assert !SimpleCatalog.isSimpleType(cls);
56: keyFormat = new CompositeKeyFormat(cls, null,
57: compositeFieldOrder);
58: } else {
59: assert SimpleCatalog.isSimpleType(cls);
60: keyFormat = catalog.getFormat(cls);
61: }
62: keyFormat.initializeIfNeeded(catalog);
63: }
64:
65: /**
66: * Binds bytes to an object for use by PersistComparator as well as
67: * entryToObject.
68: */
69: Object bytesToObject(byte[] bytes, int offset, int length) {
70: return readKey(keyFormat, catalog, bytes, offset, length,
71: rawAccess);
72: }
73:
74: /**
75: * Binds bytes to an object for use by PersistComparator as well as
76: * entryToObject.
77: */
78: static Object readKey(Format keyFormat, Catalog catalog,
79: byte[] bytes, int offset, int length, boolean rawAccess) {
80: EntityInput input = new RecordInput(catalog, rawAccess, null,
81: 0, bytes, offset, length);
82: return input.readKeyObject(keyFormat);
83: }
84:
85: public Object entryToObject(DatabaseEntry entry) {
86: return bytesToObject(entry.getData(), entry.getOffset(), entry
87: .getSize());
88: }
89:
90: public void objectToEntry(Object object, DatabaseEntry entry) {
91: RecordOutput output = new RecordOutput(catalog, rawAccess);
92: output.writeKeyObject(object, keyFormat);
93: TupleBase.outputToEntry(output, entry);
94: }
95: }
|