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