查看本类的 API文档回源码主页即时通讯网 - 即时通讯开发者社区!
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.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  import io.netty.util.internal.ObjectUtil;
27  
28  import java.util.List;
29  
30  /**
31   * Decodes a Base64-encoded {@link ByteBuf} or US-ASCII {@link String}
32   * into a {@link ByteBuf}.  Please note that this decoder must be used
33   * with a proper {@link ByteToMessageDecoder} such as {@link DelimiterBasedFrameDecoder}
34   * if you are using a stream-based transport such as TCP/IP.  A typical decoder
35   * setup for TCP/IP would be:
36   * <pre>
37   * {@link ChannelPipeline} pipeline = ...;
38   *
39   * // Decoders
40   * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
41   * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
42   *
43   * // Encoder
44   * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
45   * </pre>
46   */
47  @Sharable
48  public class Base64Decoder extends MessageToMessageDecoder<ByteBuf> {
49  
50      private final Base64Dialect dialect;
51  
52      public Base64Decoder() {
53          this(Base64Dialect.STANDARD);
54      }
55  
56      public Base64Decoder(Base64Dialect dialect) {
57          this.dialect = ObjectUtil.checkNotNull(dialect, "dialect");
58      }
59  
60      @Override
61      protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
62          out.add(Base64.decode(msg, msg.readerIndex(), msg.readableBytes(), dialect));
63      }
64  }