1 20 package org.apache.mina.filter.codec.textline; 21 22 import java.nio.charset.Charset ; 23 import java.nio.charset.CharsetEncoder ; 24 25 import org.apache.mina.common.ByteBuffer; 26 import org.apache.mina.common.IoSession; 27 import org.apache.mina.filter.codec.ProtocolEncoder; 28 import org.apache.mina.filter.codec.ProtocolEncoderAdapter; 29 import org.apache.mina.filter.codec.ProtocolEncoderOutput; 30 31 38 public class TextLineEncoder extends ProtocolEncoderAdapter { 39 private static final String ENCODER = TextLineEncoder.class.getName() 40 + ".encoder"; 41 42 private final Charset charset; 43 44 private final LineDelimiter delimiter; 45 46 private int maxLineLength = Integer.MAX_VALUE; 47 48 public TextLineEncoder() { 49 this(Charset.defaultCharset(), LineDelimiter.UNIX); 50 } 51 52 public TextLineEncoder(LineDelimiter delimiter) { 53 this(Charset.defaultCharset(), delimiter); 54 } 55 56 public TextLineEncoder(Charset charset) { 57 this(charset, LineDelimiter.UNIX); 58 } 59 60 public TextLineEncoder(Charset charset, LineDelimiter delimiter) { 61 if (charset == null) { 62 throw new NullPointerException ("charset"); 63 } 64 if (delimiter == null) { 65 throw new NullPointerException ("delimiter"); 66 } 67 if (LineDelimiter.AUTO.equals(delimiter)) { 68 throw new IllegalArgumentException ( 69 "AUTO delimiter is not allowed for encoder."); 70 } 71 72 this.charset = charset; 73 this.delimiter = delimiter; 74 } 75 76 82 public int getMaxLineLength() { 83 return maxLineLength; 84 } 85 86 92 public void setMaxLineLength(int maxLineLength) { 93 if (maxLineLength <= 0) { 94 throw new IllegalArgumentException ("maxLineLength: " 95 + maxLineLength); 96 } 97 98 this.maxLineLength = maxLineLength; 99 } 100 101 public void encode(IoSession session, Object message, 102 ProtocolEncoderOutput out) throws Exception { 103 CharsetEncoder encoder = (CharsetEncoder ) session.getAttribute(ENCODER); 104 if (encoder == null) { 105 encoder = charset.newEncoder(); 106 session.setAttribute(ENCODER, encoder); 107 } 108 109 String value = message.toString(); 110 ByteBuffer buf = ByteBuffer.allocate(value.length()) 111 .setAutoExpand(true); 112 buf.putString(value, encoder); 113 if (buf.position() > maxLineLength) { 114 throw new IllegalArgumentException ("Line length: " + buf.position()); 115 } 116 buf.putString(delimiter.getValue(), encoder); 117 buf.flip(); 118 out.write(buf); 119 } 120 121 public void dispose() throws Exception { 122 } 123 } | Popular Tags |