1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/org/sonews/daemon/LineEncoder.java Mon Aug 24 13:00:05 2009 +0200
1.3 @@ -0,0 +1,80 @@
1.4 +/*
1.5 + * SONEWS News Server
1.6 + * see AUTHORS for the list of contributors
1.7 + *
1.8 + * This program is free software: you can redistribute it and/or modify
1.9 + * it under the terms of the GNU General Public License as published by
1.10 + * the Free Software Foundation, either version 3 of the License, or
1.11 + * (at your option) any later version.
1.12 + *
1.13 + * This program is distributed in the hope that it will be useful,
1.14 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
1.15 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1.16 + * GNU General Public License for more details.
1.17 + *
1.18 + * You should have received a copy of the GNU General Public License
1.19 + * along with this program. If not, see <http://www.gnu.org/licenses/>.
1.20 + */
1.21 +
1.22 +package org.sonews.daemon;
1.23 +
1.24 +import java.nio.ByteBuffer;
1.25 +import java.nio.CharBuffer;
1.26 +import java.nio.channels.ClosedChannelException;
1.27 +import java.nio.charset.Charset;
1.28 +import java.nio.charset.CharsetEncoder;
1.29 +import java.nio.charset.CoderResult;
1.30 +
1.31 +/**
1.32 + * Encodes a line to buffers using the correct charset.
1.33 + * @author Christian Lins
1.34 + * @since sonews/0.5.0
1.35 + */
1.36 +class LineEncoder
1.37 +{
1.38 +
1.39 + private CharBuffer characters;
1.40 + private Charset charset;
1.41 +
1.42 + /**
1.43 + * Constructs new LineEncoder.
1.44 + * @param characters
1.45 + * @param charset
1.46 + */
1.47 + public LineEncoder(CharBuffer characters, Charset charset)
1.48 + {
1.49 + this.characters = characters;
1.50 + this.charset = charset;
1.51 + }
1.52 +
1.53 + /**
1.54 + * Encodes the characters of this instance to the given ChannelLineBuffers
1.55 + * using the Charset of this instance.
1.56 + * @param buffer
1.57 + * @throws java.nio.channels.ClosedChannelException
1.58 + */
1.59 + public void encode(ChannelLineBuffers buffer)
1.60 + throws ClosedChannelException
1.61 + {
1.62 + CharsetEncoder encoder = charset.newEncoder();
1.63 + while (characters.hasRemaining())
1.64 + {
1.65 + ByteBuffer buf = ChannelLineBuffers.newLineBuffer();
1.66 + assert buf.position() == 0;
1.67 + assert buf.capacity() >= 512;
1.68 +
1.69 + CoderResult res = encoder.encode(characters, buf, true);
1.70 +
1.71 + // Set limit to current position and current position to 0;
1.72 + // means make ready for read from buffer
1.73 + buf.flip();
1.74 + buffer.addOutputBuffer(buf);
1.75 +
1.76 + if (res.isUnderflow()) // All input processed
1.77 + {
1.78 + break;
1.79 + }
1.80 + }
1.81 + }
1.82 +
1.83 +}