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 org.jboss.netty.handler.codec.base64;
17  
18  import org.jboss.netty.buffer.ChannelBuffer;
19  import org.jboss.netty.channel.Channel;
20  import org.jboss.netty.channel.ChannelHandler.Sharable;
21  import org.jboss.netty.channel.ChannelHandlerContext;
22  import org.jboss.netty.channel.ChannelPipeline;
23  import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
24  import org.jboss.netty.handler.codec.frame.Delimiters;
25  import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
26  
27  /**
28   * Encodes a {@link ChannelBuffer} into a Base64-encoded {@link ChannelBuffer}.
29   * A typical setup for TCP/IP would be:
30   * <pre>
31   * {@link ChannelPipeline} pipeline = ...;
32   *
33   * // Decoders
34   * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
35   * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
36   *
37   * // Encoder
38   * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
39   * </pre>
40   * @apiviz.landmark
41   * @apiviz.uses org.jboss.netty.handler.codec.base64.Base64
42   */
43  @Sharable
44  public class Base64Encoder extends OneToOneEncoder {
45  
46      private final boolean breakLines;
47      private final Base64Dialect dialect;
48  
49      public Base64Encoder() {
50          this(true);
51      }
52  
53      public Base64Encoder(boolean breakLines) {
54          this(breakLines, Base64Dialect.STANDARD);
55      }
56  
57      public Base64Encoder(boolean breakLines, Base64Dialect dialect) {
58          if (dialect == null) {
59              throw new NullPointerException("dialect");
60          }
61  
62          this.breakLines = breakLines;
63          this.dialect = dialect;
64      }
65  
66      @Override
67      protected Object encode(ChannelHandlerContext ctx, Channel channel,
68              Object msg) throws Exception {
69          if (!(msg instanceof ChannelBuffer)) {
70              return msg;
71          }
72  
73          ChannelBuffer src = (ChannelBuffer) msg;
74          return Base64.encode(
75                  src, src.readerIndex(), src.readableBytes(),
76                  breakLines, dialect);
77      }
78  }