View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.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  class CompactObjectInputStream extends ObjectInputStream {
26  
27      private final ClassResolver classResolver;
28  
29      CompactObjectInputStream(InputStream in, ClassResolver classResolver) throws IOException {
30          super(in);
31          this.classResolver = classResolver;
32      }
33  
34      @Override
35      protected void readStreamHeader() throws IOException {
36          int version = readByte() & 0xFF;
37          if (version != STREAM_VERSION) {
38              throw new StreamCorruptedException(
39                      "Unsupported version: " + version);
40          }
41      }
42  
43      @Override
44      protected ObjectStreamClass readClassDescriptor()
45              throws IOException, ClassNotFoundException {
46          int type = read();
47          if (type < 0) {
48              throw new EOFException();
49          }
50          switch (type) {
51          case CompactObjectOutputStream.TYPE_FAT_DESCRIPTOR:
52              return super.readClassDescriptor();
53          case CompactObjectOutputStream.TYPE_THIN_DESCRIPTOR:
54              String className = readUTF();
55              Class<?> clazz = classResolver.resolve(className);
56              return ObjectStreamClass.lookupAny(clazz);
57          default:
58              throw new StreamCorruptedException(
59                      "Unexpected class descriptor type: " + type);
60          }
61      }
62  
63      @Override
64      protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
65          Class<?> clazz;
66          try {
67              clazz = classResolver.resolve(desc.getName());
68          } catch (ClassNotFoundException ignored) {
69              clazz = super.resolveClass(desc);
70          }
71  
72          return clazz;
73      }
74  
75  }