00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 package com.sleepycat.bind.serial;
00011
00012 import java.io.IOException;
00013
00014 import com.sleepycat.bind.EntryBinding;
00015 import com.sleepycat.db.DatabaseEntry;
00016 import com.sleepycat.util.FastInputStream;
00017 import com.sleepycat.util.FastOutputStream;
00018 import com.sleepycat.util.RuntimeExceptionWrapper;
00019
00031 public class SerialBinding extends SerialBase implements EntryBinding {
00032
00033 private ClassCatalog classCatalog;
00034 private Class baseClass;
00035
00046 public SerialBinding(ClassCatalog classCatalog, Class baseClass) {
00047
00048 if (classCatalog == null) {
00049 throw new NullPointerException("classCatalog must be non-null");
00050 }
00051 this.classCatalog = classCatalog;
00052 this.baseClass = baseClass;
00053 }
00054
00060 public final Class getBaseClass() {
00061
00062 return baseClass;
00063 }
00064
00082 public ClassLoader getClassLoader() {
00083
00084 return null;
00085 }
00086
00097 public Object entryToObject(DatabaseEntry entry) {
00098
00099 int length = entry.getSize();
00100 byte[] hdr = SerialOutput.getStreamHeader();
00101 byte[] bufWithHeader = new byte[length + hdr.length];
00102
00103 System.arraycopy(hdr, 0, bufWithHeader, 0, hdr.length);
00104 System.arraycopy(entry.getData(), entry.getOffset(),
00105 bufWithHeader, hdr.length, length);
00106
00107 try {
00108 SerialInput jin = new SerialInput(
00109 new FastInputStream(bufWithHeader, 0, bufWithHeader.length),
00110 classCatalog,
00111 getClassLoader());
00112 return jin.readObject();
00113 } catch (IOException e) {
00114 throw new RuntimeExceptionWrapper(e);
00115 } catch (ClassNotFoundException e) {
00116 throw new RuntimeExceptionWrapper(e);
00117 }
00118 }
00119
00137 public void objectToEntry(Object object, DatabaseEntry entry) {
00138
00139 if (baseClass != null && !baseClass.isInstance(object)) {
00140 throw new IllegalArgumentException(
00141 "Data object class (" + object.getClass() +
00142 ") not an instance of binding's base class (" +
00143 baseClass + ')');
00144 }
00145 FastOutputStream fo = getSerialOutput(object);
00146 try {
00147 SerialOutput jos = new SerialOutput(fo, classCatalog);
00148 jos.writeObject(object);
00149 } catch (IOException e) {
00150 throw new RuntimeExceptionWrapper(e);
00151 }
00152
00153 byte[] hdr = SerialOutput.getStreamHeader();
00154 entry.setData(fo.getBufferBytes(), hdr.length,
00155 fo.getBufferLength() - hdr.length);
00156 }
00157 }