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.MessageToMessageDecoder;
24  
25  import static java.util.Objects.requireNonNull;
26  
27  /**
28   * Decodes a Base64-encoded {@link Buffer} or US-ASCII {@link String}
29   * into a {@link Buffer}.  Please note that this decoder must be used
30   * with a proper {@link ByteToMessageDecoder} such as {@link DelimiterBasedFrameDecoder}
31   * if you are using a stream-based transport such as TCP/IP.  A typical decoder
32   * setup for TCP/IP would be:
33   * <pre>
34   * {@link ChannelPipeline} pipeline = ...;
35   *
36   * // Decoders
37   * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
38   * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
39   *
40   * // Encoder
41   * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
42   * </pre>
43   */
44  public class Base64Decoder extends MessageToMessageDecoder<Buffer> {
45  
46      private final Base64Dialect dialect;
47  
48      public Base64Decoder() {
49          this(Base64Dialect.STANDARD);
50      }
51  
52      public Base64Decoder(Base64Dialect dialect) {
53          requireNonNull(dialect, "dialect");
54          this.dialect = dialect;
55      }
56  
57      @Override
58      public boolean isSharable() {
59          return true;
60      }
61  
62      @Override
63      protected void decode(ChannelHandlerContext ctx, Buffer msg) throws Exception {
64          ctx.fireChannelRead(Base64.decode(msg, msg.readerOffset(), msg.readableBytes(), dialect));
65      }
66  }