1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.serialization;
17
18 import java.io.EOFException;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.ObjectInputStream;
22 import java.io.ObjectStreamClass;
23 import java.io.StreamCorruptedException;
24
25
26
27
28
29
30
31
32 class CompactObjectInputStream extends ObjectInputStream {
33
34 private final ClassLoader classLoader;
35
36 CompactObjectInputStream(InputStream in) throws IOException {
37 this(in, null);
38 }
39
40 CompactObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
41 super(in);
42 this.classLoader = classLoader;
43 }
44
45 @Override
46 protected void readStreamHeader() throws IOException,
47 StreamCorruptedException {
48 int version = readByte() & 0xFF;
49 if (version != STREAM_VERSION) {
50 throw new StreamCorruptedException(
51 "Unsupported version: " + version);
52 }
53 }
54
55 @Override
56 protected ObjectStreamClass readClassDescriptor()
57 throws IOException, ClassNotFoundException {
58 int type = read();
59 if (type < 0) {
60 throw new EOFException();
61 }
62 switch (type) {
63 case CompactObjectOutputStream.TYPE_FAT_DESCRIPTOR:
64 return super.readClassDescriptor();
65 case CompactObjectOutputStream.TYPE_THIN_DESCRIPTOR:
66 String className = readUTF();
67 Class<?> clazz = loadClass(className);
68 return ObjectStreamClass.lookup(clazz);
69 default:
70 throw new StreamCorruptedException(
71 "Unexpected class descriptor type: " + type);
72 }
73 }
74
75 @Override
76 protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
77 String className = desc.getName();
78 try {
79 return loadClass(className);
80 } catch (ClassNotFoundException ex) {
81 return super.resolveClass(desc);
82 }
83 }
84
85 protected Class<?> loadClass(String className) throws ClassNotFoundException {
86 Class<?> clazz;
87 ClassLoader classLoader = this.classLoader;
88 if (classLoader == null) {
89 classLoader = Thread.currentThread().getContextClassLoader();
90 }
91
92 if (classLoader != null) {
93 clazz = classLoader.loadClass(className);
94 } else {
95 clazz = Class.forName(className);
96 }
97 return clazz;
98 }
99 }