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 io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufOutputStream;
20  import io.netty.channel.ChannelHandler.Sharable;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.handler.codec.MessageToByteEncoder;
23  
24  import java.io.ObjectInputStream;
25  import java.io.ObjectOutputStream;
26  import java.io.Serializable;
27  
28  /**
29   * An encoder which serializes a Java object into a {@link ByteBuf}.
30   * <p>
31   * Please note that the serialized form this encoder produces is not
32   * compatible with the standard {@link ObjectInputStream}.  Please use
33   * {@link ObjectDecoder} or {@link ObjectDecoderInputStream} to ensure the
34   * interoperability with this encoder.
35   */
36  @Sharable
37  public class ObjectEncoder extends MessageToByteEncoder<Serializable> {
38      private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
39  
40      @Override
41      protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
42          int startIdx = out.writerIndex();
43  
44          ByteBufOutputStream bout = new ByteBufOutputStream(out);
45          ObjectOutputStream oout = null;
46          try {
47              bout.write(LENGTH_PLACEHOLDER);
48              oout = new CompactObjectOutputStream(bout);
49              oout.writeObject(msg);
50              oout.flush();
51          } finally {
52              if (oout != null) {
53                  oout.close();
54              } else {
55                  bout.close();
56              }
57          }
58  
59          int endIdx = out.writerIndex();
60  
61          out.setInt(startIdx, endIdx - startIdx - 4);
62      }
63  }