chris@1: /* chris@1: * SONEWS News Server chris@1: * see AUTHORS for the list of contributors chris@1: * chris@1: * This program is free software: you can redistribute it and/or modify chris@1: * it under the terms of the GNU General Public License as published by chris@1: * the Free Software Foundation, either version 3 of the License, or chris@1: * (at your option) any later version. chris@1: * chris@1: * This program is distributed in the hope that it will be useful, chris@1: * but WITHOUT ANY WARRANTY; without even the implied warranty of chris@1: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the chris@1: * GNU General Public License for more details. chris@1: * chris@1: * You should have received a copy of the GNU General Public License chris@1: * along with this program. If not, see . chris@1: */ chris@1: chris@1: package org.sonews.daemon; chris@1: chris@1: import java.nio.ByteBuffer; chris@1: import java.nio.CharBuffer; chris@1: import java.nio.channels.ClosedChannelException; chris@1: import java.nio.charset.Charset; chris@1: import java.nio.charset.CharsetEncoder; chris@1: import java.nio.charset.CoderResult; chris@1: chris@1: /** chris@1: * Encodes a line to buffers using the correct charset. chris@1: * @author Christian Lins chris@1: * @since sonews/0.5.0 chris@1: */ chris@1: class LineEncoder chris@1: { chris@1: cli@37: private CharBuffer characters; cli@37: private Charset charset; chris@1: cli@37: /** cli@37: * Constructs new LineEncoder. cli@37: * @param characters cli@37: * @param charset cli@37: */ cli@37: public LineEncoder(CharBuffer characters, Charset charset) cli@37: { cli@37: this.characters = characters; cli@37: this.charset = charset; cli@37: } chris@1: cli@37: /** cli@37: * Encodes the characters of this instance to the given ChannelLineBuffers cli@37: * using the Charset of this instance. cli@37: * @param buffer cli@37: * @throws java.nio.channels.ClosedChannelException cli@37: */ cli@37: public void encode(ChannelLineBuffers buffer) cli@37: throws ClosedChannelException cli@37: { cli@37: CharsetEncoder encoder = charset.newEncoder(); cli@37: while (characters.hasRemaining()) { cli@37: ByteBuffer buf = ChannelLineBuffers.newLineBuffer(); cli@37: assert buf.position() == 0; cli@37: assert buf.capacity() >= 512; chris@1: cli@37: CoderResult res = encoder.encode(characters, buf, true); cli@37: cli@37: // Set limit to current position and current position to 0; cli@37: // means make ready for read from buffer cli@37: buf.flip(); cli@37: buffer.addOutputBuffer(buf); cli@37: cli@37: if (res.isUnderflow()) // All input processed cli@37: { cli@37: break; cli@37: } cli@37: } cli@37: } chris@1: }