1 /* 2 * Copyright 2009 Red Hat, Inc. 3 * 4 * Red Hat licenses this file to you under the Apache License, version 2.0 5 * (the "License"); you may not use this file except in compliance with the 6 * 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 org.jboss.netty.handler.codec.embedder; 17 18 import static org.jboss.netty.channel.Channels.*; 19 20 import org.jboss.netty.buffer.ChannelBuffer; 21 import org.jboss.netty.buffer.ChannelBufferFactory; 22 import org.jboss.netty.channel.ChannelDownstreamHandler; 23 import org.jboss.netty.channel.ChannelPipeline; 24 import org.jboss.netty.handler.codec.base64.Base64Encoder; 25 import org.jboss.netty.handler.codec.string.StringEncoder; 26 import org.jboss.netty.util.CharsetUtil; 27 28 /** 29 * A helper that wraps an encoder so that it can be used without doing actual 30 * I/O in unit tests or higher level codecs. For example, you can encode a 31 * {@link String} into a Base64-encoded {@link ChannelBuffer} with 32 * {@link Base64Encoder} and {@link StringEncoder} without setting up the 33 * {@link ChannelPipeline} and other mock objects by yourself: 34 * <pre> 35 * String data = "foobar"; 36 * 37 * {@link EncoderEmbedder}<{@link ChannelBuffer}> embedder = new {@link EncoderEmbedder}<{@link ChannelBuffer}>( 38 * new {@link Base64Encoder}(), new {@link StringEncoder}()); 39 * 40 * embedder.offer(data); 41 * 42 * {@link ChannelBuffer} encoded = embedder.poll(); 43 * assert encoded.toString({@link CharsetUtil}.US_ASCII).equals("Zm9vYmFy"); 44 * </pre> 45 * 46 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a> 47 * @author <a href="http://gleamynode.net/">Trustin Lee</a> 48 * @version $Rev: 2122 $, $Date: 2010-02-02 11:00:04 +0900 (Tue, 02 Feb 2010) $ 49 * 50 * @apiviz.landmark 51 * @see DecoderEmbedder 52 */ 53 public class EncoderEmbedder<E> extends AbstractCodecEmbedder<E> { 54 55 /** 56 * Creates a new embedder whose pipeline is composed of the specified 57 * handlers. 58 */ 59 public EncoderEmbedder(ChannelDownstreamHandler... handlers) { 60 super(handlers); 61 } 62 63 /** 64 * Creates a new embedder whose pipeline is composed of the specified 65 * handlers. 66 * 67 * @param bufferFactory the {@link ChannelBufferFactory} to be used when 68 * creating a new buffer. 69 */ 70 public EncoderEmbedder(ChannelBufferFactory bufferFactory, ChannelDownstreamHandler... handlers) { 71 super(bufferFactory, handlers); 72 } 73 74 public boolean offer(Object input) { 75 write(getChannel(), input).setSuccess(); 76 return !isEmpty(); 77 } 78 }