2 * See the file LICENSE for redistribution information.
4 * Copyright (c) 2002, 2012 Oracle and/or its affiliates. All rights reserved.
8 package com.sleepycat.bind.serial.test;
10 import java.io.ObjectInputStream;
11 import java.io.ObjectOutputStream;
12 import java.io.ObjectStreamClass;
13 import java.util.HashMap;
16 import com.sleepycat.bind.serial.ClassCatalog;
17 import com.sleepycat.bind.tuple.IntegerBinding;
18 import com.sleepycat.compat.DbCompat;
19 import com.sleepycat.db.DatabaseEntry;
20 import com.sleepycat.db.DatabaseException;
21 import com.sleepycat.util.FastInputStream;
22 import com.sleepycat.util.FastOutputStream;
23 import com.sleepycat.util.RuntimeExceptionWrapper;
28 public class TestClassCatalog implements ClassCatalog {
30 private final Map<Integer, ObjectStreamClass> idToDescMap =
31 new HashMap<Integer, ObjectStreamClass>();
32 private final Map<String, Integer> nameToIdMap =
33 new HashMap<String, Integer>();
34 private int nextId = 1;
36 public TestClassCatalog() {
42 public synchronized byte[] getClassID(ObjectStreamClass desc) {
43 String className = desc.getName();
44 Integer intId = nameToIdMap.get(className);
49 idToDescMap.put(intId, desc);
50 nameToIdMap.put(className, intId);
52 DatabaseEntry entry = new DatabaseEntry();
53 IntegerBinding.intToEntry(intId, entry);
54 return entry.getData();
57 public synchronized ObjectStreamClass getClassFormat(byte[] byteId)
58 throws DatabaseException {
60 DatabaseEntry entry = new DatabaseEntry();
61 entry.setData(byteId);
62 int intId = IntegerBinding.entryToInt(entry);
64 ObjectStreamClass desc = (ObjectStreamClass) idToDescMap.get(intId);
66 throw new RuntimeException("classID not found");
70 * Workaround for a Harmony bug that appears on Android. The
71 * ObjectStreamClass is not properly initialized, and using it later
72 * will cause NullPointerException. Serializing it and then
73 * deserializing it causes is to be initialized properly. [#18163]
75 if (DbCompat.isDalvik()) {
77 /* Serialize desc first. */
78 FastOutputStream fo = new FastOutputStream();
79 ObjectOutputStream oos = new ObjectOutputStream(fo);
80 oos.writeObject(desc);
81 byte[] bytes = fo.toByteArray();
82 /* Then deserialize classFormat. */
83 FastInputStream fi = new FastInputStream(bytes);
84 ObjectInputStream ois = new ObjectInputStream(fi);
85 desc = (ObjectStreamClass) ois.readObject();
86 } catch (Exception e) {
87 throw RuntimeExceptionWrapper.wrapIfNeeded(e);
93 public ClassLoader getClassLoader() {