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