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.string;
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.LineBasedFrameDecoder;
22 import io.netty5.handler.codec.MessageToMessageEncoder;
23
24 import java.nio.charset.Charset;
25 import java.util.List;
26
27 import static java.util.Objects.requireNonNull;
28
29 /**
30 * Encodes the requested {@link String} into a {@link Buffer}.
31 * A typical setup for a text-based line protocol in a TCP/IP socket would be:
32 * <pre>
33 * {@link ChannelPipeline} pipeline = ...;
34 *
35 * // Decoders
36 * pipeline.addLast("frameDecoder", new {@link LineBasedFrameDecoder}(80));
37 * pipeline.addLast("stringDecoder", new {@link StringDecoder}(CharsetUtil.UTF_8));
38 *
39 * // Encoder
40 * pipeline.addLast("stringEncoder", new {@link StringEncoder}(CharsetUtil.UTF_8));
41 * </pre>
42 * and then you can use a {@link String} instead of a {@link Buffer}
43 * as a message:
44 * <pre>
45 * void channelRead({@link ChannelHandlerContext} ctx, {@link String} msg) {
46 * ch.write("Did you say '" + msg + "'?\n");
47 * }
48 * </pre>
49 */
50 public class StringEncoder extends MessageToMessageEncoder<CharSequence> {
51
52 private final Charset charset;
53
54 /**
55 * Creates a new instance with the current system character set.
56 */
57 public StringEncoder() {
58 this(Charset.defaultCharset());
59 }
60
61 /**
62 * Creates a new instance with the specified character set.
63 */
64 public StringEncoder(Charset charset) {
65 requireNonNull(charset, "charset");
66 this.charset = charset;
67 }
68
69 @Override
70 public boolean isSharable() {
71 return true;
72 }
73
74 @Override
75 protected void encode(ChannelHandlerContext ctx, CharSequence msg, List<Object> out) throws Exception {
76 if (msg.length() == 0) {
77 return;
78 }
79
80 out.add(ctx.bufferAllocator().copyOf(msg.toString(), charset));
81 }
82 }