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.netty5.handler.codec.base64;
17  
18  import io.netty5.buffer.api.Buffer;
19  import io.netty5.channel.ChannelHandlerContext;
20  import io.netty5.channel.ChannelPipeline;
21  import io.netty5.handler.codec.DelimiterBasedFrameDecoder;
22  import io.netty5.handler.codec.Delimiters;
23  import io.netty5.handler.codec.MessageToMessageEncoder;
24  
25  import java.util.List;
26  
27  import static java.util.Objects.requireNonNull;
28  
29  /**
30   * Encodes a {@link Buffer} into a Base64-encoded {@link Buffer}.
31   * A typical setup for TCP/IP would be:
32   * <pre>
33   * {@link ChannelPipeline} pipeline = ...;
34   *
35   * // Decoders
36   * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
37   * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
38   *
39   * // Encoder
40   * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
41   * </pre>
42   */
43  public class Base64Encoder extends MessageToMessageEncoder<Buffer> {
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          requireNonNull(dialect, "dialect");
58  
59          this.breakLines = breakLines;
60          this.dialect = dialect;
61      }
62  
63      @Override
64      public boolean isSharable() {
65          return true;
66      }
67  
68      @Override
69      protected void encode(ChannelHandlerContext ctx, Buffer msg, List<Object> out) throws Exception {
70          out.add(Base64.encode(msg, msg.readerOffset(), msg.readableBytes(), breakLines, dialect));
71      }
72  }