1/*- 2 * See the file LICENSE for redistribution information. 3 * 4 * Copyright (c) 2002,2008 Oracle. All rights reserved. 5 * 6 * $Id: PersistKeyBinding.java,v 1.1 2008/02/07 17:12:27 mark Exp $ 7 */ 8 9package com.sleepycat.persist.impl; 10 11import com.sleepycat.bind.EntryBinding; 12import com.sleepycat.bind.tuple.TupleBase; 13import com.sleepycat.db.DatabaseEntry; 14 15/** 16 * A persistence key binding for a given key class. 17 * 18 * @author Mark Hayes 19 */ 20public 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, 30 String clsName, 31 boolean rawAccess) { 32 this.catalog = catalog; 33 keyFormat = catalog.getFormat(clsName); 34 if (keyFormat == null) { 35 throw new IllegalArgumentException 36 ("Class is not persistent: " + clsName); 37 } 38 if (!keyFormat.isSimple() && 39 (keyFormat.getClassMetadata() == null || 40 keyFormat.getClassMetadata().getCompositeKeyFields() == null)) { 41 throw new IllegalArgumentException 42 ("Key class is not a simple type or a composite key class " + 43 "(composite keys must include @KeyField annotations): " + 44 clsName); 45 } 46 this.rawAccess = rawAccess; 47 } 48 49 /** 50 * Creates a key binding dynamically for use by PersistComparator. Formats 51 * are created from scratch rather than using a shared catalog. 52 */ 53 PersistKeyBinding(Class cls, String[] compositeFieldOrder) { 54 catalog = SimpleCatalog.getInstance(); 55 if (compositeFieldOrder != null) { 56 assert !SimpleCatalog.isSimpleType(cls); 57 keyFormat = new CompositeKeyFormat(cls, null, 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, rawAccess); 71 } 72 73 /** 74 * Binds bytes to an object for use by PersistComparator as well as 75 * entryToObject. 76 */ 77 static Object readKey(Format keyFormat, 78 Catalog catalog, 79 byte[] bytes, 80 int offset, 81 int length, 82 boolean rawAccess) { 83 EntityInput input = new RecordInput 84 (catalog, rawAccess, null, 0, bytes, offset, length); 85 return input.readKeyObject(keyFormat); 86 } 87 88 public Object entryToObject(DatabaseEntry entry) { 89 return bytesToObject 90 (entry.getData(), entry.getOffset(), entry.getSize()); 91 } 92 93 public void objectToEntry(Object object, DatabaseEntry entry) { 94 RecordOutput output = new RecordOutput(catalog, rawAccess); 95 output.writeKeyObject(object, keyFormat); 96 TupleBase.outputToEntry(output, entry); 97 } 98} 99