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