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.DelimiterBasedFrameDecoder;
23 import io.netty.handler.codec.Delimiters;
24 import io.netty.handler.codec.MessageToMessageEncoder;
25 import io.netty.util.internal.ObjectUtil;
26
27 import java.util.List;
28
29 /**
30 * Encodes a {@link ByteBuf} into a Base64-encoded {@link ByteBuf}.
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 @Sharable
44 public class Base64Encoder extends MessageToMessageEncoder<ByteBuf> {
45
46 private final boolean breakLines;
47 private final Base64Dialect dialect;
48
49 public Base64Encoder() {
50 this(true);
51 }
52
53 public Base64Encoder(boolean breakLines) {
54 this(breakLines, Base64Dialect.STANDARD);
55 }
56
57 public Base64Encoder(boolean breakLines, Base64Dialect dialect) {
58 this.dialect = ObjectUtil.checkNotNull(dialect, "dialect");
59 this.breakLines = breakLines;
60 }
61
62 @Override
63 protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
64 out.add(Base64.encode(msg, msg.readerIndex(), msg.readableBytes(), breakLines, dialect));
65 }
66 }