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.ChannelHandlerContext;
21  import io.netty.handler.codec.MessageToByteEncoder;
22  import io.netty.util.Attribute;
23  import io.netty.util.AttributeKey;
24  
25  import java.io.ObjectInputStream;
26  import java.io.ObjectOutputStream;
27  import java.io.OutputStream;
28  import java.io.Serializable;
29  
30  /**
31   * An encoder which serializes a Java object into a {@link ByteBuf}
32   * (interoperability version).
33   * <p>
34   * This encoder is interoperable with the standard Java object streams such as
35   * {@link ObjectInputStream} and {@link ObjectOutputStream}.
36   */
37  public class CompatibleObjectEncoder extends MessageToByteEncoder<Serializable> {
38      private final int resetInterval;
39      private int writtenObjects;
40  
41      /**
42       * Creates a new instance with the reset interval of {@code 16}.
43       */
44      public CompatibleObjectEncoder() {
45          this(16); // Reset at every sixteen writes
46      }
47  
48      /**
49       * Creates a new instance.
50       *
51       * @param resetInterval
52       *        the number of objects between {@link ObjectOutputStream#reset()}.
53       *        {@code 0} will disable resetting the stream, but the remote
54       *        peer will be at the risk of getting {@link OutOfMemoryError} in
55       *        the long term.
56       */
57      public CompatibleObjectEncoder(int resetInterval) {
58          if (resetInterval < 0) {
59              throw new IllegalArgumentException(
60                      "resetInterval: " + resetInterval);
61          }
62          this.resetInterval = resetInterval;
63      }
64  
65      /**
66       * Creates a new {@link ObjectOutputStream} which wraps the specified
67       * {@link OutputStream}.  Override this method to use a subclass of the
68       * {@link ObjectOutputStream}.
69       */
70      protected ObjectOutputStream newObjectOutputStream(OutputStream out) throws Exception {
71          return new ObjectOutputStream(out);
72      }
73  
74      @Override
75      protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
76          ObjectOutputStream oos = newObjectOutputStream(new ByteBufOutputStream(out));
77          try {
78              if (resetInterval != 0) {
79                  // Resetting will prevent OOM on the receiving side.
80                  writtenObjects ++;
81                  if (writtenObjects % resetInterval == 0) {
82                      oos.reset();
83                  }
84              }
85  
86              oos.writeObject(msg);
87              oos.flush();
88          } finally {
89              oos.close();
90          }
91      }
92  }