001 /* 002 * Copyright 2010 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package com.hs.mail.imap.server.codec; 017 018 import java.nio.ByteBuffer; 019 import java.nio.charset.Charset; 020 021 import org.jboss.netty.buffer.ChannelBuffers; 022 import org.jboss.netty.channel.Channel; 023 import org.jboss.netty.channel.ChannelHandlerContext; 024 import org.jboss.netty.channel.ChannelPipelineCoverage; 025 import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; 026 027 /** 028 * Encodes an {@link ImapMessage} into a <code>ChannelBuffer</code>. 029 * 030 * @author Won Chul Doh 031 * @since Jan 22, 2010 032 * 033 */ 034 @ChannelPipelineCoverage("all") 035 public class ImapMessageEncoder extends OneToOneEncoder { 036 037 private final String charsetName; 038 039 public ImapMessageEncoder() { 040 this(Charset.defaultCharset()); 041 } 042 043 public ImapMessageEncoder(String charsetName) { 044 this(Charset.forName(charsetName)); 045 } 046 047 public ImapMessageEncoder(Charset charset) { 048 if (charset == null) { 049 throw new NullPointerException("charset"); 050 } 051 charsetName = charset.name(); 052 } 053 054 @Override 055 protected Object encode(ChannelHandlerContext ctx, Channel channel, 056 Object msg) throws Exception { 057 if (msg instanceof String) { 058 return ChannelBuffers.copiedBuffer((String) msg, charsetName); 059 } 060 if (msg instanceof ByteBuffer) { 061 return ChannelBuffers.copiedBuffer((ByteBuffer) msg); 062 } 063 // Unknown message type 064 return msg; 065 } 066 067 }