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    *   https://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.marshalling;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.Channel;
20  import io.netty.channel.ChannelHandler.Sharable;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.handler.codec.MessageToByteEncoder;
23  
24  import org.jboss.marshalling.Marshaller;
25  
26  /**
27   * {@link MessageToByteEncoder} implementation which uses JBoss Marshalling to marshal
28   * an Object.
29   *
30   * See <a href="https://www.jboss.org/jbossmarshalling">JBoss Marshalling website</a>
31   * for more information
32   *
33   * Use {@link MarshallingEncoder} if possible.
34   *
35   */
36  @Sharable
37  public class CompatibleMarshallingEncoder extends MessageToByteEncoder<Object> {
38  
39      private final MarshallerProvider provider;
40  
41      /**
42       * Create a new instance of the {@link CompatibleMarshallingEncoder}
43       *
44       * @param provider  the {@link MarshallerProvider} to use to get the {@link Marshaller} for a {@link Channel}
45       */
46      public CompatibleMarshallingEncoder(MarshallerProvider provider) {
47          this.provider = provider;
48      }
49  
50      @Override
51      protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
52          Marshaller marshaller = provider.getMarshaller(ctx);
53          marshaller.start(new ChannelBufferByteOutput(out));
54          marshaller.writeObject(msg);
55          marshaller.finish();
56          marshaller.close();
57      }
58  
59  }