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 <http://www.gnu.org/licenses/>.
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: 
chris@1:   private CharBuffer    characters;
chris@1:   private Charset       charset;
chris@1:   
chris@1:   /**
chris@1:    * Constructs new LineEncoder.
chris@1:    * @param characters
chris@1:    * @param charset
chris@1:    */
chris@1:   public LineEncoder(CharBuffer characters, Charset charset)
chris@1:   {
chris@1:     this.characters = characters;
chris@1:     this.charset    = charset;
chris@1:   }
chris@1:   
chris@1:   /**
chris@1:    * Encodes the characters of this instance to the given ChannelLineBuffers
chris@1:    * using the Charset of this instance.
chris@1:    * @param buffer
chris@1:    * @throws java.nio.channels.ClosedChannelException
chris@1:    */
chris@1:   public void encode(ChannelLineBuffers buffer)
chris@1:     throws ClosedChannelException
chris@1:   {
chris@1:     CharsetEncoder encoder = charset.newEncoder();
chris@1:     while (characters.hasRemaining())
chris@1:     {
chris@1:       ByteBuffer buf = ChannelLineBuffers.newLineBuffer();
chris@1:       assert buf.position() == 0;
chris@1:       assert buf.capacity() >= 512;
chris@1: 
chris@1:       CoderResult res = encoder.encode(characters, buf, true);
chris@1: 
chris@1:       // Set limit to current position and current position to 0;
chris@1:       // means make ready for read from buffer
chris@1:       buf.flip();
chris@1:       buffer.addOutputBuffer(buf);
chris@1: 
chris@1:       if (res.isUnderflow()) // All input processed
chris@1:       {
chris@1:         break;
chris@1:       }
chris@1:     }
chris@1:   }
chris@1:   
chris@1: }