src/org/sonews/daemon/LineEncoder.java
author cli
Sun Aug 29 18:17:37 2010 +0200 (2010-08-29)
changeset 37 74139325d305
parent 35 ed84c8bdd87b
permissions -rw-r--r--
Switch intent style to Original K&R / Linux / Kernel.
     1 /*
     2  *   SONEWS News Server
     3  *   see AUTHORS for the list of contributors
     4  *
     5  *   This program is free software: you can redistribute it and/or modify
     6  *   it under the terms of the GNU General Public License as published by
     7  *   the Free Software Foundation, either version 3 of the License, or
     8  *   (at your option) any later version.
     9  *
    10  *   This program is distributed in the hope that it will be useful,
    11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  *   GNU General Public License for more details.
    14  *
    15  *   You should have received a copy of the GNU General Public License
    16  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 
    19 package org.sonews.daemon;
    20 
    21 import java.nio.ByteBuffer;
    22 import java.nio.CharBuffer;
    23 import java.nio.channels.ClosedChannelException;
    24 import java.nio.charset.Charset;
    25 import java.nio.charset.CharsetEncoder;
    26 import java.nio.charset.CoderResult;
    27 
    28 /**
    29  * Encodes a line to buffers using the correct charset.
    30  * @author Christian Lins
    31  * @since sonews/0.5.0
    32  */
    33 class LineEncoder
    34 {
    35 
    36 	private CharBuffer characters;
    37 	private Charset charset;
    38 
    39 	/**
    40 	 * Constructs new LineEncoder.
    41 	 * @param characters
    42 	 * @param charset
    43 	 */
    44 	public LineEncoder(CharBuffer characters, Charset charset)
    45 	{
    46 		this.characters = characters;
    47 		this.charset = charset;
    48 	}
    49 
    50 	/**
    51 	 * Encodes the characters of this instance to the given ChannelLineBuffers
    52 	 * using the Charset of this instance.
    53 	 * @param buffer
    54 	 * @throws java.nio.channels.ClosedChannelException
    55 	 */
    56 	public void encode(ChannelLineBuffers buffer)
    57 		throws ClosedChannelException
    58 	{
    59 		CharsetEncoder encoder = charset.newEncoder();
    60 		while (characters.hasRemaining()) {
    61 			ByteBuffer buf = ChannelLineBuffers.newLineBuffer();
    62 			assert buf.position() == 0;
    63 			assert buf.capacity() >= 512;
    64 
    65 			CoderResult res = encoder.encode(characters, buf, true);
    66 
    67 			// Set limit to current position and current position to 0;
    68 			// means make ready for read from buffer
    69 			buf.flip();
    70 			buffer.addOutputBuffer(buf);
    71 
    72 			if (res.isUnderflow()) // All input processed
    73 			{
    74 				break;
    75 			}
    76 		}
    77 	}
    78 }