directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From pro...@apache.org
Subject svn commit: r471457 - in /directory/branches/mina/1.2: core/src/main/java/org/apache/mina/filter/codec/textline/ core/src/main/java/org/apache/mina/util/ core/src/test/java/org/apache/mina/util/ example/src/main/java/org/apache/mina/example/httpserver/...
Date Sun, 05 Nov 2006 16:44:11 GMT
Author: proyal
Date: Sun Nov  5 08:44:10 2006
New Revision: 471457

URL: http://svn.apache.org/viewvc?view=rev&rev=471457
Log:
Inline CharsetUtil as it was a workaround for java 1.4

Removed:
    directory/branches/mina/1.2/core/src/main/java/org/apache/mina/util/CharsetUtil.java
    directory/branches/mina/1.2/core/src/test/java/org/apache/mina/util/CharsetUtilTest.java
Modified:
    directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineCodecFactory.java
    directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineDecoder.java
    directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineEncoder.java
    directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.java
    directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.java

Modified: directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineCodecFactory.java
URL: http://svn.apache.org/viewvc/directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineCodecFactory.java?view=diff&rev=471457&r1=471456&r2=471457
==============================================================================
--- directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineCodecFactory.java (original)
+++ directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineCodecFactory.java Sun Nov  5 08:44:10 2006
@@ -6,16 +6,16 @@
  *  to you under the Apache License, Version 2.0 (the
  *  "License"); you may not use this file except in compliance
  *  with the License.  You may obtain a copy of the License at
- *  
+ *
  *    http://www.apache.org/licenses/LICENSE-2.0
- *  
+ *
  *  Unless required by applicable law or agreed to in writing,
  *  software distributed under the License is distributed on an
  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  *  KIND, either express or implied.  See the License for the
  *  specific language governing permissions and limitations
- *  under the License. 
- *  
+ *  under the License.
+ *
  */
 package org.apache.mina.filter.codec.textline;
 
@@ -25,7 +25,6 @@
 import org.apache.mina.filter.codec.ProtocolCodecFactory;
 import org.apache.mina.filter.codec.ProtocolDecoder;
 import org.apache.mina.filter.codec.ProtocolEncoder;
-import org.apache.mina.util.CharsetUtil;
 
 /**
  * A {@link ProtocolCodecFactory} that performs encoding and decoding between
@@ -39,15 +38,15 @@
 {
     private final TextLineEncoder encoder;
     private final TextLineDecoder decoder;
-    
+
     /**
      * Creates a new instance with the current default {@link Charset}.
      */
     public TextLineCodecFactory()
     {
-        this( Charset.forName( CharsetUtil.getDefaultCharsetName() ) );
+        this( Charset.defaultCharset() );
     }
-    
+
     /**
      * Creates a new instance with the specified {@link Charset}.
      */
@@ -66,7 +65,7 @@
     {
         return decoder;
     }
-    
+
     /**
      * Returns the allowed maximum size of the encoded line.
      * If the size of the encoded line exceeds this value, the encoder
@@ -79,7 +78,7 @@
     {
         return encoder.getMaxLineLength();
     }
-    
+
     /**
      * Sets the allowed maximum size of the encoded line.
      * If the size of the encoded line exceeds this value, the encoder
@@ -92,7 +91,7 @@
     {
         encoder.setMaxLineLength( maxLineLength );
     }
-    
+
     /**
      * Returns the allowed maximum size of the line to be decoded.
      * If the size of the line to be decoded exceeds this value, the
@@ -105,7 +104,7 @@
     {
         return decoder.getMaxLineLength();
     }
-    
+
     /**
      * Sets the allowed maximum size of the line to be decoded.
      * If the size of the line to be decoded exceeds this value, the

Modified: directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineDecoder.java
URL: http://svn.apache.org/viewvc/directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineDecoder.java?view=diff&rev=471457&r1=471456&r2=471457
==============================================================================
--- directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineDecoder.java (original)
+++ directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineDecoder.java Sun Nov  5 08:44:10 2006
@@ -6,16 +6,16 @@
  *  to you under the Apache License, Version 2.0 (the
  *  "License"); you may not use this file except in compliance
  *  with the License.  You may obtain a copy of the License at
- *  
+ *
  *    http://www.apache.org/licenses/LICENSE-2.0
- *  
+ *
  *  Unless required by applicable law or agreed to in writing,
  *  software distributed under the License is distributed on an
  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  *  KIND, either express or implied.  See the License for the
  *  specific language governing permissions and limitations
- *  under the License. 
- *  
+ *  under the License.
+ *
  */
 package org.apache.mina.filter.codec.textline;
 
@@ -28,284 +28,282 @@
 import org.apache.mina.common.IoSession;
 import org.apache.mina.filter.codec.ProtocolDecoder;
 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
-import org.apache.mina.util.CharsetUtil;
 
 /**
  * A {@link ProtocolDecoder} which decodes a text line into a string.
- * 
+ *
  * @author The Apache Directory Project (mina-dev@directory.apache.org)
  * @version $Rev$, $Date$,
  */
 public class TextLineDecoder implements ProtocolDecoder
 {
-    private static final String CONTEXT = TextLineDecoder.class.getName() + ".context";
+	private static final String CONTEXT = TextLineDecoder.class.getName() + ".context";
 
-    private final Charset charset;
-    private final LineDelimiter delimiter;
-    private ByteBuffer delimBuf;
-    private int maxLineLength = 1024;
-    
-    /**
-     * Creates a new instance with the current default {@link Charset}
-     * and {@link LineDelimiter#AUTO} delimiter.
-     */
-    public TextLineDecoder()
-    {
-        this( CharsetUtil.getDefaultCharset(), LineDelimiter.AUTO );
-    }
-    
-    /**
-     * Creates a new instance with the spcified <tt>charset</tt>
-     * and {@link LineDelimiter#AUTO} delimiter.
-     */
-    public TextLineDecoder( Charset charset )
-    {
-        this( charset, LineDelimiter.AUTO );
-    }
-
-    /**
-     * Creates a new instance with the specified <tt>charset</tt>
-     * and the specified <tt>delimiter</tt>.
-     */
-    public TextLineDecoder( Charset charset, LineDelimiter delimiter )
-    {
-        if( charset == null )
-        {
-            throw new NullPointerException( "charset" );
-        }
-        if( delimiter == null )
-        {
-            throw new NullPointerException( "delimiter" );
-        }
-        
-        this.charset = charset;
-        this.delimiter = delimiter;
-    }
-    
-    /**
-     * Returns the allowed maximum size of the line to be decoded.
-     * If the size of the line to be decoded exceeds this value, the
-     * decoder will throw a {@link BufferDataException}.  The default
-     * value is <tt>1024</tt> (1KB).
-     */
-    public int getMaxLineLength()
-    {
-        return maxLineLength;
-    }
-    
-    /**
-     * Sets the allowed maximum size of the line to be decoded.
-     * If the size of the line to be decoded exceeds this value, the
-     * decoder will throw a {@link BufferDataException}.  The default
-     * value is <tt>1024</tt> (1KB).
-     */
-    public void setMaxLineLength( int maxLineLength )
-    {
-        if( maxLineLength <= 0 )
-        {
-            throw new IllegalArgumentException( "maxLineLength: " + maxLineLength );
-        }
-        
-        this.maxLineLength = maxLineLength;
-    }
-
-    public void decode( IoSession session, ByteBuffer in,
-                        ProtocolDecoderOutput out )
-            throws Exception
-    {
-        Context ctx = getContext(session);
-        
-        if( LineDelimiter.AUTO.equals( delimiter ) )
-        {
-            ctx.setMatchCount(
-                    decodeAuto(
-                            in,
-                            ctx.getBuffer(),
-                            ctx.getMatchCount(),
-                            ctx.getDecoder(),
-                            out ) );
-        }
-        else
-        {
-            ctx.setMatchCount(
-                    decodeNormal(
-                            in,
-                            ctx.getBuffer(),
-                            ctx.getMatchCount(),
-                            ctx.getDecoder(),
-                            out ) );
-        }
-    }
-
-    private Context getContext(IoSession session) {
-        Context ctx;
-        ctx = ( Context ) session.getAttribute( CONTEXT );
-        if( ctx == null )
-        {
-            ctx = new Context();
-            session.setAttribute( CONTEXT, ctx );
-        }
-        return ctx;
-    }
-
-    public void finishDecode( IoSession session, ProtocolDecoderOutput out ) throws Exception
-    {
-    }
-
-    public void dispose( IoSession session ) throws Exception
-    {
-        Context ctx = ( Context ) session.getAttribute( CONTEXT );
-        if( ctx != null )
-        {
-            ctx.getBuffer().release();
-            session.removeAttribute( CONTEXT );
-        }
-    }
-
-    private int decodeAuto( ByteBuffer in, ByteBuffer buf, int matchCount, CharsetDecoder decoder, ProtocolDecoderOutput out ) throws CharacterCodingException
-    {
-        // Try to find a match
-        int oldMatchCount = matchCount;
-        int oldPos = in.position();
-        int oldLimit = in.limit();
-        while( in.hasRemaining() )
-        {
-            byte b = in.get();
-            boolean matched = false;
-            switch( b )
-            {
-            case '\r':
-                // Might be Mac, but we don't auto-detect Mac EOL
-                // to avoid confusion.
-                matchCount ++;
-                break;
-            case '\n':
-                // UNIX
-                matchCount ++;
-                matched = true;
-                break;
-            default:
-                matchCount = 0;
-            }
-
-            if( matched )
-            {
-                // Found a match.
-                int pos = in.position();
-                in.limit( pos - matchCount + oldMatchCount );
-                in.position( oldPos );
-                
-                buf.put( in );
-                if( buf.position() > maxLineLength )
-                {
-                    throw new BufferDataException( "Line is too long: " + buf.position() );
-                }
-                buf.flip();
-                out.write( buf.getString( decoder ) );
-                buf.clear();
-                
-                in.limit( oldLimit );
-                in.position( pos );
-                oldPos = pos;
-                matchCount = 0;
-            }
-        }
-        
-        // Put remainder to buf.
-        in.position( oldPos );
-        in.limit( in.limit() - matchCount + oldMatchCount );
-        buf.put( in );
-        
-        return matchCount;
-    }
-
-    private int decodeNormal( ByteBuffer in, ByteBuffer buf, int matchCount, CharsetDecoder decoder, ProtocolDecoderOutput out ) throws CharacterCodingException
-    {
-        // Convert delimiter to ByteBuffer if not done yet.
-        if( delimBuf == null )
-        {
-            ByteBuffer tmp = ByteBuffer.allocate( 2 ).setAutoExpand( true );
-            tmp.putString( delimiter.getValue(), charset.newEncoder() );
-            tmp.flip();
-            delimBuf = tmp;
-        }
-        
-        // Try to find a match
-        int oldMatchCount = matchCount;
-        int oldPos = in.position();
-        int oldLimit = in.limit();
-        while( in.hasRemaining() )
-        {
-            byte b = in.get();
-            if( delimBuf.get( matchCount ) == b )
-            {
-                matchCount ++;
-                if( matchCount == delimBuf.limit() )
-                {
-                    // Found a match.
-                    int pos = in.position();
-                    in.limit( pos - matchCount + oldMatchCount );
-                    in.position( oldPos );
-                    
-                    buf.put( in );
-                    if( buf.position() > maxLineLength )
-                    {
-                        throw new BufferDataException( "Line is too long: " + buf.position() );
-                    }
-                    buf.flip();
-                    out.write( buf.getString( decoder ) );
-                    buf.clear();
-                    
-                    in.limit( oldLimit );
-                    in.position( pos );
-                    oldPos = pos;
-                    matchCount = 0;
-                }
-            }
-            else
-            {
-                matchCount = 0;
-            }
-        }
-        
-        // Put remainder to buf.
-        in.position( oldPos );
-        in.limit( in.limit() - matchCount + oldMatchCount );
-        buf.put( in );
-        
-        return matchCount;
-    }
-    
-    private class Context
-    {
-        private final CharsetDecoder decoder;
-        private final ByteBuffer buf;
-        private int matchCount = 0;
-        
-        private Context()
-        {
-            decoder = charset.newDecoder();
-            buf = ByteBuffer.allocate( 80 ).setAutoExpand( true );
-        }
-        
-        public CharsetDecoder getDecoder()
-        {
-            return decoder;
-        }
-        
-        public ByteBuffer getBuffer()
-        {
-            return buf;
-        }
-        
-        public int getMatchCount()
-        {
-            return matchCount;
-        }
-        
-        public void setMatchCount( int matchCount )
-        {
-            this.matchCount = matchCount;
-        }
-    }
+	private final Charset charset;
+	private final LineDelimiter delimiter;
+	private ByteBuffer delimBuf;
+	private int maxLineLength = 1024;
+
+	/**
+	 * Creates a new instance with the current default {@link Charset}
+	 * and {@link LineDelimiter#AUTO} delimiter.
+	 */
+	public TextLineDecoder()
+	{
+		this( Charset.defaultCharset(), LineDelimiter.AUTO );
+	}
+
+	/**
+	 * Creates a new instance with the spcified <tt>charset</tt>
+	 * and {@link LineDelimiter#AUTO} delimiter.
+	 */
+	public TextLineDecoder( Charset charset )
+	{
+		this( charset, LineDelimiter.AUTO );
+	}
+
+	/**
+	 * Creates a new instance with the specified <tt>charset</tt>
+	 * and the specified <tt>delimiter</tt>.
+	 */
+	public TextLineDecoder( Charset charset, LineDelimiter delimiter )
+	{
+		if( charset == null )
+		{
+			throw new NullPointerException( "charset" );
+		}
+		if( delimiter == null )
+		{
+			throw new NullPointerException( "delimiter" );
+		}
+
+		this.charset = charset;
+		this.delimiter = delimiter;
+	}
+
+	/**
+	 * Returns the allowed maximum size of the line to be decoded.
+	 * If the size of the line to be decoded exceeds this value, the
+	 * decoder will throw a {@link BufferDataException}.  The default
+	 * value is <tt>1024</tt> (1KB).
+	 */
+	public int getMaxLineLength()
+	{
+		return maxLineLength;
+	}
+
+	/**
+	 * Sets the allowed maximum size of the line to be decoded.
+	 * If the size of the line to be decoded exceeds this value, the
+	 * decoder will throw a {@link BufferDataException}.  The default
+	 * value is <tt>1024</tt> (1KB).
+	 */
+	public void setMaxLineLength( int maxLineLength )
+	{
+		if( maxLineLength <= 0 )
+		{
+			throw new IllegalArgumentException( "maxLineLength: " + maxLineLength );
+		}
+
+		this.maxLineLength = maxLineLength;
+	}
+
+	public void decode( IoSession session, ByteBuffer in,
+						ProtocolDecoderOutput out )
+			throws Exception
+	{
+		Context ctx = getContext(session);
+
+		if( LineDelimiter.AUTO.equals( delimiter ) )
+		{
+			ctx.setMatchCount(
+					decodeAuto(
+							in,
+							ctx.getBuffer(),
+							ctx.getMatchCount(),
+							ctx.getDecoder(),
+							out ) );
+		}
+		else
+		{
+			ctx.setMatchCount(
+					decodeNormal(
+							in,
+							ctx.getBuffer(),
+							ctx.getMatchCount(),
+							ctx.getDecoder(),
+							out ) );
+		}
+	}
+
+	private Context getContext(IoSession session) {
+		Context ctx = (Context) session.getAttribute( CONTEXT );
+		if( ctx == null )
+		{
+			ctx = new Context();
+			session.setAttribute( CONTEXT, ctx );
+		}
+		return ctx;
+	}
+
+	public void finishDecode( IoSession session, ProtocolDecoderOutput out ) throws Exception
+	{
+	}
+
+	public void dispose( IoSession session ) throws Exception
+	{
+		Context ctx = ( Context ) session.getAttribute( CONTEXT );
+		if( ctx != null )
+		{
+			ctx.getBuffer().release();
+			session.removeAttribute( CONTEXT );
+		}
+	}
+
+	private int decodeAuto( ByteBuffer in, ByteBuffer buf, int matchCount, CharsetDecoder decoder, ProtocolDecoderOutput out ) throws CharacterCodingException
+	{
+		// Try to find a match
+		int oldMatchCount = matchCount;
+		int oldPos = in.position();
+		int oldLimit = in.limit();
+		while( in.hasRemaining() )
+		{
+			byte b = in.get();
+			boolean matched = false;
+			switch( b )
+			{
+			case '\r':
+				// Might be Mac, but we don't auto-detect Mac EOL
+				// to avoid confusion.
+				matchCount ++;
+				break;
+			case '\n':
+				// UNIX
+				matchCount ++;
+				matched = true;
+				break;
+			default:
+				matchCount = 0;
+			}
+
+			if( matched )
+			{
+				// Found a match.
+				int pos = in.position();
+				in.limit( pos - matchCount + oldMatchCount );
+				in.position( oldPos );
+
+				buf.put( in );
+				if( buf.position() > maxLineLength )
+				{
+					throw new BufferDataException( "Line is too long: " + buf.position() );
+				}
+				buf.flip();
+				out.write( buf.getString( decoder ) );
+				buf.clear();
+
+				in.limit( oldLimit );
+				in.position( pos );
+				oldPos = pos;
+				matchCount = 0;
+			}
+		}
+
+		// Put remainder to buf.
+		in.position( oldPos );
+		in.limit( in.limit() - matchCount + oldMatchCount );
+		buf.put( in );
+
+		return matchCount;
+	}
+
+	private int decodeNormal( ByteBuffer in, ByteBuffer buf, int matchCount, CharsetDecoder decoder, ProtocolDecoderOutput out ) throws CharacterCodingException
+	{
+		// Convert delimiter to ByteBuffer if not done yet.
+		if( delimBuf == null )
+		{
+			ByteBuffer tmp = ByteBuffer.allocate( 2 ).setAutoExpand( true );
+			tmp.putString( delimiter.getValue(), charset.newEncoder() );
+			tmp.flip();
+			delimBuf = tmp;
+		}
+
+		// Try to find a match
+		int oldMatchCount = matchCount;
+		int oldPos = in.position();
+		int oldLimit = in.limit();
+		while( in.hasRemaining() )
+		{
+			byte b = in.get();
+			if( delimBuf.get( matchCount ) == b )
+			{
+				matchCount ++;
+				if( matchCount == delimBuf.limit() )
+				{
+					// Found a match.
+					int pos = in.position();
+					in.limit( pos - matchCount + oldMatchCount );
+					in.position( oldPos );
+
+					buf.put( in );
+					if( buf.position() > maxLineLength )
+					{
+						throw new BufferDataException( "Line is too long: " + buf.position() );
+					}
+					buf.flip();
+					out.write( buf.getString( decoder ) );
+					buf.clear();
+
+					in.limit( oldLimit );
+					in.position( pos );
+					oldPos = pos;
+					matchCount = 0;
+				}
+			}
+			else
+			{
+				matchCount = 0;
+			}
+		}
+
+		// Put remainder to buf.
+		in.position( oldPos );
+		in.limit( in.limit() - matchCount + oldMatchCount );
+		buf.put( in );
+
+		return matchCount;
+	}
+
+	private class Context
+	{
+		private final CharsetDecoder decoder;
+		private final ByteBuffer buf;
+		private int matchCount = 0;
+
+		private Context()
+		{
+			decoder = charset.newDecoder();
+			buf = ByteBuffer.allocate( 80 ).setAutoExpand( true );
+		}
+
+		public CharsetDecoder getDecoder()
+		{
+			return decoder;
+		}
+
+		public ByteBuffer getBuffer()
+		{
+			return buf;
+		}
+
+		public int getMatchCount()
+		{
+			return matchCount;
+		}
+
+		public void setMatchCount( int matchCount )
+		{
+			this.matchCount = matchCount;
+		}
+	}
 }

Modified: directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineEncoder.java
URL: http://svn.apache.org/viewvc/directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineEncoder.java?view=diff&rev=471457&r1=471456&r2=471457
==============================================================================
--- directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineEncoder.java (original)
+++ directory/branches/mina/1.2/core/src/main/java/org/apache/mina/filter/codec/textline/TextLineEncoder.java Sun Nov  5 08:44:10 2006
@@ -6,16 +6,16 @@
  *  to you under the Apache License, Version 2.0 (the
  *  "License"); you may not use this file except in compliance
  *  with the License.  You may obtain a copy of the License at
- *  
+ *
  *    http://www.apache.org/licenses/LICENSE-2.0
- *  
+ *
  *  Unless required by applicable law or agreed to in writing,
  *  software distributed under the License is distributed on an
  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  *  KIND, either express or implied.  See the License for the
  *  specific language governing permissions and limitations
- *  under the License. 
- *  
+ *  under the License.
+ *
  */
 package org.apache.mina.filter.codec.textline;
 
@@ -27,109 +27,108 @@
 import org.apache.mina.filter.codec.ProtocolEncoder;
 import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
-import org.apache.mina.util.CharsetUtil;
 
 /**
  * A {@link ProtocolEncoder} which encodes a string into a text line
  * which ends with the delimiter.
- * 
+ *
  * @author The Apache Directory Project (mina-dev@directory.apache.org)
  * @version $Rev$, $Date$,
  */
 public class TextLineEncoder extends ProtocolEncoderAdapter
 {
-    private static final String ENCODER = TextLineEncoder.class.getName() + ".encoder";
+	private static final String ENCODER = TextLineEncoder.class.getName() + ".encoder";
 
-    private final Charset charset;
-    private final LineDelimiter delimiter;
-    private int maxLineLength = Integer.MAX_VALUE;
-
-    public TextLineEncoder()
-    {
-        this( CharsetUtil.getDefaultCharset(), LineDelimiter.UNIX );
-    }
-    
-    public TextLineEncoder( LineDelimiter delimiter )
-    {
-        this( CharsetUtil.getDefaultCharset(), delimiter );
-    }
-    
-    public TextLineEncoder( Charset charset )
-    {
-        this( charset, LineDelimiter.UNIX );
-    }
-    
-    public TextLineEncoder( Charset charset, LineDelimiter delimiter )
-    {
-        if( charset == null )
-        {
-            throw new NullPointerException( "charset" );
-        }
-        if( delimiter == null )
-        {
-            throw new NullPointerException( "delimiter" );
-        }
-        if( LineDelimiter.AUTO.equals( delimiter ) )
-        {
-            throw new IllegalArgumentException( "AUTO delimiter is not allowed for encoder." );
-        }
-        
-        
-        this.charset = charset;
-        this.delimiter = delimiter;
-    }
-    
-    /**
-     * Returns the allowed maximum size of the encoded line.
-     * If the size of the encoded line exceeds this value, the encoder
-     * will throw a {@link IllegalArgumentException}.  The default value
-     * is {@link Integer#MAX_VALUE}.
-     */
-    public int getMaxLineLength()
-    {
-        return maxLineLength;
-    }
-    
-    /**
-     * Sets the allowed maximum size of the encoded line.
-     * If the size of the encoded line exceeds this value, the encoder
-     * will throw a {@link IllegalArgumentException}.  The default value
-     * is {@link Integer#MAX_VALUE}.
-     */
-    public void setMaxLineLength( int maxLineLength )
-    {
-        if( maxLineLength <= 0 )
-        {
-            throw new IllegalArgumentException( "maxLineLength: " + maxLineLength );
-        }
-        
-        this.maxLineLength = maxLineLength;
-    }
-
-    public void encode( IoSession session, Object message,
-                        ProtocolEncoderOutput out )
-            throws Exception
-    {
-        CharsetEncoder encoder = ( CharsetEncoder ) session.getAttribute( ENCODER );
-        if( encoder == null )
-        {
-            encoder = charset.newEncoder();
-            session.setAttribute( ENCODER, encoder );
-        }
-        
-        String value = message.toString();
-        ByteBuffer buf = ByteBuffer.allocate( value.length() ).setAutoExpand( true );
-        buf.putString( value, encoder );
-        if( buf.position() > maxLineLength )
-        {
-            throw new IllegalArgumentException( "Line length: " + buf.position() );
-        }
-        buf.putString( delimiter.getValue(), encoder );
-        buf.flip();
-        out.write( buf );
-    }
-
-    public void dispose() throws Exception
-    {
-    }
+	private final Charset charset;
+	private final LineDelimiter delimiter;
+	private int maxLineLength = Integer.MAX_VALUE;
+
+	public TextLineEncoder()
+	{
+		this( Charset.defaultCharset(), LineDelimiter.UNIX );
+	}
+
+	public TextLineEncoder( LineDelimiter delimiter )
+	{
+		this( Charset.defaultCharset(), delimiter );
+	}
+
+	public TextLineEncoder( Charset charset )
+	{
+		this( charset, LineDelimiter.UNIX );
+	}
+
+	public TextLineEncoder( Charset charset, LineDelimiter delimiter )
+	{
+		if( charset == null )
+		{
+			throw new NullPointerException( "charset" );
+		}
+		if( delimiter == null )
+		{
+			throw new NullPointerException( "delimiter" );
+		}
+		if( LineDelimiter.AUTO.equals( delimiter ) )
+		{
+			throw new IllegalArgumentException( "AUTO delimiter is not allowed for encoder." );
+		}
+
+
+		this.charset = charset;
+		this.delimiter = delimiter;
+	}
+
+	/**
+	 * Returns the allowed maximum size of the encoded line.
+	 * If the size of the encoded line exceeds this value, the encoder
+	 * will throw a {@link IllegalArgumentException}.  The default value
+	 * is {@link Integer#MAX_VALUE}.
+	 */
+	public int getMaxLineLength()
+	{
+		return maxLineLength;
+	}
+
+	/**
+	 * Sets the allowed maximum size of the encoded line.
+	 * If the size of the encoded line exceeds this value, the encoder
+	 * will throw a {@link IllegalArgumentException}.  The default value
+	 * is {@link Integer#MAX_VALUE}.
+	 */
+	public void setMaxLineLength( int maxLineLength )
+	{
+		if( maxLineLength <= 0 )
+		{
+			throw new IllegalArgumentException( "maxLineLength: " + maxLineLength );
+		}
+
+		this.maxLineLength = maxLineLength;
+	}
+
+	public void encode( IoSession session, Object message,
+						ProtocolEncoderOutput out )
+			throws Exception
+	{
+		CharsetEncoder encoder = ( CharsetEncoder ) session.getAttribute( ENCODER );
+		if( encoder == null )
+		{
+			encoder = charset.newEncoder();
+			session.setAttribute( ENCODER, encoder );
+		}
+
+		String value = message.toString();
+		ByteBuffer buf = ByteBuffer.allocate( value.length() ).setAutoExpand( true );
+		buf.putString( value, encoder );
+		if( buf.position() > maxLineLength )
+		{
+			throw new IllegalArgumentException( "Line length: " + buf.position() );
+		}
+		buf.putString( delimiter.getValue(), encoder );
+		buf.flip();
+		out.write( buf );
+	}
+
+	public void dispose() throws Exception
+	{
+	}
 }

Modified: directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.java
URL: http://svn.apache.org/viewvc/directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.java?view=diff&rev=471457&r1=471456&r2=471457
==============================================================================
--- directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.java (original)
+++ directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpRequestDecoder.java Sun Nov  5 08:44:10 2006
@@ -6,16 +6,16 @@
  *  to you under the Apache License, Version 2.0 (the
  *  "License"); you may not use this file except in compliance
  *  with the License.  You may obtain a copy of the License at
- *  
+ *
  *    http://www.apache.org/licenses/LICENSE-2.0
- *  
+ *
  *  Unless required by applicable law or agreed to in writing,
  *  software distributed under the License is distributed on an
  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  *  KIND, either express or implied.  See the License for the
  *  specific language governing permissions and limitations
- *  under the License. 
- *  
+ *  under the License.
+ *
  */
 package org.apache.mina.example.httpserver.codec;
 
@@ -25,6 +25,7 @@
 import java.io.StringReader;
 import java.nio.charset.CharacterCodingException;
 import java.nio.charset.CharsetDecoder;
+import java.nio.charset.Charset;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -33,230 +34,229 @@
 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
 import org.apache.mina.filter.codec.demux.MessageDecoderAdapter;
 import org.apache.mina.filter.codec.demux.MessageDecoderResult;
-import org.apache.mina.util.CharsetUtil;
 
 /**
  * A {@link MessageDecoder} that decodes {@link HttpRequest}.
- * 
+ *
  * @author The Apache Directory Project (mina-dev@directory.apache.org)
  * @version $Rev$, $Date$
  */
 public class HttpRequestDecoder extends MessageDecoderAdapter
 {
-    private static final byte[] CONTENT_LENGTH = new String( "Content-Length:" )
-            .getBytes();
+	private static final byte[] CONTENT_LENGTH = new String( "Content-Length:" )
+			.getBytes();
 
-    private CharsetDecoder decoder = CharsetUtil.getDefaultCharset()
-            .newDecoder();
+	private CharsetDecoder decoder = Charset.defaultCharset()
+			.newDecoder();
 
-    private HttpRequestMessage request = null;
+	private HttpRequestMessage request = null;
 
-    public HttpRequestDecoder()
-    {
-    }
-
-    public MessageDecoderResult decodable( IoSession session, ByteBuffer in )
-    {
-        // Return NEED_DATA if the whole header is not read yet.
-        try
-        {
-            return messageComplete( in ) ? MessageDecoderResult.OK
-                    : MessageDecoderResult.NEED_DATA;
-        }
-        catch( Exception ex )
-        {
-            ex.printStackTrace();
-        }
-
-        return MessageDecoderResult.NOT_OK;
-    }
-
-    public MessageDecoderResult decode( IoSession session, ByteBuffer in,
-            ProtocolDecoderOutput out ) throws Exception
-    {
-        // Try to decode body
-        HttpRequestMessage m = decodeBody( in );
-
-        // Return NEED_DATA if the body is not fully read.
-        if( m == null )
-            return MessageDecoderResult.NEED_DATA;
-
-        out.write( m );
-
-        return MessageDecoderResult.OK;
-    }
-
-    private boolean messageComplete( ByteBuffer in ) throws Exception
-    {
-        int last = in.remaining() - 1;
-        if( in.remaining() < 4 )
-            return false;
-
-        // to speed up things we check if the Http request is a GET or POST
-        if( in.get( 0 ) == ( byte ) 'G' && in.get( 1 ) == ( byte ) 'E'
-                && in.get( 2 ) == ( byte ) 'T' )
-        {
-            // Http GET request therefore the last 4 bytes should be 0x0D 0x0A 0x0D 0x0A
-            return( in.get( last ) == ( byte ) 0x0A
-                    && in.get( last - 1 ) == ( byte ) 0x0D
-                    && in.get( last - 2 ) == ( byte ) 0x0A && in.get( last - 3 ) == ( byte ) 0x0D );
-        }
-        else if( in.get( 0 ) == ( byte ) 'P' && in.get( 1 ) == ( byte ) 'O'
-                && in.get( 2 ) == ( byte ) 'S' && in.get( 3 ) == ( byte ) 'T' )
-        {
-            // Http POST request
-            // first the position of the 0x0D 0x0A 0x0D 0x0A bytes
-            int eoh = -1;
-            for( int i = last; i > 2; i-- )
-            {
-                if( in.get( i ) == ( byte ) 0x0A
-                        && in.get( i - 1 ) == ( byte ) 0x0D
-                        && in.get( i - 2 ) == ( byte ) 0x0A
-                        && in.get( i - 3 ) == ( byte ) 0x0D )
-                {
-                    eoh = i + 1;
-                    break;
-                }
-            }
-            if( eoh == -1 )
-                return false;
-            for( int i = 0; i < last; i++ )
-            {
-                boolean found = false;
-                for( int j = 0; j < CONTENT_LENGTH.length; j++ )
-                {
-                    if( in.get( i + j ) != CONTENT_LENGTH[ j ] )
-                    {
-                        found = false;
-                        break;
-                    }
-                    found = true;
-                }
-                if( found )
-                {
-                    // retrieve value from this position till next 0x0D 0x0A
-                    StringBuilder contentLength = new StringBuilder();
-                    for( int j = i + CONTENT_LENGTH.length; j < last; j++ )
-                    {
-                        if( in.get( j ) == 0x0D )
-                            break;
-                        contentLength.append( new String( new byte[] { in
-                                .get( j ) } ) );
-                    }
-                    // if content-length worth of data has been received then the message is complete
-                    return( Integer.parseInt( contentLength.toString().trim() )
-                            + eoh == in.remaining() );
-                }
-            }
-        }
-
-        // the message is not complete and we need more data
-        return false;
-    }
-
-    private HttpRequestMessage decodeBody( ByteBuffer in )
-    {
-        request = new HttpRequestMessage();
-        try
-        {
-            request.setHeaders( parseRequest( new StringReader( in
-                    .getString( decoder ) ) ) );
-            return request;
-        }
-        catch( CharacterCodingException ex )
-        {
-            ex.printStackTrace();
-        }
-
-        return null;
-    }
-
-    private Map parseRequest( Reader is )
-    {
-        Map map = new HashMap();
-        BufferedReader rdr = new BufferedReader( is );
-
-        try
-        {
-            // Get request URL.
-            String line = rdr.readLine();
-            String[] url = line.split( " " );
-            if( url.length < 3 )
-                return map;
-
-            map.put( "URI", new String[] { line } );
-            map.put( "Method", new String[] { url[ 0 ].toUpperCase() } );
-            map.put( "Context", new String[] { url[ 1 ].substring( 1 ) } );
-            map.put( "Protocol", new String[] { url[ 2 ] } );
-            // Read header
-            while( ( line = rdr.readLine() ) != null && line.length() > 0 )
-            {
-                String[] tokens = line.split( ": " );
-                map.put( tokens[ 0 ], new String[] { tokens[ 1 ] } );
-            }
-
-            // If method 'POST' then read Content-Length worth of data
-            if( url[ 0 ].equalsIgnoreCase( "POST" ) )
-            {
-                int len = Integer.parseInt( ( ( String[] ) map
-                        .get( "Content-Length" ) )[ 0 ] );
-                char[] buf = new char[ len ];
-                if( rdr.read( buf ) == len )
-                {
-                    line = String.copyValueOf( buf );
-                }
-            }
-            else if( url[ 0 ].equalsIgnoreCase( "GET" ) )
-            {
-                int idx = url[ 1 ].indexOf( '?' );
-                if( idx != -1 )
-                {
-                    map.put( "Context", new String[] { url[ 1 ].substring( 1,
-                            idx ) } );
-                    line = url[ 1 ].substring( idx + 1 );
-                }
-                else
-                {
-                    line = null;
-                }
-            }
-            if( line != null )
-            {
-                String[] match = line.split( "\\&" );
-                for( int i = 0; i < match.length; i++ )
-                {
-                    String[] params = new String[ 1 ];
-                    String[] tokens = match[ i ].split( "=" );
-                    switch( tokens.length )
-                    {
-                    case 0:
-                        map.put( "@".concat( match[ i ] ), new String[] {} );
-                        break;
-                    case 1:
-                        map.put( "@".concat( tokens[ 0 ] ), new String[] {} );
-                        break;
-                    default:
-                        String name = "@".concat( tokens[ 0 ] );
-                        if( map.containsKey( name ) )
-                        {
-                            params = ( String[] ) map.get( name );
-                            String[] tmp = new String[ params.length + 1 ];
-                            for( int j = 0; j < params.length; j++ )
-                                tmp[ j ] = params[ j ];
-                            params = null;
-                            params = tmp;
-                        }
-                        params[ params.length - 1 ] = tokens[ 1 ].trim();
-                        map.put( name, params );
-                    }
-                }
-            }
-        }
-        catch( IOException ex )
-        {
-            ex.printStackTrace();
-        }
+	public HttpRequestDecoder()
+	{
+	}
+
+	public MessageDecoderResult decodable( IoSession session, ByteBuffer in )
+	{
+		// Return NEED_DATA if the whole header is not read yet.
+		try
+		{
+			return messageComplete( in ) ? MessageDecoderResult.OK
+				   : MessageDecoderResult.NEED_DATA;
+		}
+		catch( Exception ex )
+		{
+			ex.printStackTrace();
+		}
+
+		return MessageDecoderResult.NOT_OK;
+	}
+
+	public MessageDecoderResult decode( IoSession session, ByteBuffer in,
+										ProtocolDecoderOutput out ) throws Exception
+	{
+		// Try to decode body
+		HttpRequestMessage m = decodeBody( in );
+
+		// Return NEED_DATA if the body is not fully read.
+		if( m == null )
+			return MessageDecoderResult.NEED_DATA;
+
+		out.write( m );
+
+		return MessageDecoderResult.OK;
+	}
+
+	private boolean messageComplete( ByteBuffer in ) throws Exception
+	{
+		int last = in.remaining() - 1;
+		if( in.remaining() < 4 )
+			return false;
+
+		// to speed up things we check if the Http request is a GET or POST
+		if( in.get( 0 ) == ( byte ) 'G' && in.get( 1 ) == ( byte ) 'E'
+			&& in.get( 2 ) == ( byte ) 'T' )
+		{
+			// Http GET request therefore the last 4 bytes should be 0x0D 0x0A 0x0D 0x0A
+			return( in.get( last ) == ( byte ) 0x0A
+					&& in.get( last - 1 ) == ( byte ) 0x0D
+					&& in.get( last - 2 ) == ( byte ) 0x0A && in.get( last - 3 ) == ( byte ) 0x0D );
+		}
+		else if( in.get( 0 ) == ( byte ) 'P' && in.get( 1 ) == ( byte ) 'O'
+				 && in.get( 2 ) == ( byte ) 'S' && in.get( 3 ) == ( byte ) 'T' )
+		{
+			// Http POST request
+			// first the position of the 0x0D 0x0A 0x0D 0x0A bytes
+			int eoh = -1;
+			for( int i = last; i > 2; i-- )
+			{
+				if( in.get( i ) == ( byte ) 0x0A
+					&& in.get( i - 1 ) == ( byte ) 0x0D
+					&& in.get( i - 2 ) == ( byte ) 0x0A
+					&& in.get( i - 3 ) == ( byte ) 0x0D )
+				{
+					eoh = i + 1;
+					break;
+				}
+			}
+			if( eoh == -1 )
+				return false;
+			for( int i = 0; i < last; i++ )
+			{
+				boolean found = false;
+				for( int j = 0; j < CONTENT_LENGTH.length; j++ )
+				{
+					if( in.get( i + j ) != CONTENT_LENGTH[ j ] )
+					{
+						found = false;
+						break;
+					}
+					found = true;
+				}
+				if( found )
+				{
+					// retrieve value from this position till next 0x0D 0x0A
+					StringBuilder contentLength = new StringBuilder();
+					for( int j = i + CONTENT_LENGTH.length; j < last; j++ )
+					{
+						if( in.get( j ) == 0x0D )
+							break;
+						contentLength.append( new String( new byte[] { in
+								.get( j ) } ) );
+					}
+					// if content-length worth of data has been received then the message is complete
+					return( Integer.parseInt( contentLength.toString().trim() )
+							+ eoh == in.remaining() );
+				}
+			}
+		}
+
+		// the message is not complete and we need more data
+		return false;
+	}
+
+	private HttpRequestMessage decodeBody( ByteBuffer in )
+	{
+		request = new HttpRequestMessage();
+		try
+		{
+			request.setHeaders( parseRequest( new StringReader( in
+					.getString( decoder ) ) ) );
+			return request;
+		}
+		catch( CharacterCodingException ex )
+		{
+			ex.printStackTrace();
+		}
+
+		return null;
+	}
+
+	private Map parseRequest( Reader is )
+	{
+		Map map = new HashMap();
+		BufferedReader rdr = new BufferedReader( is );
+
+		try
+		{
+			// Get request URL.
+			String line = rdr.readLine();
+			String[] url = line.split( " " );
+			if( url.length < 3 )
+				return map;
+
+			map.put( "URI", new String[] { line } );
+			map.put( "Method", new String[] { url[ 0 ].toUpperCase() } );
+			map.put( "Context", new String[] { url[ 1 ].substring( 1 ) } );
+			map.put( "Protocol", new String[] { url[ 2 ] } );
+			// Read header
+			while( ( line = rdr.readLine() ) != null && line.length() > 0 )
+			{
+				String[] tokens = line.split( ": " );
+				map.put( tokens[ 0 ], new String[] { tokens[ 1 ] } );
+			}
+
+			// If method 'POST' then read Content-Length worth of data
+			if( url[ 0 ].equalsIgnoreCase( "POST" ) )
+			{
+				int len = Integer.parseInt( ( ( String[] ) map
+						.get( "Content-Length" ) )[ 0 ] );
+				char[] buf = new char[ len ];
+				if( rdr.read( buf ) == len )
+				{
+					line = String.copyValueOf( buf );
+				}
+			}
+			else if( url[ 0 ].equalsIgnoreCase( "GET" ) )
+			{
+				int idx = url[ 1 ].indexOf( '?' );
+				if( idx != -1 )
+				{
+					map.put( "Context", new String[] { url[ 1 ].substring( 1,
+																		   idx ) } );
+					line = url[ 1 ].substring( idx + 1 );
+				}
+				else
+				{
+					line = null;
+				}
+			}
+			if( line != null )
+			{
+				String[] match = line.split( "\\&" );
+				for( int i = 0; i < match.length; i++ )
+				{
+					String[] params = new String[ 1 ];
+					String[] tokens = match[ i ].split( "=" );
+					switch( tokens.length )
+					{
+					case 0:
+						map.put( "@".concat( match[ i ] ), new String[] {} );
+						break;
+					case 1:
+						map.put( "@".concat( tokens[ 0 ] ), new String[] {} );
+						break;
+					default:
+						String name = "@".concat( tokens[ 0 ] );
+						if( map.containsKey( name ) )
+						{
+							params = ( String[] ) map.get( name );
+							String[] tmp = new String[ params.length + 1 ];
+							for( int j = 0; j < params.length; j++ )
+								tmp[ j ] = params[ j ];
+							params = null;
+							params = tmp;
+						}
+						params[ params.length - 1 ] = tokens[ 1 ].trim();
+						map.put( name, params );
+					}
+				}
+			}
+		}
+		catch( IOException ex )
+		{
+			ex.printStackTrace();
+		}
 
-        return map;
-    }
+		return map;
+	}
 }

Modified: directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.java
URL: http://svn.apache.org/viewvc/directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.java?view=diff&rev=471457&r1=471456&r2=471457
==============================================================================
--- directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.java (original)
+++ directory/branches/mina/1.2/example/src/main/java/org/apache/mina/example/httpserver/codec/HttpResponseEncoder.java Sun Nov  5 08:44:10 2006
@@ -6,21 +6,22 @@
  *  to you under the Apache License, Version 2.0 (the
  *  "License"); you may not use this file except in compliance
  *  with the License.  You may obtain a copy of the License at
- *  
+ *
  *    http://www.apache.org/licenses/LICENSE-2.0
- *  
+ *
  *  Unless required by applicable law or agreed to in writing,
  *  software distributed under the License is distributed on an
  *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  *  KIND, either express or implied.  See the License for the
  *  specific language governing permissions and limitations
- *  under the License. 
- *  
+ *  under the License.
+ *
  */
 package org.apache.mina.example.httpserver.codec;
 
 import java.nio.charset.CharacterCodingException;
 import java.nio.charset.CharsetEncoder;
+import java.nio.charset.Charset;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -31,87 +32,86 @@
 import org.apache.mina.common.IoSession;
 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
 import org.apache.mina.filter.codec.demux.MessageEncoder;
-import org.apache.mina.util.CharsetUtil;
 
 /**
  * A {@link MessageEncoder} that encodes {@link HttpResponseMessage}.
- * 
+ *
  * @author The Apache Directory Project (mina-dev@directory.apache.org)
  * @version $Rev$, $Date$
  */
 public class HttpResponseEncoder implements MessageEncoder
 {
-    private static final Set TYPES;
+	private static final Set TYPES;
 
-    static
-    {
-        Set types = new HashSet();
-        types.add( HttpResponseMessage.class );
-        TYPES = Collections.unmodifiableSet( types );
-    }
-
-    private static final byte[] CRLF = new byte[] { 0x0D, 0x0A };
-
-    public HttpResponseEncoder()
-    {
-    }
-
-    public void encode( IoSession session, Object message,
-            ProtocolEncoderOutput out ) throws Exception
-    {
-        HttpResponseMessage msg = ( HttpResponseMessage ) message;
-        ByteBuffer buf = ByteBuffer.allocate( 256 );
-        // Enable auto-expand for easier encoding
-        buf.setAutoExpand( true );
-
-        try
-        {
-            // output all headers except the content length
-            CharsetEncoder encoder = CharsetUtil.getDefaultCharset()
-                    .newEncoder();
-            buf.putString( "HTTP/1.1 ", encoder );
-            buf.putString( String.valueOf( msg.getResponseCode() ), encoder );
-            switch( msg.getResponseCode() )
-            {
-            case HttpResponseMessage.HTTP_STATUS_SUCCESS:
-                buf.putString( " OK", encoder );
-                break;
-            case HttpResponseMessage.HTTP_STATUS_NOT_FOUND:
-                buf.putString( " Not Found", encoder );
-                break;
-            }
-            buf.put( CRLF );
-            for( Iterator it = msg.getHeaders().entrySet().iterator(); it
-                    .hasNext(); )
-            {
-                Entry entry = ( Entry ) it.next();
-                buf.putString( ( String ) entry.getKey(), encoder );
-                buf.putString( ": ", encoder );
-                buf.putString( ( String ) entry.getValue(), encoder );
-                buf.put( CRLF );
-            }
-            // now the content length is the body length
-            buf.putString( "Content-Length: ", encoder );
-            buf.putString( String.valueOf( msg.getBodyLength() ), encoder );
-            buf.put( CRLF );
-            buf.put( CRLF );
-            // add body
-            buf.put( msg.getBody() );
-            //System.out.println("\n+++++++");
-            //for (int i=0; i<buf.position();i++)System.out.print(new String(new byte[]{buf.get(i)}));
-            //System.out.println("\n+++++++");
-        }
-        catch( CharacterCodingException ex )
-        {
-            ex.printStackTrace();
-        }
-
-        buf.flip();
-        out.write( buf );
-    }
-
-    public Set getMessageTypes()
-    {
-        return TYPES;
-    }
+	static
+	{
+		Set types = new HashSet();
+		types.add( HttpResponseMessage.class );
+		TYPES = Collections.unmodifiableSet( types );
+	}
+
+	private static final byte[] CRLF = new byte[] { 0x0D, 0x0A };
+
+	public HttpResponseEncoder()
+	{
+	}
+
+	public void encode( IoSession session, Object message,
+						ProtocolEncoderOutput out ) throws Exception
+	{
+		HttpResponseMessage msg = ( HttpResponseMessage ) message;
+		ByteBuffer buf = ByteBuffer.allocate( 256 );
+		// Enable auto-expand for easier encoding
+		buf.setAutoExpand( true );
+
+		try
+		{
+			// output all headers except the content length
+			CharsetEncoder encoder = Charset.defaultCharset()
+					.newEncoder();
+			buf.putString( "HTTP/1.1 ", encoder );
+			buf.putString( String.valueOf( msg.getResponseCode() ), encoder );
+			switch( msg.getResponseCode() )
+			{
+			case HttpResponseMessage.HTTP_STATUS_SUCCESS:
+				buf.putString( " OK", encoder );
+				break;
+			case HttpResponseMessage.HTTP_STATUS_NOT_FOUND:
+				buf.putString( " Not Found", encoder );
+				break;
+			}
+			buf.put( CRLF );
+			for( Iterator it = msg.getHeaders().entrySet().iterator(); it
+					.hasNext(); )
+			{
+				Entry entry = ( Entry ) it.next();
+				buf.putString( ( String ) entry.getKey(), encoder );
+				buf.putString( ": ", encoder );
+				buf.putString( ( String ) entry.getValue(), encoder );
+				buf.put( CRLF );
+			}
+			// now the content length is the body length
+			buf.putString( "Content-Length: ", encoder );
+			buf.putString( String.valueOf( msg.getBodyLength() ), encoder );
+			buf.put( CRLF );
+			buf.put( CRLF );
+			// add body
+			buf.put( msg.getBody() );
+			//System.out.println("\n+++++++");
+			//for (int i=0; i<buf.position();i++)System.out.print(new String(new byte[]{buf.get(i)}));
+			//System.out.println("\n+++++++");
+		}
+		catch( CharacterCodingException ex )
+		{
+			ex.printStackTrace();
+		}
+
+		buf.flip();
+		out.write( buf );
+	}
+
+	public Set getMessageTypes()
+	{
+		return TYPES;
+	}
 }



Mime
View raw message